text:
Q: How can I explain that data won't cross threads? Not sure if this is really the best place to ask.
Let's say my code looks something like this
void StartThreads()
{
    Thread thread1 = new Thread(DoWork);
    thread1.Start(data1);
    Thread thread2 = new Thread(DoWork);
    thread2.Start(data2);
}

void DoWork(object o)
{
    WorkerClass c = new WorkerClass();
    c.DoWork(o);
}

How best can I explain that random data from the thread1 instance of c isn't going to get into the data of the thread2 instance of c?
data1 and data2 are separate instances of NamedPipeServerStream.
Note that the DoWork() function itself has for quite a while been multi-threaded and has never jumbled data between the classes involved there, but I guess adding another layer here is scary for the higher-ups, since data getting jumbled around could mean very large fines.

A: Good luck with the higher ups, but here is the technical reason why this is OK.
Regardless of threading, when you call a function, it gets a brand new stack frame. That is, all of its local variables and arguments get a specific piece of memory that is specific to that function call. Any other calls to this function will not touch that memory.
Just calling the function on a new thread does not change this behavior, so your arguments are "safe" when called in the provided code (assuming they are just data and don't depend on a shared resource or each other of course). This is true because a new thread is still a function invocation (albeit on a different thread).
If those two streams are in any way related, then you have a race condition and a problem waiting to happen, so make sure they are truly not shared/dependent.
In other words, assuming no shared resources, the code is the same as writing (thanks to @ChrisHaas):
DoWork(data1);
DoWork(data2);

Which no sane programmer would object to as far as data modification goes.


text:
Q: Import data from async function I'm dealing with a project that uses AWS Cognito. There are some configuration params that needs to be fetched from server with an API call. I keep the API call in a config.js file and use async/await to get response from server like  this
const getCognitoConfigs = async () => {
const res = await axios.get(`${apiurl.apiurl}/logininfo`);
console.log(res.data);
return res.data;
};

export default getCognitoConfigs;

And in my index.js (where I set up Cognito), I import the function from config.js file
import getCognitoConfigs from "./config";
const configs = getCognitoConfigs();

Amplify.configure({
    Auth: {
        mandatorySignIn: true,
        region: configs.cognito.region,
        userPoolId: configs.cognito.user_pool,
        userPoolWebClientId: configs.cognito.app_client_id
    }
});

The problem is async await does not stop the program execution so I'm getting 'configs' as undefined. Are there anyways that I can make the app stop until the api call has resolved? Thanks.

A: If you want to use async/await, you have to wrap index.js in an asynchronous function and add
await getCognitoConfigs();

or you can use promise like
getCognitoConfigs().then(res => Amplify.configure({...}))

redpajama_set_name: RedPajamaStackExchange


text:
Q: responsive "background-image" not automatically resizing with orientation change css iOS I have an image in the dom that is sized based on the height of the screen. It works perfectly on all browsers and devices (at least all that I'm concerned about), except for Safari iOS 7.
In Safari iOS, the image loads correctly for the given orientation. However, when the orientation changes (portrait to landscape or landscape to portrait) the image doesn't resize based on the new height. (Note that it does resize as expected on Android devices.) THEN when you rotate back to the original orientation the image does resize, but for the orientation you just changed from - so it's now wrong!
I also noticed that if the image is incorrect and (without changing orientation) I interact with an element on the page which would also render based on the screen height, it loads fine AND the image in question is resized to the correct size.
I think what I'd like to do at this point is to force a css reload upon orientation change, unless there is a better solution. Would I need to do this in javascript? or can it be done in the css?
The following is my relevant css:
    position: relative;
    height: 90vh;
    z-index: -3;
    bottom: 50px;
    background-size: auto 100%;
    background-position: 30%;
    background-repeat: no-repeat;
    background-image:image-url("the/path/to/my/image.jpg");

*Note: I cannot use jQuery, and this is an angularJS app

A: I'm not 100% clear on precisely what you're looking for, but could you use a CSS media query to detect portrait vs. landscape? This way you could perhaps get better precision with your backgrounds when the orientation changes.
@media only screen and (orientation: landscape) {
  background-size: auto 100%;
}
@media only screen and (orientation: portrait) {
  background-size: 100% auto;
}

Without additional specifics about your issue though, it's hard for me to say, but maybe that might point you in the right direction.


text:
Q: collapsing toolbar layout like google play store i want to make a collapsing toolbar layout like google play store. like this:
https://sendvid.com/ugjspx8r
and here is my layout:
http://sendvid.com/s4mx3xem
how can i do that with new android support library?
here is my layout xml file:
<android.support.design.widget.CoordinatorLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusableInTouchMode="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/seffafCollapsingToolbarLayout"
            android:layout_width="match_parent"
            android:layout_height="240dp"
            app:expandedTitleMarginEnd="164dp"
            app:expandedTitleMarginStart="148dp"
            app:layout_scrollFlags="scroll|enterAlwaysCollapsed">

            <ImageView
                android:id="@+id/header"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
                android:src="@drawable/haber_icerik_resim"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/haber_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:theme="@style/ToolbarColoredBackArrow"
                app:layout_collapseMode="pin"
                app:layout_scrollFlags="scroll|enterAlways"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/newsRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        android:clickable="true"
        android:background="@color/mainBackground"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

A: Here is working code, what you need.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/detail_backdrop_height"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:layout_scrollFlags="scroll|enterAlways|snap"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <fragment
        android:name="com.support.android.designlibdemo.CheeseListFragment"
        class="com.support.android.designlibdemo.CheeseListFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

And here is Activity
public class SampleActivity extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }
}

I hope this will solve your problem. Please let me know, if you need further help!!!

A: View inside CollapsingToolbarLayout no need to set app:layout_scrollFlags. No effect.
Base on my code,  change app:layout_scrollFlags in CollapsingToolbarLayout to
"app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
and set minHeight for it.
As your toolbar is "pin", so enterAlwaysCollapsed will call it when you scroll down.
<android.support.design.widget.CoordinatorLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/seffafCollapsingToolbarLayout"
        android:layout_width="match_parent"
        android:layout_height="240dp"
        android:minHeight="?attr/actionBarSize"
        app:expandedTitleMarginEnd="164dp"
        app:expandedTitleMarginStart="148dp"
        app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed">

        <ImageView
            android:id="@+id/header"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/haber_icerik_resim"
            android:fitsSystemWindows="true"
            android:scaleType="centerCrop"
            app:layout_collapseMode="parallax" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/haber_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:theme="@style/ToolbarColoredBackArrow"
            app:layout_collapseMode="pin"/>

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<android.support.v7.widget.RecyclerView
    android:id="@+id/newsRecyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical"
    android:clickable="true"
    android:background="@color/mainBackground"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

A: I implemented this as shown below. I couldn't find any better solution.
public enum State {
    EXPANDED,
    COLLAPSED,
}
mCurrentState = State.EXPANDED;
 Boolean toolbarIsTransparent = true;
// Calculate ActionBar height
    TypedValue tv = new TypedValue();
    int actionBarHeight = 0;
    if (mContext.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
        actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
    }

    AppBarLayout appBarLayout = (AppBarLayout) rootView.findViewById(R.id.appbar_layout);
    final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) rootView.findViewById(R.id.collapsible_toolbar);
    if (appBarLayout != null) {
        final int finalActionBarHeight = actionBarHeight;
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                if (i == 0) {
                    mCurrentState = State.EXPANDED;
                } else if (Math.abs(i) >= appBarLayout.getTotalScrollRange()) {
                    mCurrentState = State.COLLAPSED;
                }
                if ((collapsingToolbarLayout.getHeight() + i <= finalActionBarHeight) && mCurrentState.equals(State.COLLAPSED)) {
                    toolbar.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
                    toolbarIsTransparent = false;
                } else if (!toolbarIsTransparent) {
                    mCurrentState = State.EXPANDED;
                    toolbar.setBackgroundColor(ContextCompat.getColor(mContext, android.R.color.transparent));
                    toolbarIsTransparent = true;
                }
            }
        });
    }

and xml code is `
<android.support.design.widget.CollapsingToolbarLayout
    android:id="@+id/collapsible_toolbar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        android:orientation="vertical"
        android:src="@drawable/image"
        app:layout_collapseMode="parallax" />

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>

`

A: I tried almost all the answers to get the same functionality but got it working after a little tweaking.
It works similar to PlayStore where the Toolbar title appears only when it is collapsed and hidden otherwise.
Here is the layout
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="@color/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
            app:titleEnabled="false">

            <ImageView
                android:id="@+id/banner"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/image"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <!--Add your views here-->
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:fadeScrollbars="true"
        android:paddingTop="10dp"
        android:scrollbarStyle="insideOverlay"
        android:scrollbars="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

Add this code to the onCreate method of your Activity
private Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
private AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
    appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            if (verticalOffset <= -appBarLayout.getTotalScrollRange() + toolbar.getHeight()) {
                //Toolbar Collapsed
                toolbar.setTitle("Your title here");
            } else {
                //Toolbar Expanded
                toolbar.setTitle(" ");
            }
        }
    });

Few things to note

*

*Do not set any background to Toolbar else it will overlap your view

*contentScrim attribute will take care of the Toolbar color on collapse

*titleEnabled attribute is set to false to disable collapsing title effect

I hope this will be useful to people looking for the same behaviour.
Please let me know how it works out. Cheers!

A: Here is my implementation
Layout Code

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsingToolbarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed">

        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:scaleType="centerCrop"
            android:layout_gravity="center_horizontal|top"
            app:layout_collapseMode="parallax" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:theme="@style/ThemeOverlay.AppCompat.Light" />

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <!-- YOUR LAYOUT CODE --->

</android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>

Java Code
inside onCreateView
if (toolbar != null) {
            ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
            ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

// in your code
img.setImageResource(R.drawable.img1);
collapsingToolbarLayout.setTitle("<TITLE>");

A: Just add the bellow tag in CollapsingToolbarLayout
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"

and remove the above same tag in ImageView, its not required there.
And it works exaclty like you see in google play
Hope this helps to someone :)


text:
Q: Facebook share button re sizes by itself my Facebook share button worked perfectly until a few days ago when it started re sizing itself and refusing to open, any clues as to what is causing this?\
here's my js script for the pop-up window
function fbShare(url, title, descr, image, winWidth, winHeight) {
    var winTop = (screen.height / 2) - (winHeight / 2);
    var winLeft = (screen.width / 2) - (winWidth / 2);
    window.open('http://www.facebook.com/sharer.php?s=100&p[title]=' + title + '&p[summary]=' + descr + '&p[url]=' + url + '&p[images][0]=' + image, 'sharer', 'top=' + winTop + ',left=' + winLeft + ',toolbar=0,status=0,width=' + winWidth + ',height=' + winHeight);
}

here's the link
Share

if this looks familiar it's cause I got it here jsfiddle


text:
Q: GAE dev_appserver build system for Sublime Text 3 I'm trying to modify this answer to instead use the development (local) app server, and I'm using Sublime Text 3 instead of 2, if there's any difference.
My current GAE_dev.sublime-build is:
{
    "working_dir": "$project_path",
    "cmd": ["sh", "-c", "dev_appserver.py", "--port=9090"],
    "encoding": "UTF-8",
    "shell": true
}

And the only output is:
[Finished in 0.1s]

Visiting localhost:9090 yields no success.
When I run (what I think is) the same command in Terminal:
$ cd /project/path
$ dev_appserver.py --port=9090

there's a load of output, the app is running at :9090, and due to the way in which dev_appserver.py works, it keeps running - which makes me highly suspicious of Sublime's 'Finished'.
I tried restarting Sublime as per this self-answered question, but it made no difference.

What crucial step have I missed?
Or even just to give me a kick in the right direction - is there a way to see Sublime's raw interaction with bash? So I can see exactly what command it issues, and what the response is?


text:
Q: Find Volume of a Wineglass - a Slice A spherical wineglass, known diameter, is brim full of wine. What is the width of any vertical parallel slice with a volume of 1/4 of the wine?
Assume that the height of the wineglass is known.

A: Use the disk (washer) method for the function $f(x):=\sqrt{R^2-x^2}$  on the interval $[x_0,x_0+h]\subset[-R,R]$ to get an equation satisfied by $x_0$ and $h$.


text:
Q: How to initiate movement and fix arrays in brackets program
I'm currently working on a basic snake game using Brackets which contains HTML5, CSS, and JS functions. I'm a self taught coder and recently I've hit a road block with the JavaScript functions. I'm trying to initiate the snake movement (which I am totally lost on and that code is beyond help) and make an array that contains 5 body segments at the start of the game. From there, I should be able to figure out the movements and adding on more body segments to the array.
Below is my code so far, I know it's a bit messy, this is my first attempt at a full working game, the most I've really done before this is create posters an a text-based adventure game.
SnakeBody is the array that I have set up to hold the body segments of the snake.
ctx is a shorten form of context where its stemming from "theCanvas.getContext("2d")" sequence when initiating the canvas object.
cw is my own shortened form of "theCanvas.width" to describe the width of the canvas, and ch is also shortened from "theCanvas.height" to describe the height of the canvas.
My plan for this segment of code was to use genSnakeBody() to generate the next portion of the snake's body, and then use the drawSnake() function for draw the image of the snake on the canvas.
Any and all help is greatly appreciated!!
function genSnakeBody() {
    var BodyHeight = 15 // Height of the snake's body
    var BodyWidth = 15 //Width of the snake's body
    var BodySpeed = 10 //Speed of the snake

    var body = {
        x: cw / 2 - (BodyHeight / 2),
        y: ch / 2 - (BodyWidth / 2),
        h: BodyHeight,
        w: BodyWidth,
        color: "green",
        speed: BodySpeed
    };
    var length = 5;

    SnakeBody.push(body)
}

function drawSnake() {
    var length = 5
    for (i = 0; i < SnakeBody.length; i++) {
        ctx.beginPath();
        ctx.fillStyle = SnakeBody[i].color;
        ctx.fillRect(SnakeBody[i].x, SnakeBody[i].y, SnakeBody[i].w, SnakeBody[i].h);
        ctx.strokeRect(SnakeBody[i].x, SnakeBody[i].y, SnakeBody[i].w, SnakeBody[i].h);
        ctx.closePath();
    }
}

I was hoping that this would make a 5 segment snake when the page was loaded.
Instead I have a single box given the dimensions in the center of the screen, I don't know if the other boxes (if my code even allows for the other boxes) are underneath the one that I can see, or if they simply don't exist.
Like I said before, any and all help is greatly appreciated and I look forward to it!! Thank you so much if you took the time to read this and try to offer up a solution, if the code is that bad I'll try creating a cleaner version of what I have and attempt this problem from a different angle. Thank You!

A: Trying to keep the minimal amount of changes to you script here is a working code snippet:

var c = document.getElementById("canvas");
var cw = 200;
var ch = 200;
var ctx = c.getContext("2d");
var SnakeBody = []

function genSnakeBody(index) {
  var BodyHeight = 15; // Height of the snake's body
  var BodyWidth = 15; //Width of the snake's body
  var BodySpeed = 10; //Speed of the snake

  var body = {
    x: cw / 2 - (BodyHeight / 2) * index,
    y: ch / 2 - (BodyWidth / 2) * index,
    h: BodyHeight,
    w: BodyWidth,
    color: "green",
    speed: BodySpeed
  };

  SnakeBody.push(body)
}

function drawSnake() {
  var length = 5;
  for (var i = 0; i < length; i++) {
    genSnakeBody(i);
    ctx.beginPath();
    ctx.fillStyle = SnakeBody[i].color;
    ctx.fillRect(SnakeBody[i].x, SnakeBody[i].y, SnakeBody[i].w, SnakeBody[i].h);
    ctx.strokeRect(SnakeBody[i].x, SnakeBody[i].y, SnakeBody[i].w, SnakeBody[i].h);
    ctx.closePath();
  }
}

drawSnake();
<canvas id="canvas"></canvas>

Apart from the missing variables (which are some wild guess) here the few thing that were added:

*

*call genSnakeBody with an index so it can differenciate each body part when called from within the loop

*remove the variable length from genSnakeBody function that wasn't used

*Call genSnakeBody inside the drawSnake loop


text:
Q: Alarms app not working (Windows 8.1) I used the built-in Microsoft Alarms app regularly. Normally a small notification appears in the upper right and the alarm chimes.
But recently it has stopped working. The notification does not appear in the upper right and the chime does not go off. I've not knowingly modified any system settings and the volume is definitely working (have listened to music multiple times).
When I set up an alarm, a banner is displayed at the top of the screen which says Notifications will only appear if the PC is awake. My PC is on and I am working on it when I expect the alarm to go off, so this may not be important but I mention it in case this is relevant.
What might be causing the Alarms application to stop working?


text:
Q: git submodule has uncommited change but inside module nothing is changed I am not sure if I have followed the right procedure to set up my submodule. I think I initially did git add url, then git submodule init then git submodule update.
It seems that there is nothing in the submodule folder, then I find that the right command to do might be git submodule update --init which get me contents in submodule's folder, but in another situation, i still get nothing, so I went into the submodule's folder and executed git pull origin master, this time I got contents, but when i go back to the root project folder where the submodule lies in, I found when I run git status, there is uncommitted changes (but i did not change the submodule at all, I just pulled) something like  modified:   submodule name (untracked content)
, if I run git checkout ., the uncommitted changes does not disappear at all.
Anyone could show me what's wrong with the procedure and how should I solve the problem? (I do not want to have the uncommited changes since I did not change anything, and it seems that git submodule update --init does not work to get me the lastest commit from the submodule)
edit:
   If I go into the submodule folder and type
git log

I got
commit 268df2521e262d5ef1985db0e152cfd94542fe26 (HEAD -> master, origin/master, origin/HEAD)

If I go to the parent repository folder, and type git ls-tree -r -t HEAD | grep commit, I got
160000 commit 268df2521e262d5ef1985db0e152cfd94542fe26

It seems that the two sha are the same?


text:
Q: Why Did Scotty Not Go Insane? On the question about the transporters in Star Trek on whether the original person dies in the transporter, I provided this answer based on the text of the Writer's Guide for the series Star Trek: The Next Generation.  Much of the material in the Writer's Guide and Writer's Technical Manual from the series was later published as a technical guide to the Enterprise (NCC-1701-D).
One point I reference is that the episode Realm of Fear shows us the transport process from the point of view of a person being transported, in this case, Lt. Barclay.  During the entire process, Barclay stays conscious and sees other people trapped in the pattern buffer.  These people in the buffer approach Barclay, again showing that someone in the beaming process is aware and able to think and act.
In the episode Relics the crew of the Enterprise (1701-D) rescues Scotty after he has been trapped in a pattern buffer for 75 years.  From what we see in Realm of Fear, people are conscious during that process, meaning Scotty was in a buffer, with nothing to do, and nobody to talk to for 75 years.
(While Scotty had also placed another person in the pattern buffer, he wasn't aware if that person survived or not, indicating there was either no interaction or that Scotty had no way to be aware when that person was no longer conscious.)
Seventy five years is a long time to be alone and with no other human interaction.
How did he survive this without losing his sanity or showing other serious ill effects mentally?

A: While within the pattern buffer, time is not perceived.  Barclay was experiencing the glowy part when dematerializing/rematerializing.  Since Scotty was fully within the pattern buffer the entire time, he did not perceive any passage of time.
I give you ENT 2x10, Vanishing Point, as a reference.  Hoshi was trapped within the pattern buffer for about 8.3 seconds, and according to Malcom, her consciousness was only active for final couple of seconds while it was being fixed.  And at neither end of the transport was her experience interrupted significantly enough to suspect something went wrong while being put in/taken out of the pattern buffer, which explains why Barclay experienced one continuous event.

A: I see two possible explanations: One possible explanation is that what we see in Realm of Fear is exaggerated or changed for dramatic effect in the episode and a human does in fact not experience the transportation process in the way Barclay did. Note that they actually stated that his experience differs from normal beams due to the special conditions the transporter system was exposed to. This allows room to interpret the fact that he seems concious to be one of the side effects.

A: Another explanation is that Scotty (being a genius engineer!) knew this would happen and modified the transporter so he would not be concious until freed. He did not anticipate for himself to be in there for 75 years, but he expected it to be a while (I think at least days, if not even weeks).

A: Another factor to keep in mind: Scotty had rigged the transporter to repeatedly cycle his pattern through the buffer, to keep his pattern intact - i.e unchanged - while he was suspended in transport.  The state of his mind as a brain-state was part of that pattern.  Therefore the transporter would have continually reset his mind to its state from the moment transport began.  He would have been unable to perceive the passage of time because his thought processes would have been unable to progress.

A: It seems highly likely that Scotty activated the transporter's 'Neural Paralyzer Control'. This would have the effect of rendering him unconscious during the transport process and preventing him from going doolally while waiting around to get untransported.

A: The most likely cause I can think of is that while the transport process seems contiguous from the perspective of the person being transported, it is very likely that during at least one stage of the transport process the person is suspended and unaware. It is most probably this stage that Scotty locked the transporter system in when he attempted to save himself in Relics.

A: In addition to the other answers, keep in mind that the transporter used on the Jenolen is at least 75 years older than the one on the Enterprise.  Perhaps remaining conscious during transport is an improvement that was made at some point between the two time periods.
We know from Scotty's confusion when he comes out of the transporter that he has no idea how much time has passed.  He believes that Kirk may pulled the Enterprise out of mothballs to rescue him.  This alone should indicate that Scotty wasn't aware of the passage of time while trapped in the buffer.

A: Perhaps Mr. Scott just has amazing mental constitution. After all that time, he still remembered the English language -- assuming he was in fact conscious, which I doubt.

A: I don't know if he went insane as such, but he was a bit mixed up. He knew Kirk had been lost on the Enterprise B,he'd been there with Chekov,  but said " I bet it was Jim Kirk himself who got the old girl outta mothballs to rescue me!" Realistically, he'd have known that was impossible, wouldn't he?

A: Let's say he was conscious. There would be no physical changes, such as chemical imbalance. Therefore, he would always have the same state of mind. I'm surprised that he didn't invent a ton of stuff in theory.

A: I think there is a lot of evidence that in real life our perception of time (and in fact all perception) is based on electrochemical processes. How those processes proceed if one is in a pattern buffer is anyone's guess - how Scotty would have been conscious as a pattern even is impossible to understand.
But it is doubtful that he would have perceived the years passing in the pattern buffer as he would have had he been simply imprisoned for all those years in a physical body.


text:
Q: jpeg file not recognized as image in laravel I have made a validation for image field as
'avatar' => 'nullable|image|mimes:jpeg,png,jpg|max:1000',

it works for png image but fails if i upload jpeg image with message The avatar must be an image. Any thoughts?
Here is form view
    {!! Form::open(['route'=>['admin.myprofile.update',$admin->id],'method'=>'put','files'=>true]) !!}
...
            {!! Form::file('avatar', ['class' => 'dropify btn-warning','data-default-file'=>$admin->avatar?asset($admin->avatar):'']) !!}
..
    {!! Form::close() !!}

A: I think your rule validation is overlap each other you can change it to this and see the result:
'avatar' => 'nullable|mimes:mimes:jpeg,jpg,png,gif|max:1000'

A: The image validator is kind of buggy here. Avoid using this validator. In the accepted answer even if you remove the mimes types validator and use the image validator only as following
'avatar' => 'nullable|image|max:1000'

Then for some jpeg images, it will work fine but for most images, it will not work.
Correction for the accepted answer. There is a typo there as mimes: is repeated twice. Bellow is the corrected code
'avatar' => 'nullable|mimes:jpeg,jpg,png,gif|max:1000'


text:
Q: jquery animate won't trigger I am trying to make a image move up at the moment you scrolled 100 or more pixels. When I turn on the alert the alert does trigger, but the animation doesn't. I can't seem to figure out where it goes wrong tho.
Could it be cause I try to change a ::before class?

$(document).ready(function(){
 $(window).scroll(function() {
        if ($(this).scrollTop() >= 100 ) {
   //alert('scrolled');
            $('.flipje_pas::before').animate({top: -300}, 1000);
        }
    });
});


text:
Q: Diablo 3: Monster kills only on last hit? + drop question
Possible Duplicate:
How does X% Chance of Finding Magical Items work for a party?

i was wondering if you get your mob killcount increased by:
last hit?
damage inflichted but not last hit?
just standing near a kill?
Why i came up with it, i play with a mate and he does the damage and i do more tanking and less damage.
He got 4 legendaries in 3 runs and me got 0. Which was then his 15-20th in the whole game time.
While i only got 4 legendaries during the whole game in almost the same time.
During the game i always got 150-200% mf more than him 348% my peak value.
So we came up with the idea that last hitting minions affects the drop rate.
Or is it really only luck?


text:
Q: context switch in the source The folowing source is an queue class :
template<typename T>
class mpmc_bounded_queue
{
public:
    bool enqueue(T const& data)
    {
        cell_t* cell;
        size_t pos  ;
        for (;;)
        {
            pos = enqueue_pos_ ;
            cell = &buffer_[pos & buffer_mask_];
            size_t seq = cell->sequence_;
            intptr_t dif = (intptr_t)seq - (intptr_t)pos;
            if (dif == 0)
            {
                //spot A
                if (__sync_bool_compare_and_swap(&enqueue_pos_,pos,pos+1) )
                    break;
            } else if (dif < 0)
            {
                return false;
            }else{
                pos = enqueue_pos_;
            }
        }
        // spot B
        cell->data_ = data;
        cell->sequence_ = pos + 1 ;
        return true;
    } //enqueue
private:
    struct cell_t
    {
        size_t     sequence_;
        T          data_;
    };
} ;

In RedHat Enterprise Linux 7.0 x86_64 , Is it possible that context switch
happened in finishing __sync_bool_compare_and_swap ( spot A) but not yet to
execute cell->data_ = data (spot B) ?
I've told that context switch would happened in like recv , send , usleep,
something to do with I/O function , in this case , while many threads execute
enqueue , there is not possible that there exist an possibility a thread finish
__sync_bool_compare_and_swap return true but at this important moment it is context switch out before it execute cell->data_ = data , Is it true ?
or context switch was not possible happened between spot A  and spot B  ?

A:
Is it true ?

Yes: a context switch can happen at any point between A and B.
That shouldn't affect the algorithm though, which appears to be correct: if __sync_bool_compare_and_swap returned true, then you have atomically reserved the cell at pos, and nobody else will interfere with that cell, so whether the context switch happens between A and B or not is irrelevant.


text:
Q: VBA Excel - SQL query via ADO returns infinite null recordset I finally have my code where it needs to be, executing as intended on my machine and returning the result I expect from a number of SQL servers. Problem is a portion of the code only works on my machine. We are running the Excel spreadsheet with specific credentials, (using run as a different user), however the code below only executes properly on my machine (the machine used to develop the code).
There are four SQL DBs being hit, on four different SQL servers. The first three function as intended on other people's machines when they run this script. The fourth SQL call enters an infinite loop on the while not EOF line. The SQL query returns an infinite recordset of null values, regardless of whether or not the query would have normally returned any data. This does not occur on my machine, but happens on others we have tested. One difference between this call and the others is the connection string. The other servers are connected using the following connection string syntax:
Provider=SQLOLEDB.1;Integrated Security=SSPI;Initial Catalog=XXXX;Data Source=XXXX;
The SQL query in question (as you can see below) uses this syntax:
Driver={SQL Server Native Client 11.0};Server=XXXX;Database=XXXX;Trusted_Connection=yes;
This connection string is the only one that works with this version of SQL server.
What do you think could cause this query to return an infinite null recordset every time its called on other people's machines, but not on mine?
WE have checked the version of Excel, OS, hardware architecture, patches, access to SQL server, running the SQL query via SSMS, installed SQL related components - even had other people log into my machine and run the Spreadsheet with the necessary credentials. Works on my machine only.
    'Variables
    Set objMyConn = New ADODB.Connection
    Set objMyCmd = New ADODB.Command
    Set objMyRecordset = New ADODB.Recordset

    'Open connection
    objMyConn.ConnectionString = "Driver={SQL Server Native Client 11.0};Server=XXXX;Database=XXXX;Trusted_Connection=yes;"
    objMyConn.Open

    'Set and execute SQL command
    Set objMyCmd.ActiveConnection = objMyConn

    objMyCmd.CommandText = "<Valid SQL Statement>"

    objMyCmd.CommandType = adCmdText

    'Open recordset
    Set objMyRecordset.Source = objMyCmd
    objMyRecordset.Open objMyCmd

    sbuildStr = ""

    While Not objMyRecordset.EOF ' HERE IS WHERE THE PROBLEM LIES ON THE MACHINES OF OTHERS
        strPSTPath = CStr(objMyRecordset("foox"))
        strPSTSize = CStr(objMyRecordset("PSTSize"))
        sbuildStr = sbuildStr & strPSTPath & " - " & strPSTSize & Chr(10) & Chr(13)
        objMyRecordset.MoveNext
    Wend

    ThisWorkbook.Sheets("WORKBOOK").Cells(i, 11).Value = sbuildStr

A: After removing the On Error Resume Next, I was able to receive the specific error code alerting me to the issue. After some research, I found the code wasn't executing on other people's machines because SQL Server Native Client 11 wasn't installed. Thanks for the nudge in the right direction, enderland.


text:
Q: Best way to sync Outlook 2010 with Google Calendar on multiple computers? I have Outlook 2010 installed on my laptop and desktop. Now I want to sync them, but Google Calendar Sync only supports Outlook 2003/2007 version. How can I do it now?

A: You can read here on how to sync Outlook 2010 with Google Calandar.
The page here
And the D/L links here
Or also: http://oggsync.com/

A: You can use KiGoo for syncing Calendar and Contacts.

KiGoo is an application running over Kayxo Insight technology which uses low access MAPI protocol to natively manage all GCal appointments inside Microsoft Outlook. Kayxo Insight technology enables this capability acting as a bridge between any external API or database and Microsoft Outlook.
Key Benefits:

*

*Manage Exchange and Google Calendars in only one program.

*Check free/busy availability of all Google Contacts who shared their information.

*See, Browse, Update, Email and invite your Google Contacts from Microsoft Outlook .

*No synchronization needed.

*Real Time access.

*Easy installation.

  Supports Microsoft Outlook 2007.  It does not currently support Outlook 2010
KiGoo is free for non commercial use.

A: I use gSyncit which has Outlook 2007, 2010 32bit as well as 2010 x64 support.
It has tons of options and is well worth the $19.99 IMO

A: Google Calendar Sync is now compatible with OL2010. (I'm unsure when it was updated to do so, but came across it last week and had to set it up on a Users computer with OL2010 - it worked flawlessly).
Compatibility
-------------
Currently, Google Calendar Sync is only compatible with Microsoft
Outlook versions 2003, 2007, 2010 and operating systems Windows XP,
Windows Vista, and Windows 7.

Windows XP 64-bit Edition is not compatible with Google Calendar Sync at this time.


text:
Q: Update framework inside app when framework source code is changed Trying this framework updation thing first time !
My app is using an external framework for which i have the source code. The app has the .framework file included inside it
What i want to achieve :

I change the source code in the framework outside the app and build and that changes should be made when i access it from the app

What i did so far:

*

*Changed a single method declaration inside the framework source code (say earlier it was returning String but i changed it to return String? now)

*Build the framework which generated a new .framework file

*Deleted the old .framework file from the app added the new .framework file

*Build the app

Result :

Error: No such module "Framework Name"

I am using Xcode 11 and under Framework,Libraries and Embedded Content , that framework exists (though it does not have the usual yellow briefcase icon but a white one)
I referred to this one : How to update a framework in an iOS app? but in this the particular error is not coming
Is there any other way to update the framework or am i missing something

A: I just ran into this myself.  I'm using Xcode 11:
Go to File > Swift Packages > Update to latest package versions
In my case this caused Xcode to pull the latest version from GitHub.
Hope it helps!
Also, I did update my framework, checked it in, and tagged it with a new version number.
Just re-read your question, and realized you have embedded the framework, so this probably won't work for you.  In my case a package was created for the framework.  I see that's not the case here.


text:
Q: Automatic apostrophes for quotation marks There are some other questions on this side addressing related issues, but I haven't found any which cover exactly my issue.
I have a text (converted from XML) which uses the apostrophe ' with three different meanings: Begin quote, end quote, and for abbreviations and genitive (can't, cats', etc.). Is there a way to keep the apostrophe ' the way it is in all cases but the begin quotes, where it must be replaced by `? For your information, I'm actually using XeLaTeX in my original document, but I'm not sure if it's going to matter.
\documentclass{memoir}

\begin{document}

He said, 'the cats' hats can't fit me'.

\end{document}

I guess the way of determining which one to use is:

*

*If the apostrophe is preceded by a text character, keep it

*If it is preceded by anything else (including space and nothing at all), change it to `

Note: Abbreviation apostrophes in the beginning of words (like in 'tis) are unlikely to appear in my documents.

A: If the apostrophe and end-quote needn't to be distinguished, then you can try:
\def\leftquote{`}\def\rightquote{'}

\catcode`\'=13
\def'{\ifvmode\leftquote \else \ifdim\lastskip=0pt \rightquote \else \leftquote\fi\fi}

He said, 'the cats' hats can't fit me'.

If the document uses such "double quotes" and you need to typeset them, then you can use following definition:
\def\leftqquote{``}\def\rightqqoute{''} % or another definition, can depend on fonts
                                        % put this definition before \catcode`\'=13
\catcode`\"=13
\def"{\bgroup\def"{\rightqqoute\egroup}\leftqquote}

The normal "quotes" are here.

Edit: Because there were comments about ' in math mode, like `$f'$, I add this functionality here:
\def\leftquote{`}\def\rightquote{'}

\catcode`\'=13
\def'{\ifmmode \expandafter\mathprime \else\ifvmode \leftquote \else
        \ifdim\lastskip=0pt \rightquote \else \leftquote\fi\fi\fi}
\def\mathprime{^\bgroup\catcode`\'=12 \csname prim@s\endcsname}

Unlike the accepted answer, I don't rewrite the \pr@m@s macro, only set the catcode temporary back to 12. This solution works in both plain TeX and LaTeX, because \prim@s macro is used in both macro packages with the same meaning.

A: I think that you want ' (open quote) only when ' is preceded by space or nothing at all.
This also copes with math mode.
\documentclass{memoir}

\makeatletter
\let\apostrophe'
\catcode`'=\active
\protected\def'{%
  \ifvmode
    `%
  \else
    \ifmmode
      \expandafter\expandafter\expandafter\active@math@prime % for math
    \else
      \ifdim\lastskip>0pt
        `%
      \else
        \apostrophe
      \fi
    \fi
  \fi
}
% redefine \pr@m@s to look for an active '
\def\pr@m@s{%
  \ifx'\@let@token
    \expandafter\pr@@@s
  \else
    \ifx^\@let@token
      \expandafter\expandafter\expandafter\pr@@@t
    \else
      \egroup
    \fi
  \fi}
\makeatother

\begin{document}

He said, 'the cats' hats can't fit me'.

'Ouch,' he said.

Some 'derivatives' $f'+f''+f'''$.

\end{document}

Note that the second line would have an open quote after the comma, under your specification.
Notes

*

*\protected is used or \section{A 'quoted'} would fail

*\section{'quoted'} will fail and there's not much to do about this

The following seems to fix the problem with section and chapter titles, when a trailing quote appears.
Compiling with both pdflatex and xelatex the result is the same.
\documentclass{memoir}

\usepackage{ifxetex}
\ifxetex
  \usepackage{fontspec}
%  \setmainfont{Linux Libertine O}
\fi

\makeatletter
% fix latex's habit of resetting ' during \write
\begingroup
\obeylines\obeyspaces%
\catcode`\'\active%
\gdef\@resetactivechars{%
\def^^M{\@activechar@info{EOL}\space}%
\def {\@activechar@info{space}\space}}%
\endgroup

\renewcommand{\cftchapteraftersnumb}{\hskip1sp\relax}
\let\ORIM@sect\M@sect
\def\M@sect#1#2#3#4#5#6[#7][#8]#9{%
  \ORIM@sect{#1}{#2}{#3}{#4}{#5}{#6}[\hskip1sp\relax#7][\hskip1sp\relax#8]{\hskip1sp\relax#9}%
}
\catcode`'=\active
\protected\def'{%
  \ifvmode
    `%
  \else
    \ifmmode
      \expandafter\expandafter\expandafter\active@math@prime % for math
    \else
      \relax
      \ifdim\lastskip=1sp
        `%
      \else
        \ifdim\lastskip>0pt
          `%
        \else
          \rq
        \fi
      \fi
    \fi
  \fi
}
% redefine \pr@m@s to look for an active '
\def\pr@m@s{%
  \ifx'\@let@token
    \expandafter\pr@@@s
  \else
    \ifx^\@let@token
      \expandafter\expandafter\expandafter\pr@@@t
    \else
      \egroup
    \fi
  \fi}
\makeatother

\begin{document}
\tableofcontents
\chapter{'Chapter'}

\section{'Quoted'}

He said, 'the cats' hats can't fit me'.

'Ouch,' he said.

Some 'derivatives' $f'+f''+f'''$.

\end{document}

A: If I understand your workflow correctly, it looks like (a) there's a process that creates a compilable .tex file that has some issues and (b) you need to address these issues before you run the .tex file through LaTeX. Moreover, the main issue appears to be that "dumb" (single) quotes are used throughout the tex file and that you wish to find a way to replace some of the single-quote characters (aka apostrophe characters) with back-quote characters (aka backticks). You haven't indicated explicitly which language your document is set in, so I'll assume for now that it's in English.

*

*If the problematic apostrophe characters occur only in mid-sentence positions (and are thus preceded by space characters) and not at the beginnings of lines, I suppose you could fire up an editor and replace all instances of space-apostrophe with space-backtick.

*If the problematic apostrophe characters can occur at the beginnings of lines, you'll need to check if your editor can perform a search-and-replace of newline_char-apostrophe for newline_char-backtick. Since you haven't indicated which editor (if any) you choose, I can't offer more-specific advice on how to go about this task.
Caveat: Both of these methods (and similarly automated methods) will not produce correct results if you have "literary" expressions such as 'tis -- short for " it is" -- in your input text. (The apostrophe indicates an elision rather than the start of a quote in such circumstances, and the apostrophe should therefore not be replaced with a backtick.)


text:
Q: Where to store in-memory app info - Angular In my Angular app I want to store a whole bunch of data for my user, in memory, to be used in many places throughout the application (so that I don't have to make extra calls to the server).
Examples of what I have to store:

*

*User's personal info (I have a User class)

*Alerts list (I have an Alert class)

*Latest Activities list (I have an Activity class)

*User's Pet list - includes a bunch of info about each pet (I have a Pet
class)

The data retrieval for these is happening in different services, such as sign-in.service.ts, pet.service.ts, etc.
I'm thinking to hold all this info in a service or services.
Is it "best practice" to store this information in one service with a function to get and to set each thing, or to have a separate service for each thing on my list?
EX: Should I have 1 "app-state.service.ts" or should I have "user-personal-info.service.ts", "alerts.service.ts", "activities.service.ts", and "pets.service.ts"?
Thanks for your help!


text:
Q: show UIPageviewcontroller childcontrollers based on array count I need to display childcontrollers in the UIPageviewController class based on the array count which i get from the API response . for eg. one child controller can have one imageview and label below it  and so multiple childcontrollers can have differnt content.

A: In my code, create an array of view controllers (could also be dynamic) for:
self.introPages = [self introContentViewControllers];

Like this:
- (NSArray *)introContentViewControllers {
  return @[
           [[IntroContentViewController alloc]
             initWithIndex:0
             text:NSLocalizedString(@"Intro.Page1.title", nil)
             image:[UIImage imageNamed:@"onboarding-10-party"]],
  // Etc.
}

That should do what you are requesting.


text:
Q: Know the position of the mouse for the event onmousemove in IE 9, firefox and Chrome I use this function to obtain the position of the mouse for the event onmousemove, but get a different result in Internet Explorer 9.
function mouseCoords(ev){
if(ev.pageX || ev.pageY){
    return {x:ev.pageX, y:ev.pageY};
}
return {
    x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
    y:ev.clientY + document.body.scrollTop  - document.body.clientTop
};
}

What is the function for the majority of browsers?

A: The most consistent way to track the mouse coordinates across browsers is to use jQuery.
http://docs.jquery.com/Tutorials:Mouse_Position


text:
Q: Min height not working properly? I am trying to create a DIV that will have a minimum height of 100%, which is not working in FireFox / IE. It works only if use the "height" property.
Chrome is behaving correctly.

        With firefox / IE, this div is not stretching to take 100% of the total page height.

Update:
I understand that I need to define the height of the body/html. That makes sense. But even with this solution, I still cannot use min-height for a child div. See the below example. The child div is not taking 33% of the parent div. (In FIREFOX and IE)

        Parent div

        With firefox / IE, this CHILD div is not stretching to take 33% of the container.

A: You also need to give the html and body a height
html, body {
  height: 100%;
}

Update 1, after a question edit
With that new markup, also .page need height: 100%

html,
body {
  height: 100%;
}

.page {
  height: 100%;
  border: 1px solid black;
}

.child {
  min-height: 100%;
  border: 1px solid red;
  display: flex;
}

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

Update 2, based on a comment
Use Flexbox and viewport units vh instead, it will work much better

body {
  display: flex;                 /*  IE need this for its 'min-height' bug  */
}

.page {
  min-height: 100vh;
  border: 1px solid black;
  display: flex;
  flex-direction: column;
}

.child {
  flex-grow: 1;
  border: 1px solid red;
}

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

Which also will work with the min-height: 33%

body {
  display: flex;                 /*  IE need this for its 'min-height' bug  */
}

.page {
  min-height: 100vh;
  border: 1px solid black;
  display: flex;
  flex-direction: column;
}

.child {
  min-height: 33%;
  border: 1px solid red;
}

    With firefox / IE, this CHILD div is not stretching to take 100% of the container.

A: The min-height property doesn't work if the direct parent of the element doesn't have an explicit height applied using CSS.
From MDN

The percentage is calculated with respect to the height of the
  generated box's containing block. If the height of the containing
  block is not specified explicitly (i.e., it depends on content
  height), and this element is not absolutely positioned, the percentage
  value is treated as 0.

The only way to do it is to add another div inside the parent div and explicitly set its height to 100% then insert the child div inside it then the min-height will work

A: To be honest, I'm not sure why it even works with the height property. When you're using percentage heights in CSS, the root element (html, body) needs to have a defined height.
This is because percentages are percentages of the parent. If the root element has no defined height, then no height can be calculated from it.
So to give the root element a height, you set it to 100% like this:

html, body {
  height: 100%;
}
.page{
  min-height:100%;
  border:1px solid black;
}

  With firefox / IE, this div is not stretching to take 100% of the total page height.

A: In my case solution was use min-height: 100vh

A: In the case of table  \
 the min-height is not working, but you can use heigh, and in this situation will behave as min-height.

A: Try adding to your CSS code this:
.page{
   min-height: 100%;
   -moz-min-height: 100%;
   border: 1px solid black;
}

Sometimes browsers do not act in the same way, and you need to add some things. Moz for mozilla firefox. -webkit-styleGoesHere is for Chrome.
I hope this helped.


text:
Q: How to remove items in a vector from another vector I have two vectors:
a = c(1,1,2,2,3,3,4,4)
b = c(1)

I want to remove the first match of b from a. Thus, here only the first 1 is removed from a:
c = c(1,2,2,3,3,4,4)

The order of items in a is not important.
I tried this code:
a[a != b]
a[! a %in% b]

Both results are:
[1] 2 2 3 3 4 4.

All numbers of 1 are removed. However, I only want to remove the specific item in b from a.
If b = c(1, 1, 2), then I wish the result
[1] 2 3 3 4 4

a[-(1:3)]

The above code could lead to the result of [1] 2 3 3 4 4. However, I wish it could be more flexible. For example when the order of items are unknown or random:
a = c(3,4,3,1,2,2,1,4)

How can I do it using R?

A: Taking inspiration from this answer to one of the questions I linked in comment, you can use fsetdiff from the package data.table.
It takes all as argument, which avoids having only the unique values returned, as happens with setdiff:
library(data.table)

# with your first example (b = c(1)):
unlist(fsetdiff(data.table(v1=a), data.table(v1=b), all = TRUE))
# v11 v12 v13 v14 v15 v16 v17
#  1   2   2   3   3   4   4

# with second example (b = c(1, 1, 2)):
unlist(fsetdiff(data.table(v1=a), data.table(v1=b), all = TRUE))
# v11 v12 v13 v14 v15
#  2   3   3   4   4

A: vecsets package can perform standard set operations, while retaining duplicates:
vecsets::vsetdiff( c(1,1,2,2,3,3,4,4), c(1) )
## [1] 1 2 2 3 3 4 4

vecsets::vsetdiff( c(1,1,2,2,3,3,4,4), c(1,1,2) )
## [1] 2 3 3 4 4

Note that it will preserve the order of the first argument. Using your last example:
vecsets::vsetdiff( c(3,4,3,1,2,2,1,4), c(1,1,2) )
## [1] 3 4 3 2 4

A: You can use which()
a = c(3, 4, 3, 1, 2, 2, 1, 4)
a
## [1] 3 4 3 1 2 2 1 4

b = 1

a[- which(a %in% b)[1]]
## [1] 3 4 3 2 2 1 4

Case b has two elements:
b2 = c(1, 2)

sapply(seq_along(b1), function(x) a <<- a[- which(a == x)[1]])[[2]]
## [1] 3 4 3 2 1 4

Or three...
b3 <- c(1, 2, 3)

sapply(seq_along(b1), function(x) a <<- a[- which(a == x)[1]])[[3]]
# [1] 4 3 2 1 4

A: I don't think that the following is the best solution (the vecsets approach strikes me as the best), but @Aaron's comment about possibly using Rcpp struck me as interesting. This is the first time I used that package. If nothing else, the fact that I was able to get working code in less than 20 minutes underscores his point that Rcpp makes it relatively easy:
library(Rcpp)
cppFunction('
  NumericVector difference(NumericVector xs, NumericVector ys){
    int m = xs.size();
    int n = ys.size();
    float flag = 1 + abs(max(xs)) + abs(max(ys)); //occurs in neither xs nor ys
    NumericVector zs = clone(xs);
    for(int i = 0; i < n; i++){
      double y = ys[i];
      int j = 0;
      while(j < m && zs[j]!= y) j++;
      if(j < m) zs[j] = flag;
    }
    int count = 0;
    for(int k = 0; k < m; k++){
      if(zs[k] < flag) count++;
    }
    NumericVector ws(count);
    int k = 0;
    for(int j = 0; j < m; j++){
      if(zs[j] < flag){
        ws[k] = zs[j];
        k++;
      }
    }
    return ws;
  }
')

After you source this:
> a = c(1,1,2,2,3,3,4,4)
> b = c(1,2,1)
> difference(a,b)
[1] 2 3 3 4 4

Since this was my first attempt at such code, I'm sure that it could be improved in multiple ways.

A: A little frustrating, the syntactical order, but Reduce and which do it with just Base R.
Reduce(b, a) a[-which(a==b)[1]], a, b)


text:
Q: Set indexed over another set in Julia If I have sets:
set F := G1 G2;
and
set PR[G1] := p1 p2;
set PR[G2] := p3 p4;
how to make the set PR in Julia. For each element of F a specific set of elements belong to PR.
Thank you!
Nikola

A: Use something like
F = [:G1, :G1]
PR = Dict(:G1 => [:p1, :p2], :G2 => [:p3, :p4])

To help more, you will need to provide more information.


text:
Q: windows batch | for loop and dir command with parameter Working command - pasted directly in command shell:
for /f %a in ('dir /b /s ..\*') do @echo %~na | findstr transport_bb_*_*_* | sort

Problem 1) The same command executed from a .bat file results in an error:
| was unexpected at this time.

Problem 2) In addition, would like the mentioned .bat file to accept a parameter (directory):
for /f %a in ('dir /b /s %1\..\*') do @echo %~na | findstr transport_bb_*_*_* | sort

Tried apostrophes, "grave accents", double percents, using SET to put whole command inside parenthesis, still no effect.
Help appreciated.
Thanks,
Bart

A: ad 1) In batch file you have to double the % -> %%. The pipes | you will have to replace with workflow:
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
for /F "delims=" %%A in ('dir /B /S ..\*') do (
    echo %~nA
    set "search_in_file=%%A"
    findstr transport_bb_*_*_* !search_in_file! | sort
)

ad 2) Take in user input
@echo off
SETLOCAL  ENABLEDELAYEDEXPANSION
SET "input=%~1"
SET "search_in_dir=!input!\*"

   for /F "delims=" %%A in ('dir /B /S !search_in_dir!') do (
        REM echo %%~nA
        set "search_in_file=%%A"
        REM ECHO findstr "transport_bb_*_*_*" "%search_in_file%"
        findstr "transport_bb_*_*_*" "!search_in_file!"
        IF ERRORLEVEL 1 (
           ECHO "String NOT found in file !search_in_file!"
        ) ELSE (
           ECHO ""String found in file !search_in_file!"
        )
    )

or more like your script:
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET "input=%~1"
SET "search_in_dir=!input!\*"

   for /F "delims=" %%A in ('dir /B /S !search_in_dir!') do (
        set "search_in_file=%%A"
        findstr /M "transport_bb_*_*_*" "!search_in_file!" | sort
    )

Notes:
Where findstr parameter:
/M         Prints only the filename if a file contains a match.

%~1 ... takes in first user parameter and expands it
!....! now delimits a variable due to SETLOCAL ENABLEDELAYEDEXPANSION being enabled.


text:
Q: Merge two tables withe condition R Hi here is a beginner question! I need some help regarding overwrite specific charter label, based on value from Class-column .
If the labels from Class-column says "Sport" with value from Sport-Class. Please see example below.
I tried to use ifelse statement:
DF$Class<-ifelse((DF$Class %in% "Sport"), DF$SportClass, DF$Class)

I have two columns, And my wanted output is "Column: Expectations"
ID:      Class:     SportClass:  |  (Expetions)
1        Movie      Hockey       |   Movie
2        Seriers    Fotboll      |   Series
3        Movie      Tennsi       |   Movie
4        Sport      Golf         |   Golf

Can somebody please assist me?

A: Make sure you are using the correct column names of your dataframe and that your variables are not factors, because the levels don't match and your process breaks.
Using the following dataframe
DF = read.table(text = "
ID      Class     SportClass
1        Movie      Hockey
2        Seriers    Fotboll
3        Movie      Tennsi
4        Sport      Golf
", header=T, stringsAsFactors=F)

I can successfully update variable/column Class
# dataset before
DF

#   ID   Class SportClass
# 1  1   Movie     Hockey
# 2  2 Seriers    Fotboll
# 3  3   Movie     Tennsi
# 4  4   Sport       Golf

# update variable
DF$Class <- ifelse(DF$Class %in% "Sport", DF$SportClass, DF$Class)

# dataset after
DF

#   ID   Class SportClass
# 1  1   Movie     Hockey
# 2  2 Seriers    Fotboll
# 3  3   Movie     Tennsi
# 4  4    Golf       Golf

Note that you don't really parenthesis around DF$Class %in% "Sport" and that you can also use DF$Class == "Sport" in this case.


text:
Q: How to generate a random word with a number? I'm looking for a method to generate a invite code. I would prefer the code not looks like garbled text: JakSj12
But rather more like heroku, using a fun word with 3 numbers.
lightspeed131 or happy124, jetski99

How can I build a method that takes a list of words, maybe 100? and randomly assigns 3 numbers to them?
Thanks

A: Other answers given here are a bit slow, since they shuffle their lists on every call.  Here's something a bit faster:
def wordwithnumber(words)
   words[rand(words.length)]+(rand(900)+100).to_s()
end

wordwithnumber(["lightspeed", "happy", "jetski"])

This gives you three digits every time, if you want a number from 0 to 999 modify the rand() call accordingly.

A: def random_name(words, number = nil)
  number ||= rand(999)

  words.sample.to_s + number.to_s # concatenate a random word and the number
end

# example:
random_name(["lightspeed", "happy"]) # lightspeedXXX, happyXXX (where XXX is a random number)
random_name(["lightspeed", "happy"], 5) # lightspeed5, happy5

A: Always 3 different numbers? not very efficient but simple:
words.zip((100..999).to_a.shuffle).map(&:join)

If you don't mind getting repeated numbers (I guess not):
words.map { |word| word + 3.times.map { rand(10) }.join }

Or simply in Ruby 1.9:
words.map { |word| word + Random.new.rand(100..999).to_s }

([edit] This generate 100 words with numbers, which is what I understood. )

A: I would use following (very readable IMHO) solution:
names = %w[tinky\ winky dipsy laa-laa po]

def random_name(names)
  [names, (100..999).to_a].collect(&:sample).join
end

3.times.collect { random_name(names) }
# => ["dipsy147", "dipsy990", "po756"]

More memory friendly solution:
def random_name(names)
  @numbers ||= (100..999).to_a
  [names, @numbers].collect(&:sample).join
end

A: def random_word_and_number( words, max=999 )
  "%s%0#{max.to_s.length}d" % [ words.sample, rand(max+1) ]
end

(1..4).map{ random_word_and_number( %w[ foo bar jim jam ] ) }
#=> ["jim048", "bar567", "jim252", "foo397"]

Let's you specify an arbitrary maximum value while ensuring that all answers have the same number of digits.


text:
Q: retrieve variable value from nsh file nsis I am creating installer using nsis. I have created .nsh file using SIMPLE SC to start, stop and remove services. I have used macros for this.
When I call this in nsi file it works. But I would like to know the return value for start service (SimpleSC::StartService "${SVC}" "${Args}" "${Timeout}", Pop $0). how do I retrieve the $0 value of nsh file in my nsis file

A: If you have some helper macros that return a result, you can leave the result on the stack:
!macro DoSomething
Push $0
Push $1

Push "Pretend that this is a function that does something and puts the result on the stack"
Pop $0 ; Result we want to return

Pop $1
Exch $0
!macroend

!insertmacro DoSomething
Pop $0
MessageBox MB_OK $0

or store it in a register as part of the macro:
!macro DoSomething outvar
Push $0
Push $1

Push "Pretend that this is a function that does something and puts the result on the stack"
Pop $0 ; Result we want to return

Pop $1
Exch $0
Pop ${outvar}
!macroend

!insertmacro DoSomething $0
MessageBox MB_OK $0


text:
Q: Too many TIME_WAIT connections in PostgreSQL I am using PostgreSQL 9.0 on Centos 5.7 Final.
At any given there are around 1,500-2,200 connections open for PostgreSQL on port 5432 which are in TIME_WAIT state.
I have a feeling this is not good.
Is this wrong? If yes how to get rid of this?
EDIT
There are mainly 3 applications connecting to the database:

*

*A Server which inserts around 5,000 rows every minute.

*A web app.

*A reporting server

A: 1500 to 2200 concurrent connections are only useful when you need them. Otherwise, bring the total number of open connections down and start using a connection pool like pgBouncer or PgPool-II. See Number of Connections (on the wiki). We do about 2500 transactions per second on 150 connections.
Don't forget, each connection uses RAM, RAM that could be used to get some real work done. PostgreSQL gets slower when you use too many connections without a connection pool. What "too many" is depends on your hardware and workload, but it's very unlikely that your system will perform better with 2000 than it will with 100; probably much worse.

A: 2000 connections in TIME_WAIT state does not look that much.
Compare this to the output of:
# cat /proc/sys/net/ipv4/ip_local_port_range
which would typically be 32768 61000 and can be enlarged if necessary.
It would be a problem if you exhausted that range, though.
If you're worried about that, you could set /proc/sys/net/ipv4/tcp_tw_reuse to 1, which would make the sockets in TIME_WAIT state disappear much faster.
See this related question on serverfault.com for some background.
On the other hand, if you have lots of connections in ESTABLISHED state, consider a connection pooler as per @FrankHeikens answer.
Note that the pooler itself is not supposed to reduce the number of connections in TIME_WAIT state, though, since these will just sit between your app and the connection pooler instead of sitting between your app and postgresql. The pooler is mainly meant to reduce the number of connections established to the database per unit of time, which is not exactly the same issue.


text:
Q: Why do I keep burning my mosfet? Following this question, I ended up with the following diagram to drive a custom made dc motor using Arduino (omitting the 5V and 12V power supply stages which work properly):

I keep burning instantly the irfp054n mosfet. An by instantly, I mean it.
I tested with a voltmeter the voltage output by the Arduino PWM pin 5 and it's between 0 and 5V.
The voltage coming out from the TC4422 (pins 6 and 7) is between 0 and 12V.
Right after giving power to the whole system, I see the motor running at full speed, so I turn off the power and measure a resistance of about 0.2 Ohm between drain and source on the mosfet, which means it's gone.
What am I doing wrong? Any hints?
UPDATE: Ok, ok, I'll get rid of that diode... Anyway, I installed it right after burning the first mosfet so I wouln't think it's the cause.
Just out of curiosity: could it be that the problem comes because the Schottky and the mosfet are screwed on the very same aluminium heatsink?
UPDATE: It works, I replaced the diode between driver and mosfet with a 120 Ohm resistor and the mosfet is now a much stronger IRFB4115Pbf. I still have some glitches to work out: when I shut down the 5 V and 12V circuit, the motor runs up to full speed. Any ideas?

A: As others have said, that diode is bad news- take it out and never put it back under any circumstances. Throw it away.
The start-up surge of a brushed DC motor from a low-impedance source such as lead-acid batteries can be very substantial- in the hundreds of amperes, and can destroy a MOSFET fairly readily. The current ratings for most TO220 and TO247 parts come with a lot of caveats. For a similar application we had to use two paralleled MOSFET modules as below, even with ramped-up current.

I suggest measuring the motor resistance with a milliohmeter to get an idea of the surge current you're exposing the MOSFET to. If you have an active high current Hall current transducer (you can buy them for a reasonable price- tens of dollars- as components) you can capture the startup transient surge with a digital oscilloscope (you don't need the MOSFET, a switch will do). Once you know what you're dealing with, it becomes a lot easier to do a design rather than guessing about what is doing on.
Also, make sure the grounds are connected solidly between the different circuits. A voltage transient caused by even a small amount of inductance in the power circuit can cause a spike that will punch through the gate oxide and destroy the MOSFET. v = L * di/dt. A series resistor from the drive circuit of 20 ohms or so and a fast TVS from gate to source would be cheap insurance, but try to make the layout good from the beginning.

A: Lose the diode.  I can't even guess what you think it does, but it will prevent the FET from being turned off quickly.
The FET driver will drive the gate high quickly, which turns on the motor.  However, when it tries to drive the gate low, the diode prevents it from doing so.  That means the gate just floats.  It probably slowly drifts low, running the FET in the intermediate region where it dissipates significant power.
You need to switch the FET quickly to prevent significant dissipation.  The power the FET dissipates is the voltage across it times the current thru it.  When it is off, there is no current, so the power is 0.  When it is on, the voltage drop is very small, so the power is also small.  In the middle of its operation, it would have 18 V across it and 5.7 A thru it, for a dissipation of over 100 W.  Poof!
The job of the FET driver is to slew the gate voltage quickly to have the FET only spend a few ns at a time in the high dissipation region.  The diode is preventing that from happening.
Added:
You now mention that the reverse diode across the motor and the FET are bolted to the same aluminum heat sink.  That could be a problem, depending on what pin of each part is connected to the mounting tab.  This is, of course, all clearly spelled out in the datasheets.  If it's not the FET drain and the diode anode, then that is very bad.  At least one of the two then needs to be insulated.  Or, use two separate heat sinks.
Another problem you may have is that the FET or diode aren't connected properly.  Again, you have to actually read the datasheets, then double check that you have things wired right.  This could explain why the FET driver blew out.
Also, do what Tom Carpenter suggested, which is to replace the motor and diode with a resistor for debugging.  However, I'd use different values.  Use a 1 kΩ resistor between the drain and the 12 V supply.  Until the drain is switching crisply and opposite of the gate drive signal there is no point going further.  With 12 V and 1 kΩ nothing else can get hurt, including the FET driver even if you flipped some pins on the FET.
Don't forget the bypass cap across the FET driver power and ground pins, and a 10 Ω or so resistor between the FET driver output and the FET gate.

A: has anyone checked BEMF?
Reminder: motor peak current is I = (V - BEMF) / R, while BEMF is 0 when the motor starts. So if you don't have current control (do you?) you may easily receive tens or in some cases hundreds of amps, depending only on ohmic resistance and bus voltage.
Add: it's another topic about motion control. And another time that best advice is: take servo. Google Galil servo or Adthech, they are the cheap high end devices that i know. But even buying random servo on ebay is better than trying random motor with random transistor. It's not even safe! Be careful.


text:
Q: Comparando matrizes de diferentes tamanhos em R Eu tenho a seguinte situação :
all_sec = Matriz de todos os ativos possiveis em uma carteira
all_sec <- matrix(c("SEC1","SEC2","SEC3","SEC4","SEC5"),ncol=1)

portfolio <- composição de um portfolio de ativos (coluna 2 é igual ao peso do ativo na carteira
portfolio <- matrix(c("SEC2","SEC4",0.45,0.55),ncol=2)

Eu quero como resultado uma matrix de 1 coluna no qual o valor retorne 0 se o ativo não estiver no portfolio e retorne o valor do peso (coluna 2 da matriz portfolio) se tiver no portfolio. O resultado seria uma matrix nesse formato :
     [,1]
[1,] 0
[2,] 0.45
[3,] 0
[4,] 0.55
[5,] 0

Poderiam me ajudar ?

A: Você pode fazer isso com o merge:

resultado <- merge(all_sec, portfolio, all=TRUE) # faz o merge das duas matrizes
resultado <- apply(resultado, 2, as.character) # transforma em texto de novo (porque o default do R é transformar texto em factor
resultado[is.na(resultado)] <-0 #substitui NA por zero
dimnames(resultado) <- NULL # tira os nomes das dimensões

Então você vai ter o seguinte resultado:

resultado
     [,1]   [,2]
[1,] "SEC1" "0"
[2,] "SEC2" "0.45"
[3,] "SEC3" "0"
[4,] "SEC4" "0.55"
[5,] "SEC5" "0"

E se você quiser somente a segunda coluna:

subset(resultado, select=V2)
     [,1]
[1,] "0"
[2,] "0.45"
[3,] "0"
[4,] "0.55"
[5,] "0"

Agora, uma coisa importante a se notar é que a sua matriz portfolio está misturando elementos character com numeric então ela vai transformar todo mundo em character. Talvez você deveria trabalhar com um data.frame e não uma matriz.

A: #define as matrizes
all_sec <- matrix(c("SEC1","SEC2","SEC3","SEC4","SEC5"),ncol=1)
portfolio <- matrix(c("SEC2","SEC4",0.45,0.55),ncol=2)
#define o tamanho das matrizes (melhor que ficar chamando dim() toda hora)
all_dim <- dim(all_sec)[1]
portfolio_dim <- dim(portfolio)[1]
#cria a matriz para guardar os resultados
resultado <- matrix(data=NA, nrow=all_dim, ncol=1)
for(j in 1:all_dim){
   #inicia como 0
   resultado[j] <- 0
   #procura por X no portfolio
   for(i in 1:portfolio_dim){
      #se encontrar define o mesmo
      if(all_sec[j] == portfolio[i,1]){
        resultado[j] <- portfolio[i,2]
        break
      }
   }
}
print(resultado)

A: Você pode fazer isso com o pacote data.table:
> library(data.table)

> all_sec <- matrix(c("SEC1","SEC2","SEC3","SEC4","SEC5"),ncol=1)
> portfolio <- matrix(c("SEC2","SEC4",0.45,0.55),ncol=2)
> all_sec = data.table(all_sec, key='V1')
> all_sec
     V1
1: SEC1
2: SEC2
3: SEC3
4: SEC4
5: SEC5
> portfolio = data.table(portfolio, key='V1')
> portfolio
     V1   V2
1: SEC2 0.45
2: SEC4 0.55
> portfolio[all_sec]
     V1   V2
1: SEC1   NA
2: SEC2 0.45
3: SEC3   NA
4: SEC4 0.55
5: SEC5   NA

> as.matrix(portfolio[all_sec][, list(V1, V2=as.numeric(as.character(V2)))][is.na(V2), V2 := 0][, V2])
     [,1]
[1,] 0.00
[2,] 0.45
[3,] 0.00
[4,] 0.55
[5,] 0.00
>


text:
Q: Django order_by() and distinct() w/ annotate I'm using Django 1.4 with Python 2.7 on Ubuntu 13.04.
I know there are issues with using order_by() and distinct() across relationships in Django.  It seems most of the suggested solutions to overcome this is to use aggregation.  I'm not seeing how I can do this in my case.
I have a QuerySet that has been pre-filtered.  I need to order it by 2 fields and then get the results by a distinct foreign key.
class Contract(models.Model):
    rpl = models.DecimalField(max_digits=20, decimal_places=2, default=0)
    priority = models.IntegerField(default=0)

class Offer(models.Model):
    contract = models.ForeignKey(Contract)
    product = models.ForeignKey(Product)

I need to get a list of offers ordered first by contract priority then contract rpl.  Of that result I need the offers with distinct products.
qs.order_by('-contract__priority', '-contract__rpl').distinct('product')
How would I do this elegantly with Django?

A: Seems like what you need is a GROUP BY statement, and unfortunately django doesn't offer that - see this question Django: Group by?
Personally I'd probably approach it from a different angle, and use a Product queryset instead. You can filter on offer fields and order by annotated priority/rpl values, then for each product you'd need to retrieve the offer details separately. It means an extra query for each row, but it might be the best you can do. Eg:
Product.objects.filter(offer__...=...) \
               .annotate(priority=models.Max('offer__contract__priority'),
                         rpl=models.Max('offer__contract__rpl')) \
               .order_by('-priority', '-rpl')


text:
Q: Mercurial Textmate bundle broken after switch to 1.5.10 After I left Textmate 1.5.9 for 1.5.10 the Textmate Mercurial bundle didn't find hg anymore.
Probably due to this change:

[CHANGED] Commands (without shebang) no longer source the default shell startup files. This means that nothing in TextMate will use the value of PATH setup in ~/.profile or similar (and on the plus side, nothing in your shell startup files will trip TextMate).

I added /usr/local/bin/ to the new Textmate PATH and hg was found again. Now, however, the TM bundle always gives me

File(s) not modified; nothing to commit.

or something similar, seemingly indicating it doesn't recognize my project anymore. I can bring up my revision history though.
If I commit in the terminal, hg works as usual. I went through the output of echo $PATH (/Library/Frameworks/Python.framework/Versions/2.7/bin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/sw/bin:/sw/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/git/bin:/usr/X11R6/bin)
but there was no hg except in /usr/local/bin.
What could cause this, or how could I narrow it down?


text:
Q: Different notions of torsors in algebraic geometry In what follows $X$ will be a scheme and $G$ a group scheme. In the examples I will take $X=\mathbb{P}^1_k$ and $G=\mathbb{G}_{m}$. When reading about "the torsor..." I found many definitions, not sure which are equivalent and why exactly:

*

*(Principle $G$-bundle) A $G$-torsor $P$ over a scheme $X$ is a scheme $P\to X$ with a $G$ action $G\times P\to P$ , which is locally trivial in the sense that there is a covering map $Y\to X$ (in the Zariski,etale,fppf,... topology), s.t. $Y\times _X P\to Y$ is isomorphic to $Y\times G\to Y$.
Example: $P=X\times G$ or $\mathbb{A}^2_k-\{0\} \to X$ the Hopf bundle

*(Sheaf version) A $G$-torsor $P$ is a sheaf on $(Sch/X)$ (with the Zariski, etale,fppf,... topology), if there is a covering $\{U_i\to X\}$, s.t. $P|_{U_i}$ is a trivial $G_{U_i}$ torsor (on sheafs a trivial torsor is a sheaf with a $G$ simply transitive action and non empty global sections).
Example: $Hom(-,X)$ for a principal $G$-bundle as in 1) ?

*(Small sheaf version) Let $\mathcal{G}$ be a sheaf of abelian groups on the topological space $X$. A $\mathcal{G}$-torsor is a sheaf $P$ on $X$ with a $\mathcal{G}$ action with non-empty stalks on which $G$ acts simply transitive.

*(Tannakian version) A $G$-torsor is an exact tensor functor $Rep_k(G)\to Bun_X$, where $X$ is a scheme over $k$. (cf this paper 4.1.)
If $G$ happens to be $GL_n$ then we even have two more notions:

*$P$ is a vector bundle, i.e. a locally free sheaf of rank $n$

*$P$ is a geometric vector bundle, i.e. $P\to X$ is a morphism which is locally of the form $pr_2:\mathbb{A}_n\times U_i\to U_i$ in a compatible way (cf. Hartshore ex.5.19 for more details)
Now here is what I think is equivalent:

*

*If we consider the etale topology, 1. and 4. are equivalent

*I think I read that 1. and 2. are equivalent in some good cases, if some affinity condition is fulfilled

*In the $GL_n$ case 3., 5. and 6. are all equivalent

*I am not sure if 1. 2. or 4. are connected to 3. (well $Hom(-,\mathbb{G}_m)=\mathcal{O}_X^*$ when restricted to X seems no coincidence?)

Further questions:

*

*What do $\check{\mathrm{H}}^1(X,\mathcal{G})$ and $\check{\mathrm{H}}^1(X,G)$ really capture?

*Is the line bundle corresponding to the Hopf bundle in 1. $\mathcal{O}(-1)$?

A: This is an incomplete answer but too long for a comment.

*

*is the standard definition of a torsor in the category of schemes.

*and 3. are a generalization for groups that are not representable. So if $T$ is a torsor in the sense of 1., then $Hom(.,T)$ are torsors in the sense of 2. and 3. But 2. is more general : if $\tau$ is a topology and $\mathcal{G}$ is a $\tau$-sheaf of group which is not representable, then we can still define $\mathcal{G}$-torsors as a sheaf which is locally for the $\tau$-topology isomorphic to $\mathcal{G}$. I believe (I hope someone can confirm this) that if $\tau$ is subcanonical (such as most of the topology fppf, étale, Zarisky, but not the h-topology) that if $\mathcal{G}$ is representable by a scheme $G\in Sch/X$, then any $\mathcal{G}$-torsor is representable. So if $\mathcal{G}$ is representable, then this is the same thing as definition 1.

*vs 2. Well obviously, a sheaf $\mathcal{G}$ on $Sch/X$ restricts as a sheaf $\mathcal{G}|_X$ on $X$ for the same topology and a $\mathcal{G}$-torsor on $Sch/X$ will restrict as a $\mathcal{G}|_X$-torsor on $X$. As I said before, torsor in the sense of 1. defines torsor in the sense of 3., but they are not representable anymore, but they are the restriction of a representable sheaf on $Sch/X$. Hence torsor in the sense of 2. provides a useful generalization of both 1. and 3. Unfortunately, this is a bit too wide because a lot of torsors in the sense of 2. "does not look like torsors" (say $X=\operatorname{Spec}k$ and $\tau=Zar$, then a torsor $T$ can be very different on $\operatorname{Spec}k$ and on $\mathbb{P}^1_k$) and because a lot of torsors in the sense of 2. restricts to the same torsor on $X$.

*I am not comfortable with this definition. But also, I am not sure about what $Bun/X$. Do you mean maps $p:Y\to X$ which are locally a projection $U\times F\to U$ or do you mean all maps $p:Y\to X$ ?

Now for the case of $GL_n$, I disagree that 5. and 6. are definitions of torsors. They are instead associated spaces. From a vector bundle of rank $n$ (a sheafy version or geometric one, this is the same, and by Hilbert 90, every topology is equivalent in this case) defines a $GL_n$ by looking at the space of frames. Conversely, from a space of frames, we can form the associated space. But this is not the same geometrical object. Even in the case $n=1$ : from the vector bundle $p:E\to X$, we have to remove the image of the zero-section. But yes, there is a bijective correspondence between the $GL_n$-torsors and rank $n$ vectors bundle.
As for your final questions :

*

*$\check H^1(X,\mathcal{G})$ classifies the $\mathcal{G}$-torsor in the sense of 1. if $\mathcal{G}$ is representable in $Sch/X$ and in the sense of 3. otherwise. We cannot get torsors in the sense of 2. because cohomology on the big site coincide with the cohomology on the small site. This agree with what I said before : torsors in 2. are too wide since there is not much connection between a scheme $Y$ and $X$ if $Y$ is not part of a covering of $X$. But definition 2. still provides a useful category in which both definition 1. and definition 3. lives.

*Yes but note again that $\mathcal{O}(-1)$ is not a $\mathbb{G}_m$-torsor=$\mathcal{O}^*$-torsor, but rather an associated space.


text:
Q: Loop-Suspension adjunction unit is stable equivalence Let $X$ be a sequential spectrum, then the unit of the $(\Sigma,\Omega)$-adjunction yields a map $\eta : X \to \Omega \Sigma X$. The authors of the book Foundations of Stable Homotopy Theory (p. 48) then claim that $\eta$ is a $\pi_*$-isomorphism because $\pi_*(\eta)$ is part of the colimit sequence defining the homotopy groups of spectra:
$$ \pi_{n+a}(X_a) \to \pi_{n+a}(\Omega \Sigma X_a) \cong \pi_{1+n+a}(\Sigma X_a) \to \pi_{1+n+a}(X_{1+a}).$$ Why does this observation show that $\eta$ is a $\pi_*$-isomorphism? Does this already tell us that the colimit sequence is somehow compatible with the one for $\pi_n(\Omega \Sigma X)$?
(I know a different argument using that suspension and loop space are $\pi_*$-equivalences along with triangle identities but I want to understand this more direct argument.)

A: This is a general fact about sequential colimits (or even more generally colimits over posets). $\newcommand\colim{\operatorname{colim}}$
Let $A : \mathbb{N}\to \mathcal{C}$ be some sequential diagram.
$\mathbb{N}$ has an endomorphism $s$ defined by $s(n)=n+1$.
There is a corresponding natural transformation $\sigma : A \to s^*A$,
which at $n$ is the map $f_n : A_n\to A_{n+1}$ which is $A(n\le n+1)$, the transition map in the sequential diagram.
In fact, more generally, let $t : \mathbb{N}\to \mathbb{N}$ be any nondecreasing map, then $t$ gives an endomorphism of $\mathbb{N}$ as a category, so we can consider the pullback $t^*A$. If $t$ additionally satisfies $t(n)\ge n$ for all $n$, then there is a natural transformation $\tau: A\to t^*A$ which at $n$ is the unique map $A_n\to A_{t(n)}$ in the diagram $A$.
Now if we assume that $t$ is cofinal (for all $n\in \mathbb{N}$, there exists $N\in\mathbb{N}$ such that $t(N)\ge n$), the following is true.

Proposition. $\colim A$ exists if and only if $t^*\colim A$ exists. In this case if $t(n)\ge n$ for all $n$, so $\tau$ exists, then $\tau$ induces a morphism $\tilde{\tau}:\colim A\to \colim t^* A$ on passing to colimits which is an isomorphism.

Proof.
It suffices to give a natural isomorphism between $\newcommand\cocone{\operatorname{co-cone}}\cocone_A$ and $\cocone_{t^*A}$, the functors that the colimits represent. Given some cocone to $A$, $(X, i_n: A_n\to X)$, we get a cocone to $t^*A$ by taking $(X, i_{t(n)}: A_{t(n)}\to X)$. However, it turns out that we can also go backwards, since $t$ is cofinal. If we are given $(Y,j_m : A_{t(m)}\to Y)$, we can define
$i_n : A_n\to Y$ by taking $N$ large enough that $t(N)\ge n$, and then defining $i_n$ to be the composite $A_n \to A_{t(N)} \xrightarrow{j_N} Y$. This is well defined regardless of the choice of $N$ because $\mathbb{N}$ is a poset and $(Y,j_m)$ are a cocone to $t^* A$. This gives us a cocone $(Y, i_n)$ to $A$. These operations are inverse to each other, so we have a natural isomorphism as desired.
Finally we need to show that when $t(n)\ge n$ for all $n$, and if $\colim A$ exists then $\tau$ induces an isomorphism on the colimits. First let's fix some notation. Let $i_n : A_n\to \colim A$ be the inclusions for the colimit of $A$, let $j_n : A_{t(n)}\to \colim t^*A$ be the inclusions of the colimit of $t^*A$, and let $\tau_n: A_n\to A_{t(n)}$ be the components of $\tau$.
Then we observe that $\tilde{\tau}$ is defined by
applying the universal property of the colimit $\colim A$ to the cocone
$(\colim t^*A, j_n \circ \tau_n)$. But we know (up to isomorphism) what the $j_n$ are. By the first half of this proof the $j_n$ are $i_{t(n)}$, so
$$j_n\circ \tau_n = i_{t(n)}\circ \tau_n = i_n,$$
since $\tau_n : A_n\to A_{t(n)}$ is a map in the diagram $A$ and $i$ is a
cocone to $A$. Thus after potentially composing with an isomorphism $(\colim t^*A, j_n)\to (\colim A, i_{t(n)})$, $\tilde{\tau}$ is actually given by the colimiting cone itself, so we have that for some isomorphism $\phi$, $\phi\circ \tilde{\tau} = 1_{\colim A}$, and thus $\tilde{\tau}$ is an isomorphism itself (namely $\phi^{-1}$). $\blacksquare$
Edited to fix the final argument
Build a modified version of the stable homotopy group colimit sequence as follows.
Fix $a$, let $P_{2n} = \pi_{n+a}(X_a)$, let $P_{2n+1} = \pi_{n+a}(\Omega\Sigma X_a)$, let the maps $f_{2n} : P_{2n}\to P_{2n+1}$ be $\pi_{n+a}(\eta_{X_a})$, and let the maps $f_{2n+1} : P_{2n+1}\to P_{2n+2}$ be given by the composite of $\pi_{1+n+a}$ applied to the structure map $\Sigma X_a\to X_{a+1}$ with the isomorphism $\pi_{n+a}(\Omega\Sigma X_a)\cong \pi_{n+1+a}(\Sigma X_a)$.
Let $d: \mathbb{N}\to \mathbb{N}$ be given by $d(n) =2n$, and let
$\delta  : P\to d^*P$ be the corresponding natural transformation.
Note that $d^*P$ is precisely the sequence that usually defines the stable homotopy groups.
Now consider the $\sigma$ natural transformation, $\sigma_P$, for this sequence. If we restrict to even $n$, then $\sigma_P$ corresponds to $\pi_{\bullet+a}(\eta)$. In other words $d^*\sigma_P = \pi_{\bullet + a}(\eta)$. We have a commutative diagram
$$
\require{AMScd}
\begin{CD}
P @>\sigma_P>> s^* P\\
@V\delta VV @V\delta VV \\
d^*P @>>\pi_{\bullet+a}(\eta)> d^*s^*P.\\
\end{CD}
$$
Termwise this commutative diagram is
$$
\require{AMScd}
\begin{CD}
P_n @>>> P_{n+1}\\
@VVV @VVV \\
P_{2n}=\pi_{n+a}(X_a) @>>\pi_{n+a}(\eta_{X_a})> P_{2n+1}=\pi_{n+a}(\Omega \Sigma X_a).\\
\end{CD}
$$
Now if we take colimits of this diagram of functors, three of the maps, $\sigma_P$ and both $\delta$s induce isomorphisms on the colimit. Therefore the last map does as well.

A: Thanks to jgon's wonderfully general argument, I understand the idea of it now. So let me write out a concrete argument where one can quickly see the intuition.
We show surjectivity and injectivity.

*

*Surjectivity: Let $[f:S^{n+a} \to \Omega \Sigma X_a] \in \pi_n(\Omega \Sigma X)$. If we denote by $[\alpha(f)]$ the image of $[f]$ under $\pi_{n+a}(\Omega \Sigma X_a) \cong \pi_{1+n+a}(\Sigma X_a)$, then we obtain $$ [f] = [\eta \circ \sigma_{a} \circ \alpha(f):S^{1+n+a} \to X_{1+a}] \in \operatorname{im}{(\pi_n(\eta))}.$$

*Injectivity: Say $[f], [g] \in \pi_n(X)$ agree after postcomposition with $\eta$. But then, they also agree after going far enough in the colimit system. On the other hand, this is the same thing as $[f] = [g]$.

Or even more succinctly: The map $\pi_n(\eta)$ moves the representative by one slot in the sequential colimit system. But doing this doesn't change the class of the representative.


text:
Q: MYOB ODBC Import Customer - address details not importing I am using the MYOB ODBC Driver to insert new customer records into MYOB (AccountRight Premier V19) from a .NET application but the records are not being imported correctly - specifically the address part of the insert is not working correctly and that then appears to impact on the location of all fields after those address fields. Everything seems to be shifted back one column.
Here is an example SQL statement as generated by the application:
Insert Into Import_Customer_Cards (CoLastName, CardStatus, CurrencyCode, Address1AddressLine1, Address1City, Address1State, Address1PostCode, Address1Country, Address1Phone1, Address1Phone2, Address1Phone3, Address1Fax, Address1Email, Address1Website, Address1ContactName, Address1Salutation, ABN) VALUES ('1 AAA TEST', 'N', 'AUD', '116 My Street', 'My Suburb', 'QLD', '4000', 'Australia', '31033383', '', '', '', '', '', 'This Bloke', '', '12345678910')

The value of '116 My Street' is NOT being imported and all subsequent fields are moving "up" one column so that the city winds up in the Address1StreetLine4 column, The state winds up in the city column etc. within MYOB itself.
Also, the phone numbers and ABN fields just disappear! I cannot find them in MYOB anywhere in the customer record after the import has completed.
I have checked the MYOB error log file and there is nothing there to suggest something major has gone wrong.
I have tried everything I know to try and get this to work but I am now stumped.
Does anyone here have any idea at all as to what might be causing this?
My guess is that these address fields need some sort of "special" formatting. Am I close?

A: *

*v19 address lines (1 to 4) are presented as if they are separate fields, but actually the driver maps them to a single field. One thing you could try is include Address1AddressLine[2..4] in your SQL statement, setting each to empty string. Be careful not to exceed 255 characters for all four (noted you're in no danger of that here).

*Do not try to import a currency code unless you are sure your flavour of v19 supports currency settings. Strange things can happen if you try to import values that are not recognised by a specific version of v19.

*The v19 ODBC driver actually invokes the same import/export routines exposed in the UI under the file menu. If you're not sure whether you're setting values correctly, try importing them using the UI (to do this take your import data and turn it into a csv). You will get better error responses.

A: It turns out this is a bug in the MYOB ODBC driver.
Rather than persevere with trying to find a resolution, we are upgrading to the latest version of MYOB so we can use the new API procedures and do away with the ODBC layer altogether.
This would appear to be the quickest and most reliable solution.