Q:

How to define a function with a parameter one string and return a new string which has the middle char repeated as much as the length of the str

Define a function called repeat_middle which receives as parameter one string (with at least one character), and it should return a new string which will have the middle character/s in the string repeated as many times as the length of the input (original) string.
Notice that if the original string has an odd number of characters there is only one middle character. If, on the other hand, if the original string has an even number of characters then there will be two middle characters, and both have to be repeated (see the example).
Additionally, if there is only one middle character, then the string should be surrounded by 1 exclamation sign in each extreme . If , on the other hand, the original string has two middle characters then the  returned string should have two exclamation signs at each extreme.
As an example, the following code fragment:
print (repeat_middle("abMNcd"))
should produce the output:
!!MNMNMNMNMNMN!!

A:

Try the following:
def repeat_middle(string):

    l = len(string)

    if l % 2 == 0:

        return "!!{}!!".format(string[int(l / 2 - .5) : int(l / 2 + 1.5)] * l)

    else:

        return "{}".format(string[int(l / 2)] * l)

odd  = "ham"
even = "spam"

print("Original odd length string: {}".format(odd))
print("Returned string: {}".format(repeat_middle(odd)))
print("")
print("Original even length string: {}".format(even))
print("Returned string: {}".format(repeat_middle(even)))

Where the sample output is:
Original even length string: spam
Returned string: !!papapapa!!

Original odd length string: ham
Returned string: aaa

You will find that print(repeat_middle("abMNcd")) does indeed output !!MNMNMNMNMNMN!!.


Q:

Config Elasticsearch and Kibana with docker

I'm working with docker for the first time.
I successfully installed elasticsearch and kibana on docker, but when I try to connect kibana with elastic I get a red status with the following errors:
ui settings   Elasticsearch plugin is red
plugin:elasticsearch@5.1.1    Authentication Exception
I'm not sure but I think the problem is kibana doesn't pass elastic x-pack authentication.
Now, I'm trying to disable this authentication via elastic yml file, according to the instructions here.
But I can't find the yml file anywhere (I searched /usr/share/elasticsearch but I can't find either config directory or elasticsearch.yml file).
How do I config elastic with docker?
P.S.
I'm working with ubuntu 16.04

A:

For Debian/Ubuntu/Mint, you can find the config files under /etc folder.
/etc/elasticsearch/elasticsearch.yml
Take a look at: https://www.elastic.co/guide/en/elasticsearch/reference/2.4/setup-dir-layout.html


Q:

kivy scrollview inside gridlayout on label

I trying to create a one screen app with one root rule set. by pressing a button i should see a scrollable text in the grid next to the button. In all the example solutions I see that scrollview is working in similar KV files that I have seen in other questions. Could someone please identify what I have missed in KV file.
my .py file:
import kivy
import string
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty
from kivy.properties import StringProperty
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window

class RootContainer(BoxLayout):
    instance = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(RootContainer, self).__init__(**kwargs)

    def clickAction1(self, instance):
        #identify the button pressed
        buttonText = instance.text
        self.lbl1.text = instance.text + " some text goes here ... "
        myresult = " this is scrolling text.\n " * 30
        self.lbl5.text = myresult

class MBApp(App):
    def build(self):
        return RootContainer()

if __name__ == '__main__':
    MBApp().run()

my KV file:
#:kivy 1.0.9
<RootContainer>:
    id: theRoot
    lbl1: my_labelC
    lbl5: my_labelCS
BoxLayout:
    orientation: 'vertical'
    spacing: 20
    padding: 20
    canvas:
        Color:
            rgb: 0, .33, 0
        Rectangle:
            pos: self.pos
            size: self.size
    Button:
        text: "This is 1st button"
        text_size: self.size
        size_hint: (.5,1)
        on_press: theRoot.clickAction1(self)
    Button:
        text: "This is 2nd button"
        text_size: self.size
        size_hint: (.5,1)
        on_press: root.clickAction1(self)

GridLayout:
    rows: 2
    cols: 1
    spacing: 10
    padding: 10
    canvas:
        Color:
            rgb: .7, .63, 0
        Rectangle:
            pos: self.pos
            size: self.size
    Label:
        id: my_labelC
        canvas.before:
            Color:
                rgb: 0,0,0
            Rectangle:
                pos: self.pos
                size: self.size
        text: "Header text for button clicked ......."
        text_size: self.size
    ScrollView:
        GridLayout:
            cols:1
            rows:1
            height: self.minimum_height
            Label:
                id: my_labelCS
                text: "Scrolling text goes here ....."

I hope this is not a duplicate. Any other suggestions to code are also welcome. Thank you.

A:

You don't set the size of your Label, so the default applies, as any widget, the defaults are
size: 100, 100
size_hint: 1, 1

since size_hintis 1, 1, and the parent is a layout, size itself is overriden by the parent's available space
since you set size: minimum_size in the parent layout, it'll give the minimum size its children require, but the Label doesn't ask for any space, it's size_hint of 1, 1 means that it's happy to take all the available space. Kivy solve this situation by not giving it any space, so the Label size ends up being 0, 0, and the GridLayout's size as well.
So you want to disable size_hint (at least for the height, of the Label, and instead set it to the texture heights
size_hint_y: None
height: self.texture_size[1]

Which is usually sided with setting the texture width to the available width, by setting text_size.
text_size: self.width, None
size_hint_x: 1    # this is the default, so this line is not required, but you want to be sure not to disable this default


Q:

Issue with SVN Commit for certain File Extension

I am having problem with uploading file to SVN repository from Tortoise SVN. I can upload all files except some specific files which always fail
List of Files
Rhino.Mocks.dll
System.Data.SQLite.dll
Microsoft.Ajax.debug.js
On SVN the error log contained  these entries.
[Tue Dec 15 15:03:33 2009] [error] [client xxx.xxx.xxx.xxx] Unable to PUT new contents for /Futures/!svn/wrk/31a3597a-ac95-9a4f-a234-bedc059f9c32/MyFolder/trunk/ExternalLibraries/RhinoMocks.dll.  [403, #0]
[Tue Dec 15 15:03:33 2009] [error] [client xxx.xxx.xxx.xxx] Could not prepare to write the file  [500, #160044]
[Tue Dec 15 15:03:33 2009] [error] [client xxx.xxx.xxx.xxx] Cannot write to the prototype revision file of transaction '11-n' because a previous representation is currently being written by this process  [500, #160044]
[Tue Dec 15 15:03:41 2009] [error] [client xxx.xxx.xxx.xxx] Unable to PUT new contents for /Futures/!svn/wrk/544b013d-1d26-ab4b-9ecf-4aab76f7bee3/MyFolder/trunk/ExternalLibraries/System.Data.SQLite.dll.  [403, #0]
[Tue Dec 15 15:03:41 2009] [error] [client xxx.xxx.xxx.xxx] Could not prepare to write the file  [500, #160044]
[Tue Dec 15 15:03:41 2009] [error] [client xxx.xxx.xxx.xxx] Cannot write to the prototype revision file of transaction '11-o' because a previous representation is currently being written by this process  [500, #160044]

Any help will be appreciated
Thank you,
The Mar
Edit: Results:
Turning off AniVirus didnt help in my case.
I restarted Apache - Same results
I copied the dlls  listed above and did a committ- it worked. It seems the cause of the issue might have been corrupted dll, but then when did it get corrupted? The project was able to use these dlls without any exceptions. I opened the javascript file adding an extra space in the header and saved it back. I was able to commit the file.
For now the issue is solved but still not sure what was the cause.
I am new to SVN - should I have done something else to the files other than Add before commiting?

A:

my guess: an antivirus


Q:

Set a UserControl Property to Not Show Up in VS Properties Window

I have a UserControl in my Asp.net project that has a public property. I do not want this property to show up in the Visual Studio Property Window when a user highlights an instance of the UserControl in the IDE. What attribute (or other method) should I use to prevent it from showing up?
class MyControl : System.Web.UI.UserControl {
  // Attribute to prevent property from showing in VS Property Window?
  public bool SampleProperty { get; set; }

  // other stuff
}

A:

Use the following attribute ...
using System.ComponentModel;

[Browsable(false)]
public bool SampleProperty { get; set; }

In VB.net, this will be:
<System.ComponentModel.Browsable(False)>

A:

Tons of attributes out there to control how the PropertyGrid works.
[Browsable(false)]
public bool HiddenProperty {get;set;}


Q:

Making an Entity Framework Model span multiple databases

Is it valid to do something such as
CREATE SYNONYM [dbo].[MyTable] FOR [AnotherDatabase].dbo.[MyTable]
and then modify Entity Framework's edmx file to read this object like it would any other table?
I did a quick sample test and it seems to work fine for selecting and updating, but I wanted to know if there was any reason why I shouldn't be doing this
I am getting the table definition by creating an edmx file pointing to the 2nd database, building out the entities there, then copy/pasting the definition into the 1st database's edmx file.
UPDATE
If anyone is interested, I wrote up what I did to make an edmx file span mulitple databases here. It includes scripts for generating synonyms and merging edmx files.

A:

If you made a test and it worked you probably showed something nobody else know about. Till now I always answered this type of question: It is not possible to use single model with two databases (with some more ugly workaround based on views hiding tables from the second database). Now I know two workarounds.
The only disadvantage of this approach is that all changes made manually to SSDL part of your EDMX are always lost if you run Update model from database. This means either manual development of EDMX (which is quite hard work) or using some tool / script which will add your changes after each update from database.


Q:

Word for repetition of the same word before and after comma?

How do you describe a type of writing in which a word is repeated (e.g. a word written before as well as after a comma), such as:

"My point is that we cannot, cannot believe in a loving, forgiving, merciful, compassionate God that is exclusive." —Quora Source
"He just made the minimum height to ride the roller coaster and he's just an awesome, awesome boy." —Example sentence suggested by @1006a.
"His speech is quite, quite fabulous"

One of my coleagues suggested the term anaphora which denotes:

the use of a word referring back to a word used earlier in a text or conversation, to avoid repetition, for
  example the pronouns he,
  she, it, and they and the
  verb do in I like it and so do they.
the repetition of a word or phrase at the beginning of successive clauses.
the part of the Eucharist
  which contains the
  consecration, anamnesis,
  and communion.

I think it's not a word which I am looking for because it refers to the repetition of a word or phrase from the starting of a sentence. See the following example of anaphora:

Now is the time to make real the promises of democracy. Now is the time to rise from the dark and desolate valley of segregation to the sunlit path of racial justice. Now is the time to make justice a reality for all of God’s children.

A:

The technical term is epizeuxis:

In rhetoric, an epizeuxis is the repetition of a word or phrase in immediate succession, typically within the same sentence, for vehemence or emphasis.

(source: Wikipedia)
but I must admit I had to look it up. According to LitCharts, it comes from an ancient Greek word meaning "fasten together."

A:

Palilogia or palilogy/palillogy (synonymous to epizeuxis) also describe this type of repetition in rhetoric.


Q:

Getting a program to start over and get a new value?

I am working with a program which requires a value to put in a variable and do some stuff on it.  The problem is that I want the program to start over again and ask the user for a new value to process the new value again.
For example look at this code, which requires a number as a grade to rate it.  When the processing was done I want the program to ask for a new grade ( next student for instance ).
#include <iostream.h>

int main (int argc, const char * argv[])
{
    int n;
    cout<< " Please Enter your grade : " ;
    cin>>n;
    switch (n/10) {
        case 10: cout<< " A+ : Great! ";

        case 9:
            break;
        case 8: cout<< " A : Very Good ";
            break;

        case 7: cout<< " B : Good " ;
            break;
        case 6:
        case 5:
        case 4:
        case 3:
        case 2:
        case 1:
        case 0: cout<< " Failed ";
            break;

        default:
            break;
    }
    return 0;
}

A:

What you need is a while loop
int main (int argc, const char * argv[])
{
    int n;
    while(1) {
        cout<< " Please Enter your grade : " ;
        cin>>n;
        switch (n/10) {
            case 10: cout<< " A+ : Great! ";

            case 9:
            case 8: cout<< " A : Very Good ";
                break;

            case 7: cout<< " B : Good " ;
                break;
            case 6:
            case 5:
            case 4:
            case 3:
            case 2:
            case 1:
            case 0: cout<< " Failed ";
                break;

            default:
                break;
        }
        cout<<"do you wish to continue?(y/n)";
        cin>>some_declared_variable;
        if (some_declared_variable == 'n')
            break; //hopefully this will break the infinite loop
    }
    return 0;
}


Q:

Image in Telerik Radgrid EditCommandColumn doesn't match EditImageUrl

I have a detail table within a Telerik Radgrid that needs to allow inline editing. Everything in the grid works, except for the images displayed for Edit, Update, and Cancel operations aren't displaying. Instead they appear to be generic images.
The only link I was able to find regarding this issue is here but the instructions didn't resolve my issue. This is the grid displaying the incorrect images:
                    <radG:GridTableView runat="server" AllowSorting="true" AllowFilteringByColumn="true" AutoGenerateColumns="false"
                        ShowFooter="false" DataKeyNames="sysId" HierarchyLoadMode="ServerOnDemand"
                        GridLines="None" Name="RadGrid1" EditMode="InPlace" Width="100%" Height="75%" >
                        <EditFormSettings>
                            <EditColumn UniqueName="EditCommandColumn1" ButtonType="ImageButton" EditImageUrl="~/APP_THEMES/MASTERPAGE/btnEdit.gif"
                                UpdateImageUrl="~/APP_THEMES/MASTERPAGE/btnSaveSM.gif" CancelImageUrl="~/APP_THEMES/MASTERPAGE/btnCancelSM.gif"
                                UpdateText="Save" InsertText="Save" InsertImageUrl="~/APP_THEMES/MASTERPAGE/btnSaveSM.gif">
                            </EditColumn>
                        </EditFormSettings>
                        <Columns>
                            <radG:GridEditCommandColumn UniqueName="EditCommandColumn"
                                ButtonType="ImageButton" EditImageUrl="~/APP_THEMES/MASTERPAGE/btnEdit.gif">
                                <ItemStyle Width="5%" />
                            </radG:GridEditCommandColumn>

The correct icons should look like this:
But the generic ones that appear show this:

I know the paths are correct, because they are the same as the images used in other non-detail grids I have in the site. It's not a huge issue as it functions correctly, but it is definitely ugly and pretty frustrating.
What am I missing here?
Edit
I should have clarified that I tried using the same work present in the owner table's GridEditCommandColumn for the DetailTable which I'm showing now:
                   <radG:GridEditCommandColumn UniqueName="EditCommandColumn" UpdateText="Save" InsertText="Save"
                        ButtonType="ImageButton" InsertImageUrl="~/APP_THEMES/MASTERPAGE/btnSaveSM.gif"
                        UpdateImageUrl="~/APP_THEMES/MASTERPAGE/btnSaveSM.gif" CancelImageUrl="~/APP_THEMES/MASTERPAGE/btnCancelSM.gif"
                        EditImageUrl="~/APP_THEMES/MASTERPAGE/btnEdit.gif">
                        <ItemStyle Width="5%" />
                    </radG:GridEditCommandColumn>

A:

Apply your images to the GridEditCommandColumn:
                    <telerik:GridEditCommandColumn UniqueName="EditCommandColumn"
                        ButtonType="ImageButton" EditImageUrl="~/images/icon_16x16.png"
                        UpdateImageUrl="~/images/icon_16x16.png" CancelImageUrl="~/images/icon_16x16.png"
                        UpdateText="Save" InsertText="Save" InsertImageUrl="~/images/icon_16x16.png">
                        <ItemStyle Width="5%" />
                    </telerik:GridEditCommandColumn>


Q:

What does the at sign, or '@', mean as a prefix to an angular module as a package name?

In my `package.json' file, it seems that all the Angular depedencies are prefixed by @. What does this mean? E.g.
"dependencies": {
    "@angular/common": "2.0.0-rc.5",

Why not just as below, with no @?
"dependencies": {
    "angular/common": "2.0.0-rc.5",

A:

npm has two types of modules:

Global modules - npm install mypackage
Scoped modules - npm install @myorg/mypackage

Scopes are a way of grouping related packages together, and also affect a few things about the way npm treats the package.


Q:

C++ Instances VS pointers VS references

I've a program which creates many instances of my own Class. Then I operate them: read, change, pass them to some third party methods etc.
There are three questions.

Do I store an vector of instances or a vector of pointers? Why?
If I do not want to change an instance do I pass to the function an instances or pointers to it? Why?
If I do want to change an instance, do I pass a pointer or a reference? Why?

Thanks in advance!
Class example:
class Player {
    public:
        static const char               width = 35;
        static const char               height = 5;
        static const char               speed = 15;

        int                             socketFD;
        float                           xMin;
        float                           xMax;

        char                            status;
        float                           x;
        float                           y;
        char                            direction;

                                        Player ( int );
        void                            Reset();
        void                            Move();
        void                            SetHost();
        void                            SetClient();

    private:
        void                            EscapeCheck();
};

A:

Do I store an array of instances or an array of pointers? Why?

If Class is a base class, and you want to prevent object slicing, you store pointers. Otherwise, objects.

If i do not want to change an instance do I pass to the function an instances or pointers to it? Why?

If you pass by value, you don't modify the original object because you're working on a copy. If you pass a pointer or a reference, you mark it as const:
void foo ( MyClass const* );
void foo ( MyClass const& );

If i do want to change an instance, do i pass a pointer or a reference? Why?

Either. I personally prefer references, pointers are more tightly connected to dynamic allocation.
Nowadays, RAII is often used, so an excellent alternative is to use smart pointers instead.

A:

Do I store an array of instances or an array of pointers? Why?

This really depends on the use case. Either solution can be OK, depending on context. You may want to store base classes of a polymorphic type, or you might want to avoid copying elements (for example, when dealing with non-copyable types). In these cases, you should store pointers or smart pointers.

If i do not want to change an instance do I pass to the function an instances or pointers to it? Why?

Then you should pass a const reference (reference to a const instance)
void foo(const Foo& f);

If i do want to change an instance, do i pass a pointer or a reference? Why?

Then you should pass a non-const reference (reference to a non-const instance). This assumes you really want to change an existing instance:
void foo(Foo& f);

But when would you use pointers then? Then only case I can think of right now is when there is a possibility for the passed entity to have an invalid or null value. With references this is impossible, or at least not trivial to implement. Pointers can be set to 0, NULL (the same) or nullptr in C++11.
void (Foo* f) {
  if (f) {
    // do something with pointee
  } else {
    // deal with it
  }
}

A:

For number two, it kind of depends. Most efficient would probably be to pass a constant reference instead.
And generally, try to avoid pointers as much as possible. If you have to use pointers, use the smart pointers.


Q:

initializer element is not constant

I have read other answers on this topic, but they didn't help me.
I declared a global stuck:
    typedef stuck {
    ....
    } a;

and right after i initialized a dynamic array of this struct:
    a * severalA= (a*)malloc (sizeof (a)*3);

after compiling i get error : "initialize element is not constant" on the malloc type (bold).
any idea what am i missing here?
i tried to add const before the initialization with no success.

A:

In C language objects with static storage duration have to be initialized with constant expressions or with aggregate initializers containing constant expressions.
My guess is that you are trying to define several A as a global variable - Is that true?
In that case, malloc() is not a a constant expression and cannot be used.


Q:

jQuery Not Defined within a function

Alright, here's a puzzler. I've got a jQuery function to display a PHP generated list of announcements for a website via .fadeIn/.fadeOut; the very first thing loaded on the page is jQuery 1.11.xx from a CDN. I'm running Bootstrap, fullCalendar, SmartMenus, etc., and jQuery is most definitely loading.
Except within the setInterval() to update the announcement. This is rough-code, some functionality isn't present, but to my mind it should be doing an animation.
var announcementArray = [];
var announcementSource = "../announcements.php";
var totalAnnc;

$.getJSON(announcementSource, function(data) {
    announcementArray = data.concat();
    totalAnnc = announcementArray.length;
});

var count = 0;

var fadeAnnc = function() {

    $('#announcementArea').text(announcementArray[count].announceText);
    $('#announcementArea').fadeIn('slow',function() {
        $('#announcementArea').css('display','block');
    }).delay(2000).fadeOut('slow',function() {
        count = (count + 1) % totalAnnc;
    });
};

setInterval(function() {
    fadeAnnc();
}, 3000);

Instead, when I run the page, I get a "function not defined" error for any jQuery function that's called within the setInterval(). If I call using document.getElementById('announcementArea').innerHTML = etc., it works, but doing the fade in/out via DOM manipulation seems to be more work than is needed when jQuery is available and working everywhere else on the page.
I've tried a few scope adjustments and have been working on what should be simple code for the last 5 hours. So, where's my glaring error? ;)

A:

Not sure what kind of scope issue you are having (looks like it's the result of unposted code, as everything in your question looks OK), but if you want a fairly foolproof way of passing along the jQuery object, you could always pass it as a parameter:
var fadeAnnc = function($) {

    $('#announcementArea').text(announcementArray[count].announceText);
    $('#announcementArea').fadeIn('slow',function() {
        $('#announcementArea').css('display','block');
        }).delay(2000).fadeOut('slow',function() {
        count = (count + 1) % totalAnnc;
    });
};

setInterval(function() {
    fadeAnnc($);
}, 3000);

Based on your updated answer, here's another possible solution:
(function($){

    var announcementArray = [];
    var announcementSource = "../announcements.php";
    var announcementSpace = "#announcementArea";

    $.getJSON(announcementSource, function(data) {
        announcementArray = data.concat();
        if (announcementArray.length === 0) {
            $('#anncRow').css('display','none');
        }
    });

    var count = 0;
    var masterCount = 0;
    var totalAnnc =  announcementArray.length;
    var timer;

    var fadeAnnc = function() {
        if (announcementArray.length > 0) {
            $(announcementSpace).html(announcementArray[count].announceText);
            $(announcementSpace).fadeIn(750, function() {
                $(announcementSpace).css('display','block');
            }).delay(4500).fadeOut(750, function() {
                $(announcementSpace).css('display','hidden');
            });
        }
        count += 1;
        if ((count % announcementArray.length) == 0) {count = 0}
    };

    setInterval(fadeAnnc, 6000);

}(jQuery));

$ is defined as a function parameter and thus overrides the globally scoped $ within the function body, protecting it's definition for your code. This is actually exactly what jQuery recommends when creating an extension.


Q:

How to Open Two Excel Files in Multiple Monitors in Windows 7 pro excel 2010?

I want to open two (or more) excel windows on different screen (extended displays), But was not able to. I tried few solutions found on Google.
One worked, that was making changes in registry and after that checking the option 'Ignore other application that use DDE'. Now I am able to get separate excel windows but same time I get this error 'There was a problem sending the command to the program'
How to avoid this error. Can someone help me in this?
Thanks
Ritesh

A:

This is what works for me

Open your first Excel file and place it on the screen you want
Open a new Excel file from the Excel icon (New instance of excel needed)
The new file will open on top of the one you have already opened.  Drag it to the other screen
Drag the icon for the second Excel file INTO the new (blank) Excel document

Excel is a difficult beast sometimes

A:

What I've done is opened up one saved excel document.  Then, instead of locating the second excel document and double clicking on it to open, I just went to the start button and clicked on Excel to open up a new blank document.  This will give you 2 excel windows.  In the 2nd excel window, open up your second excel document by going to file / open / and then browse for your 2nd excel file.
Now you will have 2 excel documents, each in their own window.

A:

Just follow these steps and there is no need to replace the icon (at least in Windows 7):
Start -> type “run” into the “Search Programs and files” and hit Enter -> type regedit and hit Enter:
Left column: HKEY_CLASSES_ROOT/Excel.Sheet.8/shell/Open/commend:
Right column {adding (space)”%1″}: (be sure to include the quotation marks when typing)
Double Click on (Default) and write – “C:\Program Files\Microsoft Office\Office12\EXCEL.EXE” /e “%1″
Right Click on Command – choose “rename” and add something to the name – for example 2 (commend2).
Left column: HKEY_CLASSES_ROOT/Excel.Sheet.8/shell/Open/ddeexec:
Right Click on the folder ddeexec and choose “rename” and add something to the name – for example 2 (ddeexec2)
Left column HKEY_CLASSES_ROOT/Excel.Sheet.12/shell/Open/commend:
Right column {adding (space)”%1″}
Double Click on (Default) and write – “C:\Program Files\Microsoft Office\Office12\EXCEL.EXE” /e “%1″
Right Click on Command – choose “rename” and add something to the name – for example 2 (commend2).
No restart needed. You can do this for .CSV files as well. Have Fun, and please share this answer with others. If the icon is not listed, you can right-click and go to Properties on any file that you wish to open with Excel, click the Change… button under the Opens With section, Browse…, look under C:\Program Files\Microsoft Office\Excel.exe (or under C:\Program Files (x86)\Microsoft Office\Excel.exe) and double click the EXCEL.exe; You may have to check the box under the Opens With section that states “Always use this file type…”


Q:

What does the error C4996 mean?

Here is a simple C++ code:
#include <cstring>
using namespace std;

int main(int argc, _TCHAR* argv[])
{
    char str[80];
    cout << "輸入字串：";
    gets(str);
    cout << "輸入的字串：" << str << endl;
    return 0;
}

When compiling it, I get the following error:

"错误1  error C4996: 'gets': This function or variable may be unsafe.
Consider using gets_s instead. To disable deprecation,
          use _CRT_SECURE_NO_WARNINGS. See online help for details."

A:

In genuine C++11 or C++14 the correct way to read an entire line is std::getline or std::basic_istream::getline.
Also, you'll better flush the output before reading an input; remember that C++ and C standard IO functions are buffering.
The old C89 gets function is deprecated since a long time (probably more than ten years), and now forbidden because it is so dangerous (can't avoid a buffer overflow). So please forget it (in C99 or C11, use fgets instead, on POSIX with C99 or C11, use getline; in C++11 or C++14 use as I said std::getline or std::basic_istream::getline).
Your main's body should be:
string str;
cout << "輸入字串：" << flush;
getline(cin,str);
cout << "輸入的字串：" << str << endl;
return 0;

The advantage of using a std::string is that your user could input an arbitrarily long line (up to implementation limits, perhaps million of characters).
If you are coding on a POSIX system like MacOSX or Linux, you could use the GNU readline library and function (see also ncurses) when reading on a terminal. The big advantage is that your user is given editing ability (and completion) when typing his line.
PS. General hint when programming: read the documentation of every function that you are using before coding.


Q:

How to have tmux prompt me for the status-left text to display?

I want to change status bar left message to anything I type.
Just like when I press Ctrl+B F I have this prompt in status bar :
(find-window)

I'd like to press, say Ctrl+B E and have a prompt like :
(status-left)

Then on Enter the text I've typed would be assigned to status-left.
I DON'T want to have to call a shell script that would print the prompt in the shell window and print entered value (is that even possible?), I want the prompt to happen in the status bar itself.
How should I go with that? If i put in my .tmux.conf :
unbind e
bin e set status-left

It quite understandably prints Empty value message when I press Ctrl+B E

A:

command-prompt is probably what you are looking for.
bind-key S command-prompt -p "New Status: " "set -g status-left '%1'"


Q:

Proving sufficient conditions

I am wondering if a "reverse necessary condition" implies sufficiency. Suppose your objective is to solve
$$
\min_{x\in X} f(x)
$$
where $X$ is a convex and compact subset of $\mathbb{R}^n$ and $f(\cdot)$ is a continuously differentiable function. The necessary condition for $x^*\in X$ to be optimal is that $$
(x-x^*)f'(x^*)\geq 0
$$
for all $x\in X$. However, suppose that $f$ is not convex so we don't know if the necessary conditions are also sufficient. Instead, consider the following condition:
$$
\tag A
f'(x)(x^*-x)\leq 0
$$
for all $x\in X$. Essentially, (A) implies that starting from any $x
\in X$ and moving in the "direction" of $x^*$ is always beneficial. More formally, assuming $f$ is Malliavin differentiable, (A) is implied by  $f(\epsilon x^*+(1-\epsilon)x)\leq f(x)$ for small enough $\epsilon >0$.
Does (A) imply that $x^*$ is optimal?

A:

I must be frank, I am not up to speed on the consequences of Malliavin differentiability. But it seems that under some mild conditions on $f$ it ought to be so. Suppose that there exists a point $y$ such that $f(y) < f(x^*)$. Define:
$$g(t) = f((1-t)x^* + ty) = f(x^* + t(y-x^*))$$
Then for $t\in[0,1]$, with $g(0) = f(x^*)$, and $g(1) = f(y)$, with $g(1) < g(0)$. Then for $t>0$, we have
\begin{aligned}
g'(t) &= \langle \nabla f(x^* + t(y-x^*)), y-x^*\rangle \\
&= -t^{-1} \langle \nabla f(x^* + t(y-x^*)), x^* - (x^* + t(y-x^*)) \rangle \geq 0.
\end{aligned}
(and the continuity of the derivative ensures that $g'(0)\geq 0$ as well). Therefore,
$$0 \leq \int_0^1 g'(t) dt = g(1) - g(0) < 0$$
which is a contradiction.


Q:

height for absolute position is not working and stopping jquery from working (example)

look at this please http://jsfiddle.net/xhpqa/4/
the sub_menu div keeps hiding if mouseover it because it has no height (to expand with content if i specify height or min-height and max-height it doesn't expand)

A:

add this line in your code it will serve your purpose. please check i have added some css styles at proper locations:
EDIT:
   $(document).ready(function() {
// getting links from db and show sub_menu div //
    $(".menu_item").mouseover(function(){
        $(this).children().slideDown(100,function(){});
        $(this).children(".sub_menu").css({'display':'block'});
    });

// hiding sub_menu div //
    $(".menu_item").mouseout(function(){
        $(this).children(".sub_menu").slideUp(100);
        $(this).children(".sub_menu").css({'height':'auto', 'display':'none' });
    });

// keeping sub_menu div visible on mouse over //
    $(".sub_menu").mouseover(function() {
        $(this).stop();
        $(this).css({'display':'block'});
    });

        $(".sub_menu").mouseout(function() {
        $(this).parent().css("background-image","url(images/menu_bg.gif)");
        $(this).slideUp(10);
            $(this).css({'height':'auto', 'display':'none'});

    });

// document ready end
});

since you are using slideUp and slideDown function of jQuery.
when you mouse over/ out quickly the height is not properly set to your sub-menu div.
slideUp happens when your element is display:block (i.e visible) and its height starts from actual height til it becomes zero (0).
slideDown happens when the height of the element is started to increase from zero (0) to it actual height and it is display:none (i.e hidden).


Q:

How can I get rid of artifacts in my OpenGL ES iPhone app?

I'm using the Texture2D class from the CrashLanding sample code.  I'm getting strange artifacts around my images in both the simulator and the phone.  The artifacts are little gray borders around the textures.  The borders are inconsistent and do not surround the entire texture.  I'm using pngs.

A:

Hey MrDatabase - It sounds like the problem is that your texture images have premultiplied alpha. I've had this problem on the iPhone too - the PNG compression that it performs when you build your app automatically premultiplies all the alpha values. If you're using glBlend(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), you're basically applying the alpha twice - try using glBlend(GL_ONE, GL_ONE_MINUS_SRC_ALPHA) instead. There's lots of stuff in the Apple forums about this :-)


Q:

Count subobjects in json

I have a json object that could look like this that i need to loop through. The problem is when i do this
for (int i = 0; i <= jsonResult.count-1; i++) {
}

It only returns 1 since there is only 1 object in match, but there is a lot of subobjects that i would like to count i've tried doing something like this
[jsonResult valueForKey:@"match"].count

But that is not possible.
How can i count all the matches (the subobjects)?
The json code:
match =     (
            {
        awayteam = Elche;
        hometeam = Espanol;
        location = "Estadi Cornell\U00e0-El Prat";
        playdate = "2014-03-09";
        time = "04:00:00";
    },
            {
        awayteam = Betis;
        hometeam = Elche;
        location = "Mart\U00ednez Valero";
        playdate = "2014-03-16";
        time = "04:00:00";
    };

}

A:

Your top level NSDictionary object contains an NSArray of sub NSDictionary's. So you should be able to do something like:
int subObjects = ((NSArray *)jsonResult[@"match"]).count;
// subObjects is count of all sub objects


Q:

Что означает ... (троеточие) в python?

Увидел следующую конструкцию:
class BadStatus(Exception):
    ...

Что она означает? Есть ли отличия от:
class BadStatus(Exception):
    pass

A:

Ellipsis Object или ... - это литерал встроенной константы (Ellipsis).
 Типа есть True, False, None, ... .
... можно использовать там, где у нас пустое тело класса или оператора (вместо pass),
т.е. можно сказать пока здесь пусто, но продолжение следует или потом напишу.
>>> ...
Ellipsis
>>> type(...)
<class 'ellipsis'>
>>> bool(...)
True


Q:

Accessing data using facebook graph API in fb_graph [rails]

I encounter something annoying while playing around with the facebook graph API. I'm using fb_graph which is a ruby wrapper for the facebook sdk. I'm not sure if this issue I encounter is a limitation of the facebook sdk or I should contact the owner of fb_graph.
So, using fb_graph, this is how I would connect to a user:
jane = FbGraph::User.fetch('janeid', :access_token => "janeaccesstoken")

jane.friends will list all of jane's friends. However, if I try to get jane's friends birthday or email, it returns nil. In other words,
jane.friends[0].birthday => nil

But, I can access friends[0] birthday this way:
bill = FbGraph::User.fetch(jane.friends[0].id, :access_token => "janeaccesstoken")

In other words, if I wanted a list of all jane's friends' birthdates, I cannot do this:
@jane.friends.each do |friend|
  puts friend.birthday
end

instead, it will have to be something like this
@jane.friends.each do |friend|
  friendname = FbGraph::User.fetch(friend.id, :access_token => "janeaccesstoken")
  puts friendname.birthday
end

I guess it's not too bad but it does make me wonder why this is the case, because actually only some info is nil. Name, for example, is not.
@jane.friends.each do |friend|
  puts friend.name # => works!
end

A:

The answer is here:
https://github.com/nov/fb_graph/issues/237.


Q:

Multiple IntegrationFlows attached to the same request channel in Gateway method

Given I have application which uses Spring Integration and I define gateway:
@Component
@MessagingGateway
public interface SmsGateway {

    @Gateway(requestChannel = CHANNEL_SEND_SMS)
    void sendSms(SendSmsRequest request);
}

public interface IntegrationChannels {
    String CHANNEL_SEND_SMS = "channelSendSms";
}

I also attach IntegrationFlow to CHANNEL_SEND_SMS channel:
@Bean
public IntegrationFlow sendSmsFlow() {
    return IntegrationFlows.from(CHANNEL_SEND_SMS)
            .transform(...)
            .handle(...)
            .get();
}

Whenever I call sendSms gateway method from business code, sendSmsFlow is executed as expected.
When I want to attach another IntegrationFlow to the same CHANNEL_SEND_SMS channel, e.g.
@Bean
public IntegrationFlow differentFlow() {
    return IntegrationFlows.from(CHANNEL_SEND_SMS)
            .transform(...)
            .handle(...)
            .get();
}

then this differentFlow is not executed.
Why does it behave this way?
Is there any solution to make it work for both flows?

A:

The default channel type is DirectChannel and messages are distributed to multiple subscribed channels in a round robin fashion by default.
Declare CHANNEL_SEND_SMS as a PublishSubscribeChannel if you want each flow to get every message.
This will only work with a void gateway method; if there is a return type, you will get the first (or random if there is any async downstream processing) and the others will be discarded.


Q:

Is there a suitable way to cluster time series where only four values are possible(0,1,2,4) and length is not fixed?

I am trying to cluster customers consumption behaviors using time series techniques. Customers buy tokens and use them whenever they want (a max of 4 tokens per day).
This is a sample of what the customers journeys time series (x = days after first order , y = number of tokens consumed per day) and it look alike the image below.

I tried clustering with derived variables (median delay between two events, standard deviation of the delays, total number of tokens, time between first and last consumption, mean number of tokens consumed per consumption event ...). I used K-means and this gave me some good results but it wasn't enough to spot all patterns in data. I looked at some papers about the use of Dynamic time warping in such cases but I have never used such algorithms..
Is there any materials (demos) on the use of such algorithms to cluster such time series ?

A:

Yes.
There are many techniques that can be useful here.
The obvious approach from literature would be HAC with DTW.


Q:

Strange seg fault error, gdb is unhelpful

I have a little program that is trying to emulate reading a (non-standard) packet header and processing it.
I'm getting a strange seg fault when I run the program, on analysis with gdb, I see that code executes entirely and THEN give me a "0x00000000 in ?? ()".
I have never seen this kindof an error before, and don't have a clue as to what could be causing it.
I compiled the code as gcc -g header.c -lcrypto -lssl
Here is the code
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include"hash_list.c"

void process(unsigned char header[48]);

int main()
{

    unsigned char header[48];
    unsigned short int responseCode_Fail = 255;
    unsigned short int responseCode_Pass = 0;
    unsigned short int packlen = 65000;
    long long int packetnumber = 2345678;

    memset(&header, 0, 96);
    strcpy(header,"FILELST");
    memcpy(&header[8], &responseCode_Fail, sizeof(responseCode_Fail));
    memcpy(&header[10], &packlen, sizeof(packlen));
    memcpy(&header[16], &packetnumber, sizeof(packetnumber));

    unsigned char result[MD5_DIGEST_LENGTH];
    calcmd5("sample.txt", result);
    memcpy(&header[32], &result, sizeof(result));

    process(header);

    return 0;
}

void process(unsigned char header[48])
{
    unsigned short int responseCode;
    unsigned short int packlen;
    long long int packetnumber;
    unsigned char md5hash[MD5_DIGEST_LENGTH];

    memcpy(&responseCode, &header[8], sizeof(responseCode));
    memcpy(&packlen, &header[10], sizeof(responseCode));
    memcpy(&packetnumber, &header[16], sizeof(packetnumber));
    memcpy(&md5hash, &header[32], sizeof(md5hash));
    printmd5(md5hash);

    printf("CODE: %hu\n",responseCode);
    printf("LEN: %hu\n",packlen);
    printf("PNO: %lld\n",packetnumber);
    if(strncmp(header, "LULZ?", 8) == 0)
    {
        printf("Recieved Peer query.\n");
    }
    else if(strncmp(header, "LULZ.", 8) == 0)
    {
        printf("Recieved Peer query confirmation.\n");
    }
    else if(strncmp(header, "FILELST", 8) == 0)
    {
        printf("Recieved File list\n");
    }
    else if(strncmp(header, "DWNLOAD", 8) == 0)
    {
        printf("Recieved Download request.\n");
    }
    else if(strncmp(header, "UPLOAD", 8) == 0)
    {
        printf("recieved upload from peer ?\n");
    }
    else if(strncmp(header, "ERROR", 8) == 0)
    {
        printf("Recieved Error\n");
    }
    else if(strncmp(header, "LIST", 8) == 0)
    {
        printf("Recieved Peer query for filelist.\n");
    }

    return;

}

This is the output I get
4768bfdd77920fe0b4f25f173e568266
CODE: 255
LEN: 65000
PNO: 2345678
Recieved File list
Segmentation fault (core dumped)

A:

unsigned char header[48];

...

memset(&header, 0, 96);

This sounds wrong.


Q:

Internationalization Best Practices / Rails App

I am new to ruby & rails and have started building an application.
My goal is to build this in a way I can easily translate the contents of the rails app and display the website contents in a locale preferred by registered user.
Appreciate any inputs on some of the best practices or references to any documentation to read, to build a web application that can be easily translated?
Thanks,
Krish.

A:

Check out the Rails Internationalization (I18n) API. It does everything you've described.

A:

Also check out Globalize3, it became a standard for model translations. Very useful.

A:

You can use ready_for_i18n  plugin that convert your erb to desired form.It saves some time.


Q:

Defining a class using objects and strings with python

I'm told to

Define a new class, Track, that has an artist (a string), a title
  (also a string), and an album (see below).

Has a method __init__(self, artist, title, album=None). The arguments artist and and title are strings and album is an Album
  object (see below)
Has a method __str__(self) that returns a reasonable string representation of this track
Has a method set_album(self, album) that sets this track's album to album

This is my first time working with classes, and I was wondering if someone can explain the difference between using strings and objects in Python. I read up about __str__ also, but I'm not exactly sure how it works. It says the "the string returned by __str__ is meant for the user of an application to see" but I never see the return value for my inputs. Can someone explain the use of __str__ please?
I'm not sure if I followed the guideline correctly either, if someone could confirm what I did is correct, that would be great.
class Track:
    def __init__(self, artist, title, album=None):
        self.artist = str(artist)
        self.title = str(title)
        self.album = album

    def __str__(self):
        return self.artist + " " + self.title + " " + self.album

    def set_album(self, album):
        self.album = album

Track = Track("Andy", "Me", "Self named")

A:

Your class is good for me but if you really want the attributes be strings you should consider use @property decorator and make propper setters and getters.
Example below:
class Track:
    def __init__(self, artist, title, album=None):
        self._artist = str(artist)
        self._title = str(title)
        self._album = album

    def __str__(self):
        return self.artist + " " + self.title + " " + self.album
    #example for artist
    @property
    def artist(self):
        return self._artist
    @artist.setter
    def artist(self, artist):
        if artist != type("string"):#ensure that value is of string type.
            raise ValueError
        else:
            self._artist = artist
    #this way you could properly make setters and getter for your attributes
    #same ofr the other stuff

Track = Track("Andy", "Me", "Self named")


Q:

Update Error de Sintaxis

Buenos dias, estoy intentando hacer un "Update" a dos tablas dentro de mi base de datos pero al hacerlo me marca un error y no soy capaz de encontrar el error, hasta donde entiendo la sintaxis de mi query esta bien. Pero aun asi phpmyadmin me lanza el error de que algo no esta bien con la sintaxis.
Aqui el Codigo:
UPDATE
    pm_t_bb
INNER JOIN pm_t_pt ON(pm_t_bb.OT = pm_t_pt.OT)
SET
    pm_t_bb.BB_1 = 'R' pm_t_bb.BB_2 = 'R' pm_t_bb.BB_3 = 'R' pm_t_bb.BB_4 = 'R' pm_t_bb.BB = '100' pm_t_bb.F_Up = Now() pm_t_pt.BB = '1.5'
WHERE
    pm_t_bb.OT = '1010176'

La una diferencia respecto a cuando funcionaban mis actualizaciones era que estaban en consultas separadas y por cuestiones de performance pues las uni.
Gracias de Antemano!
Saludos a todos!

A:

Proba de la siguiente forma:
UPDATE
     A
SET
    pm_t_bb.BB_1 = 'R',
    pm_t_bb.BB_2 = 'R',
    pm_t_bb.BB_3 = 'R',
    pm_t_bb.BB_4 = 'R',
    pm_t_bb.BB = '100',
    pm_t_bb.F_Up = Now() ,
    pm_t_pt.BB = '1.5'

FROM pm_t_bb A
    INNER JOIN pm_t_pt B ON A.OT = B.OT

WHERE
    A.OT = '1010176'


Q:

Prove $x \geq \sin x$ on $[0,\pi/4]$

As the title says.. it says to use the mean value theorem but I don't see how that's applicable.
Thank you

A:

I just propose a geometric proof:


Q:

R prediction of filler values (needed to generate smoothed curve from model)

I am trying to use predict() filler values (the rows contain x values and y values as NaN) to fill in the prediction curve in a plot that includes the data.  The idea is to get a smoother prediction curve than just by using the data x values.  However, predict() is returning funky values that do seem to not be a y calculation based on the x value.  The questions are:

What is wrong with the prediction calculation.
How do I set the dataframe or change the code to get the smoothed line.

This is what the output looks like (note the dips for the erroneously predicted y values):

Here is the code that yields the gruesome result:
library(ggplot2)
library(nlme)

# generate test data frame
x = c(0, 5, 100, 1000, 50, 200, 300, 500)
y = c(0, 3, 5, 6, NaN, NaN, NaN, NaN)
df=data.frame(x,y)

# a log model to fit the data
lF <- formula(y ~ Ymax-(Ymax-Y0)*exp(-k*x))

# nonlinear regression
model <- nls(lF, data=df,
             start=list(Ymax=3.0, k=0.01, Y0=0.3),
             na.action = na.omit)

# print out the model resutls
summary(model)

# Derive predicted lines
df$pred <- predict(model)

# plot the data and three models
ggplot(df, aes(x=x, y=y))+
     geom_point() +
     geom_line(aes(y=pred))

A:

If you specificy the argument newdata=df in the prediction command, you get:
df$pred <- predict(model, newdata=df)

ggplot(df, aes(x=x, y=y))+
     geom_point(color="red", size=3) +
     geom_line(aes(y=pred), size=1) +
     theme_bw()

If you want to draw a smooth line from the model, you need to define a suitable sequence of x values:
df2 <- data.frame(x=c(seq(0,1,0.001),1:1000))
df2$pred <- predict(model, newdata=df2)

ggplot(df, aes(x=x, y=y))+
     geom_point(color="red", size=3) +
     geom_line(data=df2, aes(x=x, y=pred), color="blue", size=1) +
     theme_bw()


Q:

Adding multiple numbers in if and case statements

I'm developing my first game app for the iphone, and I'm still a bit nooby in objective-c.
The game is coming along fine but i'm stuck on a little problem...
I want to make it so that for every 20 kills, you get +1 life, I know how to do that but with poorly written code such as this...:
    switch (kills) {

        case 20:

            lives++;

            livescount.text = [NSString stringWithFormat:@"%i", lives];

            break;

        case 40:

            lives++;

            livescount.text = [NSString stringWithFormat:@"%i", lives];

            break;

        case 60:

            lives++;

            livescount.text = [NSString stringWithFormat:@"%i", lives];

            break;
        case 80:

            lives++;

            livescount.text = [NSString stringWithFormat:@"%i", lives];

            break;
        case 100:

            lives++;

            livescount.text = [NSString stringWithFormat:@"%i", lives];

            break;

        case 120:

            lives++;

            livescount.text = [NSString stringWithFormat:@"%i", lives];

            break;
        case 140:

            lives++;

            livescount.text = [NSString stringWithFormat:@"%i", lives];

            break;
        case 160:

            lives++;

            livescount.text = [NSString stringWithFormat:@"%i", lives];

            break;

        case 180:

            lives++;

            livescount.text = [NSString stringWithFormat:@"%i", lives];

            break;

        case 200:

            lives++;

            livescount.text = [NSString stringWithFormat:@"%i", lives];

and so on.... I don't want to keep writing this till infinity lol

I know for a fact that this is an improper way to write the code. Can anyone give me a proper code for every 20 kills = +1 life. I would probably spot on and understand how the code works too.

A:

Use the modulo operator (%) that return the remaider of division by 20 ; also check that the number of kills is different from zero.
if (kills != 0 && kills % 20 == 0) {
    lives++;
    livescount.text = [NSString stringWithFormat:@"%i", lives];
}


Q:

Is there a word for "re-parent"?

The definition for "parent" includes:

an ancestor, precursor, or progenitor.
a source, origin, or cause.

Is there a term that describes changing the parent of a child object to a different source, origin or cause? My first thought was "re-parent" or "reparent" but neither seem to be well accepted terms.

A:

Reparent is the standard term in computer programming and related contexts.  For instance, StackOverflow has a tag.

A:

As @Nate points out, reparent has a "domain-specific" sense sufficiently well established as to merit an SO tag. And OED has these entries first recorded in the 70s...

reparenting Psychol. (orig. and chiefly U.S.).
    noun: Any of various therapeutic techniques intended to treat emotional and psychological problems relating to the parenting a person experienced as a child.
reparent Psychol. (orig. and chiefly U.S.).
    verb trans.: To treat by the process of reparenting. Cf. reparenting n.

...which is obviously a totally different domain-specific sense (there may be others, I don't know).
The point being that the most morphologically natural way to convey verb again is re[-]verb. Therefore reparent has to be the front-runner for a "generic" verb in OP's context. The fact that it has domain-specific senses (unknown to most native speakers) doesn't affect its suitability for more general use.
The reason it's not really an "accepted" term is just that it doesn't reference a concept that's easily understood and useful in more general contexts. I can't find any written instances of reparent more than half a century old that aren't presaging the physchology usage. It just doesn't mean enough.


Q:

Why aren't my threads timing out when they fail?

So I asked a question a little while ago: Over here that asked the question "How can I make my threads get killed if they take too long"
I have implemented the solution mentioned there but under certain rare circumstances where a thread times out, the program can still fail / lock up (see: Keep the main() method open, and prevent further cron runs of the program).
Here's the source I'm using:
 //Iterate through the array to submit them into individual running threads.
    ExecutorService threadPool = Executors.newFixedThreadPool(12);
    List<Future<?>> taskList = new ArrayList<Future<?>>();
    for (int i = 0; i < objectArray.length; i++) {
        Future<?> task = threadPool.submit(new ThreadHandler(objectArray[i], i));
        taskList.add(task);
        Thread.sleep(500);
    }

    //Event handler to kill any threads that are running for more than 30 seconds (most threads should only need .25 - 1 second to complete.
    for(Future future : taskList){
        try{
            future.get(30, TimeUnit.SECONDS);
        }catch(CancellationException cx){ System.err.println("Cancellation Exception: "); cx.printStackTrace();
        }catch(ExecutionException ex){ System.err.println("Execution Exception: ");ex.printStackTrace();
        }catch(InterruptedException ix){ System.err.println("Interrupted Exception: ");ix.printStackTrace();
        }catch(TimeoutException ex) {future.cancel(true);}
    }
    threadPool.shutdown();
    threadPool.awaitTermination(60, TimeUnit.SECONDS);

So my question is:  with this code implemented, why is the executor service not cutting things off at 30 seconds.

A:

Because I suspect your worker threads are still running.  You are calling future.cancel(true); but all that does is set the interrupt flag on the thread -- it does not actively interrupt your running code.  Another way to "interrupt" code is to set some volatile boolean shutdown flag to be true and to test for that in your code.  See here for more details about interrupting threads.
You need to make sure that your ThreadHandler code handles interrupts correctly.  It needs to, for example, check Thread.currentThread().isInterrupted() in loops or in other code blocks.  You also need to make sure that you are handling InterruptedException correctly and not just swallowing the interrupt.
See my answer here for more information about thread interrupts.


Q:

How to use C++ classes with ctypes?

I'm just getting started with ctypes and would like to use a C++ class that I have exported in a dll file from within python using ctypes.
So lets say my C++ code looks something like this:
class MyClass {
  public:
    int test();
...

I would know create a .dll file that contains this class and then load the .dll file in python using ctypes.
Now how would I create an Object of type MyClass and call its test function? Is that even possible with ctypes? Alternatively I would consider using SWIG or Boost.Python but ctypes seems like the easiest option for small projects.

A:

Besides Boost.Python(which is probably a more friendly solution for larger projects that require one-to-one mapping of C++ classes to python classes), you could provide on the C++ side a C interface. It's one solution of many so it has its own trade offs, but I will present it for the benefit of those who aren't familiar with the technique. For full disclosure, with this approach one wouldn't be interfacing C++ to python, but C++ to C to Python. Below I included an example that meets your requirements to show you the general idea of the extern "c" facility of C++ compilers.
//YourFile.cpp (compiled into a .dll or .so file)
#include <new> //For std::nothrow
//Either include a header defining your class, or define it here.

extern "C"  //Tells the compile to use C-linkage for the next scope.
{
    //Note: The interface this linkage region needs to use C only.
    void * CreateInstanceOfClass( void )
    {
        // Note: Inside the function body, I can use C++.
        return new(std::nothrow) MyClass;
    }

    //Thanks Chris.
    void DeleteInstanceOfClass (void *ptr)
    {
         delete(std::nothrow) ptr;
    }

    int CallMemberTest(void *ptr)
    {

        // Note: A downside here is the lack of type safety.
        // You could always internally(in the C++ library) save a reference to all
        // pointers created of type MyClass and verify it is an element in that
        //structure.
        //
        // Per comments with Andre, we should avoid throwing exceptions.
        try
        {
            MyClass * ref = reinterpret_cast<MyClass *>(ptr);
            return ref->Test();
        }
        catch(...)
        {
           return -1; //assuming -1 is an error condition.
        }
    }

} //End C linkage scope.

You can compile this code with
gcc -shared -o test.so test.cpp
#creates test.so in your current working directory.

In your python code you could do something like this (interactive prompt from 2.7 shown):
>>> from ctypes import cdll
>>> stdc=cdll.LoadLibrary("libc.so.6") # or similar to load c library
>>> stdcpp=cdll.LoadLibrary("libstdc++.so.6") # or similar to load c++ library
>>> myLib=cdll.LoadLibrary("/path/to/test.so")
>>> spam = myLib.CreateInstanceOfClass()
>>> spam
[outputs the pointer address of the element]
>>> value=CallMemberTest(spam)
[does whatever Test does to the spam reference of the object]

I'm sure Boost.Python does something similar under the hood, but perhaps understanding the lower levels concepts is helpful. I would be more excited about this method if you were attempting to access functionality of a C++ library and a one-to-one mapping was not required.
For more information on C/C++ interaction check out this page from Sun: http://dsc.sun.com/solaris/articles/mixing.html#cpp_from_c

A:

The short story is that there is no standard binary interface for C++ in the way that there is for C.  Different compilers output different binaries for the same C++ dynamic libraries, due to name mangling and different ways to handle the stack between library function calls.
So, unfortunately, there really isn't a portable way to access C++ libraries in general.  But, for one compiler at a time, it's no problem.
This blog post also has a short overview of why this currently won't work.  Maybe after C++0x comes out, we'll have a standard ABI for C++?  Until then, you're probably not going to have any way to access C++ classes through Python's ctypes.

A:

The answer by AudaAero is very good but not complete (at least for me).
On my system (Debian Stretch x64 with GCC and G++ 6.3.0, Python 3.5.3) I have segfaults as soon has I call a member function that access a member value of the class.
I diagnosticated by printing pointer values to stdout that the void* pointer coded on 64 bits in wrappers is being represented on 32 bits in Python. Thus big problems occurs when it is passed back to a member function wrapper.
The solution I found is to change:
spam = myLib.CreateInstanceOfClass()

Into
Class_ctor_wrapper = myLib.CreateInstanceOfClass
Class_ctor_wrapper.restype = c_void_p
spam = c_void_p(Class_ctor_wrapper())

So two things were missing: setting the return type to c_void_p (the default is int) and then creating a c_void_p object (not just an integer).
I wish I could have written a comment but I still lack 27 rep points.


Q:

Commensurated subgroups of a free group

Let $F$ be a non-abelian free group, say finitely generated. Suppose $N$ is a commensurated subgroup of $F$. That is $N \cap N^g$ is of finite index in both $N$ and in $N^g$ for any $g \in F$.
What is known about $N$?
I guess $N$ does not have to be normal as it can be normal in a subgroup of finite index or of finite index in a normal subgroup. Are there other examples?

A:

There are many commensurated subgroups in a free groups which are not of the kind you described above.
We all know that normal subgroups $N\lhd \Gamma$ could be thought of as kernels of surjective maps $\Gamma\to G$. Here is an analogous way of thinking of commensurated subgroups $N<\Gamma$.
Fix a group $\Gamma$.
For every totally disconnected locally compact (tdlc) group $G$, a compact open subgroup $K<G$ and
a homomorphism $\rho:\Gamma\to G$,
$N=\rho^{-1}(K)$ is commensurable in $\Gamma$ (as $K$ is commensurtaed in $G$).
In fact, every commensurated $N<\Gamma$ is obtained this way (a construction of a group $G$ and a map $\rho$ as above is called sometimes the "Schlichting completion" of $\Gamma$ wrt $N$).
If $\rho(\Gamma)$ is dense in $G$ then (a finite index subgroup of) $K$ is normal in (a finite index subgroup of) $G$ iff (a finite index subgroup of) $N$ is normal in (a finite index subgroup of) $\Gamma$. This is easy to see.
Now, to give an example answering the question just fix a tdlc group that you know well enough (say $\text{PGL}_2(\mathbb{Q}_p)$) and a compact open subgroup which is far from being normal (say $\text{PGL}_2(\mathbb{Z}_p)$) and find an injective dense homomorphism $\rho:F_n\to G$ by fixing any generic enough $n$-tuple in $G$ (which could be made very concrete).


Q:

List rotation to the left in Python 3

I'm trying to create a list (b) that is list (a) rotating a's members k times to the left. I came up with this on Python 3:
n = 5
k = 4
a = [1,2,3,4,5]
b = []

for i in a:
    if (i + k) <= (n - 1):
            b.append(a[i+k])
        elif (i+k-n) < (n-1):
                b.append(a[i+k-n])
print(b)

But for some reason, it doesn't work since when I tell print(b) it returns a list that is exactly like list a
What am I missing here?

A:

A simple solution:
k = k % len(a) #we don't care about shifting x*len(a) times since it does not have any effect

b = a[k:] + a[:k]

A:

Thanks to @RemcoGerlich for helping me see my mistake! Here's how I quickly fixed my code:
n = 5
k = 4
a = [1,2,3,4,5]
b = []
i = 0
while (i < n):
    if (i + k) <= (n - 1):
            b.append(a[i+k])
    elif (i+k-n) < (n-1):
            b.append(a[i+k-n])
    i = i+1
print(b)


Q:

How to say the term "招" and "式" in English?

It's used as a classifier, like this:

"亢龙有悔"是"降龙十八掌"中的*一招*.

and

*一招一式*他都记得清清楚楚.

So how to say it in English?

A:

Generally it's called 'move'.
To be precise, 招 is 'move' and 式 is 'stance' or 'form'.
When it comes to a specific move, you can use words like catch (手 as in 擒拿手), hit (打), reach (长拳), kick (踢) etc.

一招一式他都记得清清楚楚。
Every move is imprinted on his mind.


Q:

Best way to remesh a quad 3D mesh?

I have a quad-based 3D mesh. I want to:

remesh it while keeping the shape the same
the end output should be in quads
ideally it should have a similar number of verts / polys as the input
ideally the remeshing would be random, and output mesh would be distinct from the input

Right now I'm remeshing with Meshlab, which outputs tris. I then use the Tris to Quads function from Blender. The problem is that that function is not perfect, and leaves many tris.
So ideally there'd be a quad-based random remesh tool, but if anyone knows of a better tri-to-quad tool that would also be helpful?
Thank you.

A:

I'd recommend using OpenVDB. It's quite battle-tested.
Use meshToVolume to voxelize the mesh. Then use volumeToMesh to produce a high-quality quad mesh.
meshToVolume voxelizes the mesh into a SDF. volumeToMesh seems to use dual contouring / SurfaceNets.


Q:

Format any currency and amount for current culture (not culture of the currency)

I need to format an amount in any given currency so that it looks as expected in the current culture.
For example in UK culture (en-GB) one would expect to see the following:
£1.00
$1.00
€1.00
And in German culture, the same currency amounts should appear as:
1,00 £
1,00 $
1,00 €
I have found a method (below) which formats the currency/amount according to the format of the culture associated with the currency (e.g. £1.00, 1,00 €) but this is not quite right, as someone from the UK would expect to see €1.00 even though Euro is not the currency associated with en-GB.
public static string FormatCurrency(this decimal amount, string currencyCode)
{
    var culture = (from c in CultureInfo.GetCultures(CultureTypes.SpecificCultures)
                   let r = new RegionInfo(c.LCID)
                   where r != null
                   && r.ISOCurrencySymbol.ToUpper() == currencyCode.ToUpper()
                   select c).FirstOrDefault();

    if (culture == null)
        return amount.ToString("0.00");

    return string.Format(culture, "{0:C}", amount);
}

Can anyone provide or describe a method to view an amount in any given currency according to the current culture?

A:

To set the current symbol to the desired one (£, $, € or whatever else) while still using the other attributes of the current culture, you can just clone your current NumberFormatInfo and replace the currency symbol:
var cultureInfo = Thread.CurrentThread.CurrentCulture;
var numberFormatInfo = (NumberFormatInfo)cultureInfo.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "€"; // Replace with "$" or "£" or whatever you need

var price = 12.3m;
var formattedPrice = price.ToString("C", numberFormatInfo); // Output: "€ 12.30" if the CurrentCulture is "en-US", "12,30 €" if the CurrentCulture is "fr-FR".


Q:

How to store ip addresses of visitors in database in php?

I have tried this php method to get ip address but it is providing wrong output.
the regular method
 <?php     echo $_SERVER['REMOTE_ADDR'];   ?>

does not provide the appropriate output. when i use this method , i get output like

IP address : '::1'

is there any problem in my script?
also give the details about storing those ip addresses in database
Thanks in advance

A:

'::1' means it is your localhost IP Address.
::1 == 127.0.0.1
You can try this one also.
$ip=$_SERVER['REMOTE_ADDR'];
echo "IP address= $ip";

If your application hosted on same machine from where you are trying to request it will always return '::1', It means LocalHost. else it will return client IP Address.

A:

The complete one :D :p (unfortunately, this script is in mysql not mysqli/pdo. you can modify this later.
File1.php
<?php
//connect to database
        class usersOnline {

            var $timeout = 300;
            var $count = 0;
            var $error;
            var $i = 0;

            function usersOnline () {
                $this->timestamp = time();
                $this->ip = $this->ipCheck();
                $this->new_user();
                $this->delete_user();
                $this->count_users();
                }

            function ipCheck() {
                if (getenv('HTTP_CLIENT_IP')) {
                    $ip = getenv('HTTP_CLIENT_IP');
                    }
                elseif (getenv('HTTP_X_FORWARDED_FOR')) {
                    $ip = getenv('HTTP_X_FORWARDED_FOR');
                    }
                elseif (getenv('HTTP_X_FORWARDED')) {
                    $ip = getenv('HTTP_X_FORWARDED');
                    }
                elseif (getenv('HTTP_FORWARDED_FOR')) {
                    $ip = getenv('HTTP_FORWARDED_FOR');
                    }
                elseif (getenv('HTTP_FORWARDED')) {
                    $ip = getenv('HTTP_FORWARDED');
                    }
                else {
                    $ip = $_SERVER['REMOTE_ADDR'];
                    }
                return $ip;
                }
            function new_user() {
                $cekIP = "SELECT ip FROM useronline WHERE ip='$this->ip'";
                $resultCekIp=mysql_query($cekIP);
                $countCekIp=mysql_num_rows($resultCekIp);
                if($countCekIp>0){
                    $insert1 = mysql_query ("UPDATE useronline SET timestamp='$this->timestamp', date=NOW(), ip='', distinct_ip='$this->ip'");
                    if (!$insert1) {
                        $this->error[$this->i] = "Unable to record new visitor\r\n";
                        $this->i ++;
                        }
                    }
                else{
                    $insert2 = mysql_query ("INSERT INTO useronline (timestamp, date, ip, distinct_ip) VALUES ('$this->timestamp',NOW(), '$this->ip', '$this->ip')");
                    if (!$insert2) {
                        $this->error[$this->i] = "Unable to record new visitor\r\n";
                        $this->i ++;
                        }
                    }
                }
            function delete_user() {
                $delete = mysql_query ("DELETE FROM useronline WHERE timestamp < ($this->timestamp - $this->timeout)");
                if (!$delete) {
                    $this->error[$this->i] = "Unable to delete visitors";
                    $this->i ++;
                    }
                }
            function count_users() {
                if (count($this->error) == 0) {
                    $count = mysql_num_rows ( mysql_query("SELECT DISTINCT ip FROM useronline"));
                    return $count;
                    }
                }
            }
        ?>

File2.php
<?php
include('file1.php');
$jml_ol = new usersOnline();
if (count($jml_ol->error) == 0) {
    if ($jml_ol->count_users() == 1) {
        echo $jml_ol->count_users() . "
";
        echo "Your IP: " . $jml_ol->ipCheck();
        }
    else{
        echo $jml_ol->count_users() . "
";
        echo "Your IP: " . $jml_ol->ipCheck();
        }
}
?>

in body or in div:

<?php include('File2.php'); ?>


Q:

How to hide Bar Button Items when UITableView is in edit mode? (Swift)

Title essentially says it all.
I have a UITableView and I want the RightBarButtonItem item to disappear while the UITableView is in edit mode. Unfortunately, all of the answers that I have found so far suggest setting the button to nil... which won't work for me because I do not want to get rid of the button and the reference to it, just hide it while the UITableView is in edit mode.
What I'm having trouble figuring out what to do, then, is:

Detect when the UITableView has entered editing mode
Hiding the RightBarButtonItem (not removing it entirely)
Detect when the UITableView has left editing mode (so the button can reappear)

Any help would be appreciated, thank you!

A:

My working solution for anyone who needs it:
override func setEditing(editing: Bool, animated: Bool) {
    if (editing) {
        super.setEditing(true, animated: true)
        self.navigationItem.rightBarButtonItem!.enabled = false
    } else {
        super.setEditing(false, animated: true)
        self.navigationItem.rightBarButtonItem!.enabled = true
    }
}

Make sure to set the super.setEditing before and after editing starts in order to preserve the functionality of the edit button.
In addition, if you don't want the UITableView to remain in edit mode when the user leaves the UITableView and doesn't click "done" first, add the following function:
override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(true)
    if (editing) {
        editing = false
    }
}

A:

You can use an optional datasource method to detect when a row is being edited, tableView(_:canEditRowAtIndexPath:)
And inside that method, you can either hide or disable the bar button item (disabling is probably the friendlier thing to do, in terms of the UI and code).  There is no hidden property on a bar button, so to properly hide it means you potentially do some grody coding to temporarily remove or make it disappear.
Anyways, I suggest something like:
func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
    self.navigationItem.rightBarButtonItem.enabled = false
    return true
}


Q:

Any benefit of uses CHAR over VARCHAR?

CHAR is stored as a fixed length string, VARCHAR is stored as a variable length string. I can use VARCHAR to store a fixed length string, but why people still want to use CHAR to store a fixed length string? Is there any benefit of using CHAR over VARCHAR? If none of benefit, why mySQL database doesn't remove the option of CHAR?

A:

VARCHAR

varchar stores variable-length character string. it can require less storage than fixed-length types because it uses only as much space as it needs.
varchar also uses 1 or 2 extra bytes to record the value's length. for example varchar(10) will use up to 11 bytes of storage space. varchar helps performance because it saves space. however because the rows are variable length, they can grow when you update them, which can cause extra work. if a row grows and no longer fits in its original location, the behavior is storage engine-dependent...

CHAR

char is fixed-length , mysql always allocates enough space for the specified number of characters. When storing a CHAR value, MySQL removes any trailing spaces. Values are padded with spaces as needed for comparisons.
char is useful if you want to store very short strings, or if all the values are nearly
the same length. For example, CHAR is a good choice for MD5 values for user passwords,
which are always the same length.
char is also better than VARCHAR for data that’s changed frequently, because a fixed-length row is not prone to fragmentation.


Q:

How to use reindex to fill in missing timesteps?

I'm trying to test the example given in the docs that fills in missing timesteps
date_index = pd.date_range('1/1/2010', periods=6, freq='D')
df2 = pd.DataFrame({"prices": [100, 101, np.nan, 100, 89, 88]}, index=date_index)
date_index2 = pd.date_range('12/29/2009', periods=10, freq='D')

#show how many rows are in the fragmented dataframe
print(df2.shape)
df2.reindex(date_index2)

#show how many rows after reindexing
print(df2.shape)

But running this code shows that no rows were added. What am i missing here?

A:

reindex does not work inplace by default. You can do
print(df2.shape)

# assign back
df2 = df2.reindex(date_index2)
print(df2.shape)

Output:
(6, 1)
(10, 1)


Q:

Draggable into Sortable as Grid

I'm trying to create using jquery a draggable list into a sortable list.
Everything works, except when using CSS to transform this list into a grid. As soon as everything is displayed as a grid, the draggable into the sortable stops to work.
My HTML is:

A

B

C

D

1

2

3

My page SCRIPT is:
$(function() {
   $("#sortable").sortable();
   $("#sortable2 li").draggable({
      connectToSortable: "#sortable",
      helper: "clone"
   });
});

And the CSS I've added to make both UL display as grid is:
#sortable {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 450px;
}
#sortable li {
  margin: 3px 3px 3px 0;
  padding: 1px;
  float: left;
  width: 100px;
  height: 90px;
  font-size: 4em;
  text-align: center;
}
#sortable2 {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 450px;
}
#sortable2 li {
  margin: 3px 3px 3px 0;
  padding: 1px;
  float: left;
  width: 100px;
  height: 90px;
  font-size: 4em;
  text-align: center;
}

Any ideas?
I'm using jquery-ui.css, jquery-ui.js and jquery.min.js.
Thanks

A:

The reason this is occurring is because the children li elements are floated.
When an element is floated, it is essentially removed from the normal document flow, and in this case results in the parent element collapsing upon itself with a height of 0:

As a result, you can't drop elements into the #sortable element because it doesn't have a height.
The most common work-around is to use a clearfix to prevent the parent element from collapsing.
Either add overflow: auto to the container element (example):
ul {
  overflow: auto;
}

or use a pseudo-element (example):
ul:after {
  content: '';
  clear: both;
  display: table;
}

Alternatively, you could also just remove float: left from the li elements and set their display to inline-block instead. Additionally, vertical-align: top should be added to resolve a minor alignment issue when dragging the elements (example):
ul li {
  display: inline-block;
  vertical-align: top;
}


Q:

JQuery sortable with a handle - not possible to select text

When I use JQuery UI Sortable with a handlers (or without) there's no possibility to select a text from the rest of the element. I have tried "cancel" param with no result.
$('ul').sortable({
  distance: 15,
  items: '> li',
  handle: '> span'
}).disableSelection();

JSBin:
http://jsbin.com/ikazuh/3/edit

A:

Simply remove .disableSelection() and it's fixed :)
You can select the text but not the handler.


Q:

Are holomorphic an anti-holomorphic vectors or forms in any way fundamentally different?

The question is stated in the title. Could one introduce all the complex geometry concepts just by using the "anti-" objects instead? Or is it just a $Z_2$ symmetry thing like it sometimes is with complex problems?

A:

The identity map is holomorphic; it is not antiholomorphic.
If you pull a (p,q)-form by a holomorphic map, you get another (p,q)-form; but pulling it by an antiholomorphic map gives you a (q,p) form, an element of a different space. Etc. It's like comparing positive numbers to negative: as long as you stick to addition, there is a perfect symmetry, but once you start considering multiplication, positive numbers win.


Q:

Building a multi-panel display with React and Bootstrap

The exercise is part of a React course in which I'm currently enrolled.
Description:

The way it shall look on desktop-screen:

How it shall look on mobile:

Here's my solution:
HTML

JSX
// Manager bundles the single components together.
var React = require('react');
var ReactDOM = require('react-dom');
var PanelWithoutHeading = require('./components/PanelWithoutHeading.jsx');
var PanelCentered = require('./components/PanelCentered.jsx');
var PanelColoredHeading = require('./components/PanelColoredHeading.jsx');
var PanelLarge = require('./components/PanelLarge.jsx');

var largePanelVals = [
  {
    headline: 15080,
    text: 'Shot Views'
  },
  {
    headline: 12000,
    text: 'Likes'
  },
  {
    headline: 5100,
    text: 'Comments'
  }
];

var PanelManager = React.createClass({
    render: function() {
        return (

                <PanelWithoutHeading headline="20" text="New followers added this month" />
                <PanelWithoutHeading headline="$ 1250" text="Average Monthly Income" />
                <PanelWithoutHeading headline="$ 13865" text="Yearly Income Goal" />
                <PanelCentered headline="18 deg" text="Paris" backgroundColor="orange" />

                <PanelLarge vals={ largePanelVals } backgroundColor="violet" />
                <PanelColoredHeading headingColor="blue" description="New visitors" message="1.5k" />
                <PanelColoredHeading headingColor="violet" description="Bounce Rate" message="50%" />

                <PanelLarge vals={ largePanelVals } backgroundColor="violet" />
                <PanelColoredHeading headingColor="red" description="Searches" message="28%" />
                <PanelColoredHeading headingColor="green" description="Traffic" message="140.5 kb" />

        );
    }
});

// Render the bundle into HTML.
ReactDOM.render(<PanelManager />, document.getElementById('display'));

// -- THE COMPONENTS ----------------------------

// 1. Component
var React = require('react');

var PanelCentered = React.createClass({
  render: function() {
     var divStyle = {
      'marginTop': '10px'
    } ;

    var panelStyles = {
      'background': this.props.backgroundColor,
      'textAlign': 'center',
      'color': 'white',
      'minHeight': '100px'
    };

    var h3Styles = {
      fontSize: '36px'
    };

    return (

{ this.props.headline }

{ this.props.text }

    );
  }
});

module.exports = PanelCentered;

// 2. Component
var React = require('react');

var PanelColoredHeading = React.createClass({
  render: function() {
    var divStyle = {
      'marginTop': '10px',
      'minHeight': '100px'
    } ;

    var panelHeadingStyle = {
      'color': 'white',
      'background': this.props.headingColor
    };

    var messageStyle = {
      'fontSize': '1.2em',
      'fontWeight': 800
    };

    return (

{ this.props.description }

{ this.props.message }

    );
  }
});

module.exports = PanelColoredHeading;

// 3. Component
var React = require('react');

var PanelWithoutHeading = React.createClass({
  render: function() {
    var divStyle = {
      'marginTop': '10px'
    } ;

    var panelStyle = {
      'height': '130px',
      'minHeight': '100px'
    }
    return (

{ this.props.headline }

{ this.props.text }

    );
  }
});

module.exports = PanelWithoutHeading;

// 4. Component
var React = require('react');

var PanelLargePart = React.createClass({
  render: function() {
    var panelStyle = {
      'border': 0,
      'minHeight': '130px'
    };

    var bigFont = {
      'fontWeight': 800,
      'fontSize': '1.3em',
      'paddingTop': '15px'
    };

    var divStyle = {
      'paddingLeft': this.props.paddingLeft,
      'paddingRight': this.props.paddingRight
    }

    return (

{ this.props.headline }

{ this.props.text }

    );
  }
});
var PanelLarge = React.createClass({
  render: function() {
    var divStyle = {
      'marginTop': '10px'
    } ;

    var topRow = {
      'height': '120px',
      'background': this.props.backgroundColor,
      'marginLeft': '0px',
      'marginRight': '0px',
      'minHeight': '130px'
    }

    var lastElement = this.props.vals.length - 1;

    var panels = this.props.vals.map(function(val, i) {
      var leftPadding;
      var rightPadding;
      // First panel (i === 0) gets NO left-padding
      !i ? leftPadding = '15px' : leftPadding = '0';

      i === lastElement ? rightPadding = '15px' : rightPadding = '0';

      return <PanelLargePart paddingLeft={ leftPadding }
                             paddingRight={ rightPadding }
                             headline={ val.headline }
                             text={ val.text }
                             key={ i }/>
    });

    return (

          { panels }

    )
  }
});

module.exports = PanelLarge;

Live demo with compiled JSX-code here.
While coding I've realized that I'm still very much a React beginner. Any hints and tips are welcomed. The same goes for the Bootstrap usage.

A:

Move variables out of render
All the variables you are storing are sitting in the render method of the respective component. This means that the variables are constantly created and destroyed.
It would be better to either:

Set them as properties of the object you are passing into React.createClass()
Write the values inline with the returned elements.

Modify special loop cases separately
In this loop:

var lastElement = this.props.vals.length - 1;

var panels = this.props.vals.map(function(val, i) {
  var leftPadding;
  var rightPadding;
  // First panel (i === 0) gets NO left-padding
  !i ? leftPadding = '15px' : leftPadding = '0';

  i === lastElement ? rightPadding = '15px' : rightPadding = '0';

  return <PanelLargePart paddingLeft={ leftPadding }
                         paddingRight={ rightPadding }
                         headline={ val.headline }
                         text={ val.text }
                         key={ i }/>
});

The special cases are the first and last element: you've written two conditionals and are storing extra data just so you can handle these two separately from the rest.
Rather than that, it would be a lot simpler and a lot cleaner in the loop if you instead modified the elements after the loop:
var panels = this.props.vals.map(function(val, i) {
    return <PanelLargePart paddingLeft={ leftPadding }
                         paddingRight={ rightPadding }
                         headline={ val.headline }
                         text={ val.text }
                         key={ i }/>
});
panels[0].props.paddingLeft = '0';
panels[panels.length - 1].paddingRight = '15px';

Stateless Functional Components
None of your components hold a state. Therefore, it is better practice to write them in the form of a stateless functional component:
function MyComponent(props) {
    return <my-tags/>
}

ES6
Small, side recommendation: learn ES6 and use it with React. React (and libraries like Flux and Redux) work a lot better, cleaner, and easier with ES6, e.g., creating classes is more natural in ES6 since you use the actual class system.
Also, things are just starting to move away from ES5 anyway, so it would be good to get comfortable with ES6.


Q:

Can I test for visual regressions in my responsive design?

My Ruby on Rails site has a responsive design. Can I write tests for visual regressions? For example, my site fits in an iPhone 5's viewport without horizontal scrolling. If offset-x: hidden isn't set, and I unintentionally extend the width of an image past the viewport, my site will have horizontal scrolling (pictured below). This is undesirable. Does a visual regression test method such as assert_horizontal_scroll(0) or assert_page_width == "480px", :viewport_width => "480px" exist?
+---------+      +---------+
| PAGE    |      | PAGE    |
| +-----+ |      | +---------+
| | IMG | |      | |   IMG   |
| +-----+ |      | +---------+
|         |      |         |
+---------+      +---------+

EDIT: Let me try to clarify: I currently preview changes to my styles in a fullscreen browser window. If I make changes that could affect the way my site appears on mobile screens, I'll resize that browser window to match the dimensions of a mobile device, then see if everything looks ok. I want to automate the process of "seeing if everything looks ok" on small screens via a unit test so that I don't have to resize my browser to each device width.
EDIT: Another example: I want an element to be 50% transparent, and I set opacity: .5. I want to test the element's opacity, so that if later CSS styles unintentionally set that element's opacity to 1, I'll know because my test will fail. Or if a particular browser (early IE) doesn't support opacity, the test will also fail.

A:

PhantomCSS is "a CasperJS
module for automating visual regression testing with PhantomJS and
Resemble.js. For testing Web apps, live style guides and responsive
layouts."
CasperJS "is a navigation scripting and testing utility for PhantomJS, written in JavaScript. It allows us to test websites a lot like PHPUnit or JUnit allow us to test our code."
Wraith is a tool for "testing CSS changes, both deliberate and unintentional." It's used "to compare screenshots of pages, at the pull request level and when merged into master."


Q:

lockfile purpose in init.d daemon scripts (linux)

When looking at various daemon scripts in /etc/init.d/, I can't seem to understand the purpose of the 'lockfile' variable. It seems like the 'lockfile' variable is not being checked before starting the daemon.
For example, some code from /etc/init.d/ntpd:
prog=ntpd
lockfile=/var/lock/subsys/$prog

start() {
        [ "$EUID" != "0" ] && exit 4
        [ "$NETWORKING" = "no" ] && exit 1
        [ -x /usr/sbin/ntpd ] || exit 5
        [ -f /etc/sysconfig/ntpd ] || exit 6
        . /etc/sysconfig/ntpd

        # Start daemons.
        echo -n $"Starting $prog: "
        daemon $prog $OPTIONS
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && touch $lockfile
        return $RETVAL
}

What is the 'lockfile' variable doing?
Also, when writing my own daemon in C++ (such as following the example at the bottom of http://www.itp.uzh.ch/~dpotter/howto/daemonize), do I put the compiled binary directly in /etc/init.d/ or do I put a script there that calls the binary. (i.e. replacing the 'daemon $prog' in the code above with a call to my binary?)

A:

What is the 'lockfile' variable doing?

It could be nothing or it could be eg. injected into $OPTIONS by this line
   . /etc/sysconfig/ntpd

The daemon takes the option -p pidfile where $lockfile could go. The daemon writes its $PID in this file.

do I put the compiled binary directly in /etc/init.d/ or do I put a script there that calls the binary

The latter. There should be no binaries in /etc, and its customary to edit /etc/init.d scripts for configuration changes. Binaries should go to /(s)bin or /usr/(s)bin.


Q:

Looking for temporal upsampling / motion interpolation software

I'm looking for something (prereably FOSS software) which can take an animation with N images as input, and which will output an animation with M frames, where M is in the range 2N to 5N or so.
I believe the general technique is called "temporal upsampling" or possibly "inbetweening" (or "'tweening" for short).  Note that it does need to make some effort to do motion tracking of things in the scene ("optical flow"); just fading ("dissolve") between keyframes isn't going to cut it.  Googling "temporal upsampling" turns up any number of papers on the subject, but I've yet to discover any code/software (a gstreamer plugin would be perfect) I can just use to try the technique out.
Any suggestions ?
Additional information: "Motion interpolation" seems to be the more widely used name in the TV world for what I'm looking for.  See this and the video here too.  Interestingly, some cinephiles seem to hate what these technologies do to 24FPS film: e.g a comment "makes Gone With The Wind look like a soap opera shot on video".

A:

The MVTools plugin for AVISynth performs frame interpolation. AviSynth (sourceforge) is a script based video editing tool. You define operations to perform in a script text file.
The script i had to playback Charlie Wilson's War at 120fps:
cyia.avs:
source = DirectShowSource("Cyia Batten - Charlie Wilson's War.avi")

# assume progressive NTSC Film 23.976 source

# Fast Search
#============
# we use explicit idx for more fast processing
#backward_vec = source.MVAnalyse(blksize=16, isb = true, chroma=false, pel=1, searchparam=1, idx=1)
#forward_vec = source.MVAnalyse(blksize=16, isb = false, chroma=false, pel=1, searchparam=1, idx=1)

# Slow Search
# ===========
# Use block overlap, halfpixel accuracy and Exhaustive search
backward_vec = source.MVAnalyse(overlap=4, isb = true, pel=2, search=3, idx=1)
forward_vec = source.MVAnalyse(overlap=4, isb = false, pel=2, search=3, idx=1)

#double framerate
#source.MVFlowFps(backward_vec, forward_vec, num=2*FramerateNumerator(source), den=FramerateDenominator(source), idx=1)

#triple framerate
#source.MVFlowFps(backward_vec, forward_vec, num=3*FramerateNumerator(source), den=FramerateDenominator(source), mask=0, idx=1)

#120fps
source.MVFlowFps(backward_vec, forward_vec, num=120, den=1, mask=0, idx=1)

Yes, it does destroy the movie quality when converted to anything higher than 24fps.


Q:

Rolling different sided die chosen from a bag at random

Let's say I have a bag with 6 different dice in it, a D4, D6, D8, D10, D12, and D20. I randomly draw 3 dice from the bag without replacement and roll each of them.
I want to know a formula for calculating the probability of at least 2 of them rolling a value of 1.
I think I'm getting hung up on the fact that the probability of each die rolling a 1 is different, along with the fact that I'm doing this without replacement so the chance is changing with each draw. It feels like a hypergeometric distribution problem, but since there's not clear "successes" for the draws (any die is OK to draw), I'm not sure how to take that into account.
I'm happy with first answering the question of "exactly 3 of them rolling a value of 1" and then expanding it to the "at least 2" version.
I understand that, at first, the combined chance for each die of drawing it and rolling a 1 is, respectively...
$\left(\frac{1}{6}\right)\left(\frac{1}{4}\right)$,
$\left(\frac{1}{6}\right)\left(\frac{1}{6}\right)$,
$\left(\frac{1}{6}\right)\left(\frac{1}{8}\right)$,
$\left(\frac{1}{6}\right)\left(\frac{1}{10}\right)$,
$\left(\frac{1}{6}\right)\left(\frac{1}{12}\right)$, and
$\left(\frac{1}{6}\right)\left(\frac{1}{20}\right)$
or
$0.041\bar6$,
$0.02\bar7$,
$0.0208\bar3$,
$0.01\bar6$,
$0.013\bar8$, and
$0.008\bar3$
But then for the second draw it changes to a $\left(\frac{1}{5}\right)$ chance of drawing each die that is left. And while the chance of rolling a 1 on each individual die doesn't change, WHICH die was drawn first and is no longer available to be drawn does affect the chances that are left.
Brute forcing this with a probability tree gets large very quickly. If the problem was just drawing from a bag or just rolling dice, I feel like they'd be relatively simple, but I'm having trouble putting those two types of problems together.

A:

For dice of type D(A),D(B),D(C) the probability of at least 2 showing 1's is
$
\begin{align}
(1/A)*(1/B)*((C-1)/C) + (1/A)*((B-1)/B)*(1/C) + ((A-1)/A)*(1/B)*(1/C) + (1/A)*(1/B)*(1/C) = (A+B+C-2)/(A*B*C)
\end{align}$
Moving on, We are left to choose A,B and C. Which we have to do manually and there is no other way around. All the possible 20 combinations have equal probability of being chosen. We can calculate answer for each of those, add them up and divide by 20.
I understand your concern of manually doing calculations so you could always do a little coding to help you out with the process. I have taken the liberty to code it for you.
Edit: Yes, the (-2) accounts for double counting. It would be more clear if we used the Inclusion Exclusion Principle to calculate the probability. Try it.


Q:

Shopify Api working with PHP

I am working with Shopify Webhook for order fulfillment(in PHP) now i want the payment details of "Information from the gateway" which are available in the shopify admin but not showing in Webhook details so anyone can please give any solution for this. following is the screenshot of details which i want to get in order.
These following are details which I want when any new order is confirmed:
1) Authorization key
2) Name on Credit card
3) Exp month
4) Exp year
details which i want to get in order

A:

For this information you needs to use following shopify method
GET /admin/orders/#{id}/transactions.json

And following response you get:
HTTP/1.1 200 OK
{
  "transactions": [
    {
      "id": 179259969,
      "order_id": 450789469,
      "amount": "209.00",
      "kind": "refund",
      "gateway": "bogus",
      "status": "success",
      "message": null,
      "created_at": "2005-08-05T12:59:12-04:00",
      "test": false,
      "authorization": "authorization-key",
      "currency": "USD",
      "location_id": null,
      "user_id": null,
      "parent_id": null,
      "device_id": null,
      "receipt": {},
      "error_code": null,
      "source_name": "web"
    },
    {
      "id": 389404469,
      "order_id": 450789469,
      "amount": "409.94",
      "kind": "authorization",
      "gateway": "bogus",
      "status": "success",
      "message": null,
      "created_at": "2005-08-01T11:57:11-04:00",
      "test": false,
      "authorization": "authorization-key",
      "currency": "USD",
      "location_id": null,
      "user_id": null,
      "parent_id": null,
      "device_id": null,
      "receipt": {
        "testcase": true,
        "authorization": "123456"
      },
      "error_code": null,
      "source_name": "web",
      "payment_details": {
        "credit_card_bin": null,
        "avs_result_code": null,
        "cvv_result_code": null,
        "credit_card_number": "•••• •••• •••• 4242",
        "credit_card_company": "Visa"
      }
    },
    {
      "id": 801038806,
      "order_id": 450789469,
      "amount": "250.94",
      "kind": "capture",
      "gateway": "bogus",
      "status": "success",
      "message": null,
      "created_at": "2005-08-05T10:22:51-04:00",
      "test": false,
      "authorization": "authorization-key",
      "currency": "USD",
      "location_id": null,
      "user_id": null,
      "parent_id": null,
      "device_id": null,
      "receipt": {},
      "error_code": null,
      "source_name": "web"
    }
  ]
}

And you want to more details than please refer the below link:
https://help.shopify.com/api/reference/transaction


Q:

Is any body using sql service broker to update winforms(WPF) GUI?

I have a scenario to update Winforms application GUI when ever there is a data change in database table.Is any body  using SQL Service broker to do same?
For example:
I have a customer and order tables in SQl Server 2005 database and I have winform(WPF) application which resides on Call Center executives(say CCE-A,CCE-B,CCE-C,CCE-D) desks to show pending customer orders.
All those Call Center Executives will process pending orders simultaniously.As a developer my challenge is update Call Cener Executives GUIs when ever there is a change in Customer and Order tables.
Thanks in advance for your valuable time.

A:

It really depends on the number of GUI's that you would have to be updating.  Essentially, the SqlDependency works of ServiceBroker to fire updates to the application when data changes in the database, so your could use it, or roll your own implementation, but the caveat is that it isn't good for large scale/multi-dependency refreshes because of the overhead of each Dependency.  Pro SQL Server 2008 Service Broker by Klaus Aschenbrenner is a great reference for how you can use service broker with managed code.
You can create a single test SqlDependency on the data you want to watch, and use SQLTrace to capture the statements executed by the Database Engine to create the Service and Queues in SQL Server.  Then you can take those statements and use them as the basis for a customize Service to meet your needs, having the clients setup to use the same Service instead of each starting their own through SqlDependency.  This along with an ObservableCollection in WPF should get your to where you need to be.