text:
Q: How do I get an objects height from awakeFromNib to my mainViewController.m? I programmatically created a UILable in a xib file - class of awakeFromNib, and I'm trying to get the labels height in the mainViewController.m. I tried using an NSBundle to load the xib file, but it didn't work. Is there another way I should load it? I need to call awakFromNib in viewDidLoad.
Here is my code:
- (void)awakeFromNib
{
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 200)];
    [self.label setText:@"This is a label"];
    [self.myView addSubview:self.label];

    NSLog(@"%f", self.label.frame.size.height);  // Results: 200.0000
}

mainViewController.m
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [[[NSBundle mainBundle] loadNibNamed:@"customCell" owner:self options:nil]objectAtIndex:0];
    customCell *cellVC = [[cutsomCell alloc] init];

    NSLog(@"%f", cellVC.label.frame.size.height); // Results: 0.0000
}

I need the NSLog to display 200, not 0.

A: I have had the worst luck loading nibs and issues searching for an easy way to do so. This is what worked for me in the past.
Add this to customCell.m
- (id)initWithNib
{
    // where MyCustomView is the name of your nib
    UINib *nib = [UINib nibWithNibName:@"customCell" bundle:[NSBundle mainBundle]];
    self = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
    return self;
}

Add this to customCell.h
- (id)initWithNib;

Now in your view controller do this
customCell *cellVC = [[cutsomCell alloc] initWithNib];

I found a good link here that uses that example here


text:
Q: Second member of Azure AD group can not create schema in Azure SQL database We have a curious issue with our Azure SQL database with AAD authentication.
We have created a role (dbt_user) with all permissions, and excluded some schemas:
CREATE ROLE dbt_user AUTHORIZATION dbo;

GRANT CREATE SCHEMA, ALTER, DELETE, EXECUTE, INSERT, REFERENCES, SELECT, UPDATE TO dbt_user;
DENY ALTER, DELETE, EXECUTE, INSERT, UPDATE ON SCHEMA :: dbo TO dbt_user;
DENY ALTER, DELETE, EXECUTE, INSERT, UPDATE ON SCHEMA :: schema1 TO dbt_user;
DENY ALTER, DELETE, EXECUTE, INSERT, UPDATE ON SCHEMA :: schema2 TO dbt_user;

Then, we add an AAD group (myAADGroup) as user, and add this to the role above:
CREATE USER [myAADGroup] FROM EXTERNAL PROVIDER;
ALTER ROLE dbt_user ADD MEMBER [myAADGroup];

There are 2 members of the AAD group: user1@domain.com and user2@domain.com.
The first user can log in, and execute the following command:
CREATE SCHEMA [test_schema_user1];

However, when user2 executes the following command, we get an error:
CREATE SCHEMA [test_schema_user2];

Msg 2760, Level 16, State 1, Line 1
The specified schema name "user2@domain.com" either does not exist or you do not have permission to use it.
Msg 2759, Level 16, State 0, Line 1
CREATE SCHEMA failed due to previous errors.

Only the first user can successfully create a schema.
I only found 2 slightly related issues online, but they talk about CREATE TABLE, which can be circumvented by explicitly defining dbo as schema prefix for the table:

*

*Microsoft Tech Community

*Azure docs (see the note at the end of step 5)

Some things I executed as user2@domain.com in order to debug:
select SCHEMA_NAME()
-- returns dbo

SELECT name, default_schema_name
FROM sys.database_principals
WHERE name = 'myAADGroup'
-- default_schema_name = dbo

SELECT name, default_schema_name
FROM sys.database_principals
WHERE name = 'dbt_user'
-- default_schema_name = null  --> a role can not have a default_schema?

Thanks!

A: Assuming you have AAD admin rights,
When user1 a member of the myAADGroup group, logs in and tries to create a new SCHEMA.  A new schema will be created in the database. If any other member within this group, say user2 tries to CREATE SCHEMA, an Invalid Object Name error will be shown. Also,  default_schema_name is Null for principals not of type SQL user, Windows user, or Application role.
This security issue is resolved by assigning a default schema for Groups.
USE your_database;
GO

CREATE USER [myAADGroup] FROM EXTERNAL PROVIDER WITH DEFAULT_SCHEMA = dbo;

or
ALTER USER [myAADGroup] WITH DEFAULT_SCHEMA=[dbo]

However, please see the following note from the Remarks section of the CREATE SCHEMA documentation:

Note: The implicit creation of an Azure Active Directory user is not possible on SQL Database. Since creating an Azure AD user from external provider must check the users status in the AAD, creating the user will fail with error 2760: The specified schema name "<user_name@domain>" either does not exist or you do not have permission to use it. And then error 2759: CREATE SCHEMA failed due to previous errors. To work around these errors, create the Azure AD user from external provider first and then rerun the statement creating the object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "It's the people who love you >you're the hardest on<." In this sentence, the middle part "--who love you" is an attributive clause which depicts "the people", but how to explain the latter clause?
Is it an emphatic sentence? Could someone explain the whole sentence in a detailed way? Much thanks.

A: A similar sentence: "It's what we have we don't cherish."  I think it's what's known as "cleft sentence".  The latter part is a dependent clause.  Rewritten as a regular sentence it would be "You're the hardest on the people who love you".  You can take any simple sentence that has an object and rewrite it as a cleft one by starting with "it is/was".
The last part is usually connected by "what", "which", "that" or "who/whom", but such a word can be omitted, like in your case.


text:
Q: SQL Server 2005 Express on Windows 8 I need to install SQL Server 2005 Express on Windows 8 Home Edition x64.
But I get a compatibility error!
I have tried SP1, SP2, SP3 of SQL Server 2005.
Visual Studio 2008 is working fine.
Any suggestions?

A: According to this Microsoft KB article, SQL Server 2005 (in any form, even with all the Service Packs installed) is not supported on Windows 8.

*

*SQL Server 2008 is supported, as long as you install Service Pack 3.

*SQL Server 2008 R2 is supported, as long as you install Service Pack
1.

*SQL Server 2012 is supported with any version.

A: While the others are correct in that its not supported, it doesn't mean you can't install it and that it doesn't work (actually I have SQL Server 2005 on my Win8 machines, and have not seen any issues with it) If you turn off the Compatibility Assistant (which actually will block you from doing what you want) you should be able to install it. See this answer at Superuser which describes how to turn it off.
As an alternate suggestion, maybe you could setup Win7 in a hyper-v virtual machine, assuming you have a license for Win7.  If you don't you may want to consider at least an MSDN OS only subscription, which would cover you in this situation (you could install Win7 or whatever OS you wanted that SQL Server 2005 was supported on as a virtual).


text:
Q: sqlplus error creating table with multiple foreign keys So I am trying to create a table with multiple foreign keys however it keeps saying missing or invalid option. I have successfully created all the other tables that the keys reference without issue. What's strange is that I have found that the table creates if I remove either foreign key, but as soon as I have two foreign keys it gives me the error above. Any help is appreciated! :)
create table Class(
Class#  int(5),
Class_Size int(30),
Module# char(5),
Student#    char(4),
Constraint Class_PK primary key(Class#),
Constraint Class_Module_FK foreign key(Module#) references Modules(Module#) on delete cascade ),
Constraint Class_Student_FK foreign key(Student#) references Students(Student#) on delete cascade );

A: Looks like you have an extra ) at the end of second last line.
This should work
create table Class(
Class#  int(5),
Class_Size int(30),
Module# char(5),
Student#    char(4),
Constraint Class_PK primary key(Class#),
Constraint Class_Module_FK foreign key(Module#) references Modules(Module#) on delete cascade,
Constraint Class_Student_FK foreign key(Student#) references Students(Student#) on delete cascade );


text:
Q: stop socket from waiting to ack I am writing a TCP server in Python.
I want the server to close the connection right after the server send the SYN-ACK (response to SYN from client) without waiting to the client's ACK response (without finishing the handshake).
That's my server:
def get_tcp(port, data_len=1024):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('', port))
    sock.listen(1)

    conn, addr = sock.accept()

    conn.close()

Is there a way to do it?
Thank you very much


text:
Q: Cakephp add function if id exists edit else create I'm using cakephp 2 in my controller add function, I want to edit the data if the id exists, if not exists create.
This is my code in add function:
public function add () {

    if(!$this->request->data){
        throw new NotFoundException();
    }

    $googleCategory = $this->request->data;

    foreach ($googleCategory as $key => $value) {
        if(empty($value['category'])){
            unset($value);
        }

        $conditions = array (
            'AccountShopMeta.shop_id' => $value['shop_id'],
            'AccountShopMeta.name' => $value['category'],
            'AccountShopMeta.value' => $value['url_key']
        );

        if(!$this->AccountShopMeta->hasAny($conditions)){

            $this->AccountShopMeta->create();

            $data['shop_id'] = $value['shop_id'];
            $data['name'] = $value['category'];
            $data['value'] = $value['url_key'];
            $data['tag'] = '';

            if($this->AccountShopMeta->save($data)){
                $account_shop_meta = $this->AccountShopMeta->read();
                $this->set($account_shop_meta);
                $this->set('_serialize', array_keys($account_shop_meta));
            }
        }
    }
}

A: public function add () {

    if(!$this->request->data){
        throw new NotFoundException();
    }

    $googleCategory = $this->request->data;

    foreach ($googleCategory as $key => $value) {
        if(empty($value['category'])){
            unset($value);
        }

        $conditions = array (
            'AccountShopMeta.shop_id' => $value['shop_id'],
            'AccountShopMeta.name' => $value['category'],
            'AccountShopMeta.value' => $value['url_key']
        );

        $accountShopMeta = $this ->AccountShopMeta->find('first', $conditions);

        if(empty($accountShopMeta)) {
            //ADD
            $this->AccountShopMeta->create();
        } else {
           //EDIT
           $this->AccountShopMeta->id = $accountShopMeta['AccountShopMeta']['id'];
        }

        $data['shop_id'] = $value['shop_id'];
        $data['name'] = $value['category'];
        $data['value'] = $value['url_key'];
        $data['tag'] = '';

        if($this->AccountShopMeta->save($data)) {
            //This part shoud be out of loop (foreach)
            $account_shop_meta = $this->AccountShopMeta->read();
            $this->set($account_shop_meta);
            $this->set('_serialize', array_keys($account_shop_meta));
        }
    }

}

More info Saving Your Data


text:
Q: Differentiable function bounded between constant multiples
I honestly have no idea how to do this. Can anyone help?

A: We split the inequality into two:
$f'\ge kf$, and $f'\leq Kf$, which are two inequality ODE's, now imagine we have the ODE:
$f'=Af\Rightarrow f(x)=f(0)e^{Ax}$, apply this to our two odes and we get:
$f(x)\leq f(0)e^{Kx}$ and $f(x)\ge f(0)e^{kx}$, merging these inequalities we get:
$f(0)e^{kx}\leq f(x)\leq f(0)e^{Kx}$ as desired.


text:
Q: TableLayout binding problem at runtime? I've arraylist of objects and i need to bind these list of objects to TableLayout at runtime but i didn't get any data into it, please check my code:
XML code:
<TableLayout android:background="#cfe1edFF" android:id="@+id/tl"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" >

  <TableRow>
    <TextView android:text="Symbol"
    android:layout_height="fill_parent" android:textColor="#104e8b"
        android:layout_width="wrap_content"
        android:layout_weight="1" android:gravity="center" android:background="@drawable/shapefile"/>
    <TextView android:text="A/c Type"
    android:layout_height="fill_parent" android:textColor="#104e8b"
        android:layout_width="wrap_content"
        android:layout_weight="1" android:gravity="center" android:background="@drawable/shapefile">
    </TextView>
    <TextView android:text="Position" android:textColor="#104e8b" android:layout_height="fill_parent"
        android:layout_width="wrap_content"
        android:layout_weight="1" android:gravity="center" android:background="@drawable/shapefile">
    </TextView>
  </TableRow>

    <ScrollView>
    <TableLayout android:id="@+id/score_table"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">
      <TableRow></TableRow>
    </TableLayout>
  </ScrollView>
</TableLayout>

so from above TableLayout "score_table" i'm trying to bind data from ArrayList of objects like:
Code to bind table layout using arryalist objects:
public void TableBinding(ArrayList<Position> posLst)
    {
        TableLayout tLayout=(TableLayout)findViewById(R.id.score_table);
        Position pos;
        for(int i=0;i<posLst.size();i++)
        {
            TableRow tr = new TableRow(this);
            tr.setId(100+i);
            pos=posLst.get(i);
            tr.setLayoutParams(new LayoutParams(
                       LayoutParams.FILL_PARENT,
                       LayoutParams.WRAP_CONTENT));

            TextView b = new TextView(this);
            b.setText(pos.Symbol);
            tr.addView(b);
            //b.setId(200+i);

            TextView b1 = new TextView(this);
            b1.setText(pos.AcType);
            tr.addView(b1);
            //b1.setId(300+i);

            TextView b2 = new TextView(this);
            b2.setText(pos.Position);
            tr.addView(b2);
            //b2.setId(400+i);

            /* Add row to TableLayout. */
            tLayout.addView(tr,new TableLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));

        }

    }

But i didn't get any data into it, i already checked that ArrayList getting data, please help me.
Thanks,
nag.

A: You try this way :
 ArrayList<String> tablesName = new ArrayList<String>();
 TableLayout tl;

public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

   tl = (TableLayout) findViewById(R.id.tableLayout1);

    for (int i = 0; i < posLst.size(); i++) {
    TableRow tr = new TableRow(this);
    CheckBox ch = new CheckBox(this);
    ch.setId(i);

    TextView tv2 = new TextView(this);
    tr.addView(ch);
    createView(tr, tv2, tablesName.get(i));
    tl.addView(tr);
}

    public void createView(TableRow tr, TextView t, String viewdata) {
    t.setText(viewdata);
    t.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    t.setTextColor(Color.DKGRAY);
    t.setPadding(20, 0, 0, 0);
    tr.setPadding(0, 1, 0, 1);
    tr.addView(t);
}

A: try this it worked for me
for (int position=0; position < data.size(); position++)
            {
                TableRow tableRow= new TableRow(this);

                ArrayList<Object> row = data.get(position);

                TextView idText = new TextView(this);
                idText.setText(pos.Symbol);
                tableRow.addView(idText);

                TextView textOne = new TextView(this);
                textOne.setText(pos.AcType);
                tableRow.addView(textOne);

                TextView textTwo = new TextView(this);
                textTwo.setText(pos.AcType);
                tableRow.addView(textTwo);

                dataTable.addView(tableRow);
            }
        }


text:
Q: Recommended second textbook for dynamical systems? I recently finished a course on dynamical systems supplemented by Strogatz's textbook. There are a few parts of the book that we didn't cover (in particular, the material on fractals), but the material that was covered was taught with a bit more detail than presented in Strogatz alone.
What's a good general dynamical systems textbook to "graduate" on to? Preferably, the book should not skimp out on theory and proofs.
I don't expect it to be self-contained in terms of topology material, but it would be nice if it were self-contained otherwise.
I don't mind books that skimp out on theory and proofs, if they otherwise present material in a unique way. Please write a little about why you recommand a particular textbook.
Some relevant M.SE questions:
Textbook Recommendation: Topological Dynamics

A: Two books you might consider are:

*

*Perko's Differential Equations and Dynamical Systems published by Springer.

*Guckenheimer, J and Holmes, P., Nonlinear Oscillations, Dynamical Systems, and Bifurcations of Vector Fields also published by Springer.


text:
Q: Posting to Twitter using SLComposeViewController not working on iOS 8 devices I use the following code to post to Twitter.
SLComposeViewController *tweetSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
[tweetSheet setInitialText:@"Sample post string"];
[self presentViewController:tweetSheet animated:YES completion:nil];

This works fine on iOS 7 devices. For iOS 8 devices, tapping Post button shows this alert.

Moreover console prints this message plugin com.apple.share.Twitter.post invalidated
I went through these links
1) Can't send tweet anymore: plugin com.apple.share.Twitter.post invalidated
2) IOS7 - SLComposeViewController - Error posting to Twitter - cannot send tweet - connection failed
3) https://discussions.apple.com/thread/5275212
I did log out and log in in Settings->Twitter accounts. Also sharing content length is not the problem.
Does any one else experiencing/solved this issue? Appreciate any help. Thanks.
Update: This works on iOS 8.3. Not works on iOS 8.1.2

A: This issue solved when

*

*Date & Time set to automatically

*Language changed to English India (my language)

*Region Format changed to India (my region)

A: Please Check this Link and Read All Comments and check it
http://forums.imore.com/ask-question/287207-when-tweeting-photo-i-get-tweet-cannot-sent-because-connection-twitter-failed.html


text:
Q: gulp-jscs Object.keys called on non-object I'm a novice at gulp, and trying to play with it. I get this error when I try to use gulp-jscs
'default' errored after 98 ms
[16:58:00] TypeError: Object.keys called on non-object
    at Function.keys (native)
    at NodeConfiguration.Configuration._throwNonCamelCaseErrorIfNeeded (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp-jscs/node_modules/jscs/lib/config/configuration.js:440:12)
    at NodeConfiguration.Configuration.load (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp-jscs/node_modules/jscs/lib/config/configuration.js:51:10)
    at StringChecker.configure (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp-jscs/node_modules/jscs/lib/string-checker.js:66:29)
    at Checker.configure (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp-jscs/node_modules/jscs/lib/checker.js:26:39)
    at module.exports (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp-jscs/index.js:31:11)
    at Gulp.<anonymous> (/home/kbadr/Node_Projects/demo/membership/gulpfile.js:22:15)
    at module.exports (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:34:7)
    at Gulp.Orchestrator._runTask (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp/node_modules/orchestrator/index.js:273:3)
    at Gulp.Orchestrator._runStep (/home/kbadr/Node_Projects/demo/membership/node_modules/gulp/node_modules/orchestrator/index.js:214:10

and here's my gulpfile
var gulp = require('gulp');
var jscs = require('gulp-jscs');

gulp.task('default', function () {
    return gulp.src('src/app.js')
        .pipe(jscs());
});

A: This seems to happen if jscs doesn't have read access to your .jscsrc or if it doesn't exist.  This happened to me after copying and pasting it from an old git repro.  To fix this open the file with a text editor and resave it, accepting the prompt to overwrite as well as starting with a '.'  (e.g. .jscsrc)  Run your task again and it will complete.

A: I had the same problem: "Unable to load JSCS config file at /Desktop/node/My_Project_Name/.jscsrc
Unexpected end of input...."
I was able to solve the problem by first checking to see if the file existed in the root of my project. in terminal run this command:
ls -ld .?*
The file was never created for me so I created the .jscsrc file then I added the following code:
{
 "excludeFiles": ["node_modules/**", "bower_components/**"],

"requireCurlyBraces": [
    "if",
    "else",
    "for",
    "while",
    "do",
    "try",
    "catch"
],
"requireOperatorBeforeLineBreak": true,
"requireCamelCaseOrUpperCaseIdentifiers": true,
"maximumLineLength": {
  "value": 100,
  "allowComments": true,
  "allowRegex": true
},
"validateIndentation": 4,
"validateQuoteMarks": "'",

"disallowMultipleLineStrings": true,
"disallowMixedSpacesAndTabs": true,
"disallowTrailingWhitespace": true,
"disallowSpaceAfterPrefixUnaryOperators": true,
"disallowMultipleVarDecl": null,

"requireSpaceAfterKeywords": [
  "if",
  "else",
  "for",
  "while",
  "do",
  "switch",
  "return",
  "try",
  "catch"
],
"requireSpaceBeforeBinaryOperators": [
    "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=",
    "&=", "|=", "^=", "+=",

    "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&",
    "|", "^", "&&", "||", "===", "==", ">=",
    "<=", "<", ">", "!=", "!=="
],
"requireSpaceAfterBinaryOperators": true,
"requireSpacesInConditionalExpression": true,
"requireSpaceBeforeBlockStatements": true,
"requireLineFeedAtFileEnd": true,
"disallowSpacesInsideObjectBrackets": "all",
"disallowSpacesInsideArrayBrackets": "all",
"disallowSpacesInsideParentheses": true,

"validateJSDoc": {
    "checkParamNames": true,
    "requireParamTypes": true
},

"disallowMultipleLineBreaks": true,

"disallowCommaBeforeLineBreak": null,
"disallowDanglingUnderscores": null,
"disallowEmptyBlocks": null,
"disallowMultipleLineStrings": null,
"disallowTrailingComma": null,
"requireCommaBeforeLineBreak": null,
"requireDotNotation": null,
"requireMultipleVarDecl": null,
"requireParenthesesAroundIIFE": true
}

Save this file to the root of your project, then run the gulp task command again it should work.

A: Updated the dependency in bower.json on ngCordova and resolved the issue !!!


text:
Q: OpenWRT https доступ к web интерфейсу Почему-то на веб интерфейс роутера заходит только через http.
Установил пакет luci-ssl (также присутствуют libcyassl libopenssl).
Роутер tp-link tl-wr1043nd v1.
OpenWrt | OpenWrt Backfire 10.03.1 | Загрузка: 0.06 0.04 0.04
При вводе https://192.168.1.1:

Попытка соединения не удалась

Пробовал другой браузер - всё также.

просто reboot надо было сделать после установки luci-ssl...
но всё равно приходится ручками https вводить
пробовал
uci set uhttpd.main.listen_http=192.168.1.1:80
uci set uhttpd.main.listen_https='192.168.1.1:443'
uci set uhttpd.main.redirect_https='1'
uci commit
/etc/init.d/uhttpd restart

не перенаправляет(даже ребут делал, всё равно)
в итоге сделал так
uci delete uhttpd.main.listen_http ; uci commit

теперь http доступ просто не работает, но https всё равно вводить приходится


text:
Q: How do I fix the navigation menu in Firefox and Internet Explorer? On Firefox, the navigation menu appears below the area the navigation menu is supposed to be in. On Internet Explorer the drop-down does not work. It works fine on Chrome and Opera. I used the visibility:hidden and visibility:visible for the sub-menus.
Here is what it looks like on Firefox: http://i.imgur.com/bQbKvhw.png
Here is how it supposed to look: http://i.imgur.com/LKip7Dv.png
The menu goes ALL the way across the screen.
Here is the HTML:

              Home

              My Projects ▿

                  Upside Down Text

                  Random Number

                  Code Editor

                  Website Templates

                  Snake Game

                  Random ▹

                      Matrix

              Contact

              About

Here is the CSS:
#logo {
  margin-right:20px;
}

#header {
  height:65px;
  line-height:65px;
  background-color:#222222;
  margin-top:0px;
  padding-left:20px;
  padding-right:20px;
  border-bottom:3px solid #28B899;
}

#header a {
  color:#999999;
  text-decoration:none;
  display:block;
  text-align:center;
}

#header a:hover {
}

#header ul {
  list-style:none;
  display:inline-table;
  padding:0;
  margin:0;
  position:absolute;
}

#header ul li {
  display:inline;
  position:relative;
  background-color:transparent;
  width:150px;
  float:left;
  padding:0;
  margin:0;
  text-align:left;
  min-width:200px;
}

#header ul li:hover {
  background-color:#111111;
}

#header ul ul {
  visibility:hidden;
  position:absolute;
}

#header ul ul li {
  background-color:#333333;
  min-width:200px;
  text-align:left;
}

#header ul ul li:hover {
  background-color:#222222;
}

#header ul li:hover > ul {
  visibility:visible;
  position:relative;
}

#header ul ul ul {
  visibility:hidden;
  position:absolute;
}

#header ul ul li:hover > ul {
  visibility:visible;
  position:absolute;
  left:100%;
  top:0;
  border-bottom:none;
}

A: The problem is that you have not defined a top value on #header ul.
This should fix it:
#header ul {
  ...
  top: 0;
}

JSFiddle example


text:
Q: TableView Crashes when Inserting I keep getting the following error when trying to insert a row:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'
*** First throw call stack:
(0x31fe82a3 0x39ccc97f 0x31f33b75 0x8d18f 0x33fee5a9 0x33edb0c5 0x33edb077 0x33edb055 0x33eda90b 0x33edae01 0x33df9421 0x31fbd6cd 0x31fbb9c1 0x31fbbd17 0x31f2eebd 0x31f2ed49 0x35af62eb 0x33e44301 0xa49d 0x3a103b20)
libc++abi.dylib: terminate called throwing an exception

Does anyone know what's going on here?
Here is my code:
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(editingStyle == UITableViewCellEditingStyleDelete)
    {
        Caseload *deletedCaseload = [self.caseload objectAtIndex:indexPath.row];
        [self.caseload removeObject:deletedCaseload];

        [self.caseloadTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    else if
        (editingStyle == UITableViewCellEditingStyleInsert)
    {

        Caseload *copiedEntry = [self.caseload objectAtIndex:indexPath.row];
        Caseload *newEntry = [[Caseload alloc]init];
        newEntry.name = copiedEntry.name;
        newEntry.address = copiedEntry.address;
        newEntry.phoneNumber = copiedEntry.phoneNumber;
        newEntry.identNumber = copiedEntry.identNumber;

        [self.caseload addObject:newEntry];
        [self.caseloadTableView insertRowsAtIndexPaths:
                    [NSArray arrayWithObject:indexPath]
                                              withRowAnimation:UITableViewRowAnimationRight];
    }
}

A: This types of error generate whenever you try to get object/value of an array at totalIndex + 1 such like for example if your array has 4 value (Make sure index start with 0) and you try to fetch value such like
[Myarray objectAtIndex:4] at that time this type of error occur.
So best why is use breakPoint and find out your problem by help of my suggestion.

A: The error is "NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'".  That means you're calling "objectAtIndex:" somewhere with an index of 2, and your NSArray only has entries at index 0 and index 1.
You need to figure out where you are setting the bogus index, which I suspect might start in your "numberOfRowsInSection:" method.


text:
Q: Python program to convert Hexadecimal to IEEE-754 Floating Point with Single precision I'm writing a Python program to decode Base64(Raw Data) output from my sensors to find it's latitude and longitude.
After checking the documents (attached below) that came with the sensor to decode the values, I'm still unsure on how to achieve it. I found a partial solution to convert it below but not sure how to achieve the final output.
So for example, if the Hexa value is B4 39 F5 42, my latitude output should be 1.3768.

import binascii
import struct

data = 'F9 7B 9C 45'
fdata = struct.unpack('<f', binascii.unhexlify(data.replace(' ', '')))[0]
print(fdata)

output:
5007.49658203125

A: You are almost there. You should now convert the floating point number to degrees as specified in the docs you attached:
deg = fdata // 100 + (fdata % 100) / 60

The result would be 50.124943033854166 for 'F9 7B 9C 45' and 1.3768783569335938 for 'B4 39 F5 42'.


text:
Q: Query regarding OSM file structure Had a query regarding the OSM file's tags and values. I came across files where there are inconsistencies in tag names and certain node ids/uids do not have tag names and thereby don't allow us to identify what feature it is without opening them in any GIS software. For example, some node ids and uids have tag names as "source bing". Is there a way to identify what they represent without opening them in GIS software? Also, How does OSM recognize these features without proper tag names and values?
Thank you!

A: In the OSM data model, nodes can represent point features, but they can also be used to define the shape of ways (or, rarely, relations). OSM ways do not have location information on their own, but instead reference a list of node IDs. You can read more about this in the OSM wiki's article on nodes. The OSM wiki is also a good source on the meaning of the tags used in the OSM database.
Nodes that do not represent a point feature will usually carry no tags. However, you will sometimes find nodes with tags for internal use by OSM contributors, such as source information.
There are other reasons why a node may have no tags or unexpected tags, such as editing mistakes by an OSM contributor or newly invented tags. But these are comparatively less common.


text:
Q: Get LUIS Intent and Entities without LUISGEN
*

*Currently I'm using LUISGen to help my bot to get Intent and Entities easily in C#.

*But we are building a bot automation, and do not want to use LUISGen, because we can't ask user to use LUISGEN to generate the C# class.

*So, which is the best/latest method for me to call LUIS to get Intent and Entities?
Is it the API method at https://westus.dev.cognitive.microsoft.com/docs/services/5890b47c39e2bb17b84a55ff/operations/5890b47c39e2bb052c5b9c2f ?
But I can't seems to find any documentation for getting Intent and Entities with User Utterances.
Thanks.

A: You can refer to this documentation to get intents using endpoint REST API. Also, depending on what exactly you want to query for, you can make use of the LUIS API.

*

*LUIS get entity

*LUIS get intent
Hope this helps.


text:
Q: Allow update access to only 2 tables in a database schema I would like to have a login which is capable of accessing a specific schema but should be having only update access to 2/3 tables. Is it possible?
The Database runs on SQL Server 2008 R2. Kindly guide me if possible.

A: Here is an example script
CREATE USER [UserName] FROM LOGIN [LoginName]

-- Grant SELECT on the schema
GRANT SELECT ON SCHEMA::SchemaName TO [UserName]
-- Grant UPDATE on the individual tables
GRANT UPDATE ON SchemaName.TableName1 TO [UserName]
GRANT UPDATE ON SchemaName.TableName2 TO [UserName]

And please remember that unless the user is some level of administrator, db_owner for example, any DENYs that you do will override any form of grant.  If you do this:
DENY UPDATE ON SchemaName.TableName3 TO [UserName]

Then nothing you can do will grant them update access until you REVOKE the DENY.
You could add the user to db_datareader to give them the SELECT permissions but that will give them SELECT permissions to all schemas not just one.  It just depends on what you are looking for.  That command is like this:
EXEC sp_addrolemember 'db_datareader','UserName'

A: Besides using the script (which is preferred in most cases), you can do the same in SQL Server Management Studio:

*

*Right-click the table you want to grant/deny permissions to

*Select Properties

3 Open the Permissions tab
4 Click Search to find the user you want to grant permissions to

5 Select the specific permission and check the Grant box

GRANT (Transact-SQL)

A: Pretty much what Edward Dortland said.  If I understand what you're wanting, you probably want to create the user, add them to the datareaders role on that database, and manually give them update on the tables you want them to update.


text:
Q: How to define additional instance variables with Pytest fixtures I'd like to run a series of Python unit tests which all share the same setUp method. However, a subset of the test require a larger, more specific set of variables. One way to implement this is to define an auxiliary function and call it every time in the 'more specific' tests:
import unittest

class TestFixtures(unittest.TestCase):
    def setUp(self):
        self.a = 1

    def additional_setup(self):
        self.b = 1

    def test_check_value(self):         # Ordinary test
        self.assertEqual(self.a, 1)

    def test_add_variables(self):       # More specific test requiring 'self.b' to be defined
        self.additional_setup()
        self.assertEqual(self.a + self.b, 2)

if __name__ == "__main__":
    unittest.main()

It seems to me like this can be done more elegantly using Pytest fixtures, but none of the examples I saw use fixtures in combination with a conventional setUp method. How could I define the additional variables using Pytest fixtures?
What I've tried so far
I actually haven't been able to simply define a variable to be used in later test cases using a fixture. For example,
import pytest
import unittest

class TestFixtures(unittest.TestCase):
    @pytest.fixture
    def additional_setup_fixture():
        b = 1

    def test_use_fixtures(additional_setup_fixture):
        print b

if __name__ == "__main__":
    unittest.main()

yields a NameError: global name 'b' is not defined.. How can I define variables for use in tests (either create local variables or instance variables) with Pytest fixtures?

A: Here is an approximately equivalent test with Pytest fixtures:
import pytest

@pytest.fixture
def generate_variables():
    a = 1
    b = 2
    return a, b

def test_trivial(generate_variables):
    a, b = generate_variables
    assert a+b == 3

if __name__ == "__main__":
    pytest.main([__file__])

As I understand it, when using Pytest it is no longer necessary for the tests to be methods of a class inheriting from unittest.TestCase. Within test_trivial, the local variable generate_variables is the output of the generate_variables function (namely, the tuple (a, b)) and not the function itself, because it is marked with the @pytest.fixture decorator.


text:
Q: Why POST returns error even if everything is executed correctly? On server side there is a following code to receive POST request:
router.post('/signup', function(req, res, next) {
    //console.log(res);
    passport.authenticate('signup', function(err, user, info) {
        console.log(user);
        if (err) {
            console.log(err);
            return next(err);
        }
        if (!user) { return res.json({redirect: 'auth'}); }
        req.logIn(user, function(err) {
            if (err)
            {
                console.log(err);
                return next(err);
            }
            console.log(res);
            return res.json({redirect: 'userPanel'});
        });
    })(req, res, next);
});

On client side the following function executes POST request and handles response:
$("#btn-signup").click(function() {
    var data = $('form#signupform').serialize();
    $.ajax({
        type: "POST",
        dataType: "jsonp",
        url: "/auth/signup", //process to mail
        data: data,
        success: function(msg) {
            console.log("Received data: " + msg);
            if (msg.redirect) {
                window.location.href = msg.redirect;
            }
        },
        error: function(e) {
            console.log("Error: " + e.responseText);
        }
    });
});

When making a post request I get the following console output:
Error: {"redirect":"auth"}

Therefore I assume the server returns everything correctly but don't know why on client side it is considered an error.
Does anyone know what is going wrong?

A: I'm guessing you're seeing a parse error. jQuery is expecting to see JSONP, which is JSON wrapped in a callback function, something like
callback({"key" : "value"});

but you're only returning regular JSON, as in
{"key" : "value"}

Change the dataType for jQuery from jsonp to just json

A: It is not possible to perform POST operations using JSONP (only GET operations). I assume you don't even need JSONP.
Instead, use JSON and change your code to
dataType: "json",


text:
Q: Best approach to chain two jobs one after another using Spring Batch I am having two jobs(Job1,Job2)
Job2 is depended on the results of job1 so it has to wait till job 1 finished
I need to chain them somehow:

*

*When job1 finish it needs to call job2. how to do that? using tasklet in the end which will call job2?

*The other way could be that the invoker(which is some scheduler service) will be responsible for calling job2 as soon as job1 returns - not really good because than ill need to call job1 synchronously.
How would you implement two chained (and depended jobs) using spring batch?
Thank you.

A: You can use a JobStep to launch the second job from within the first job. See 5.3.6 Externalizing Flow Definitions and Dependencies Between Jobs

A: This is my way of launching two (a list) jobs one after the other:
1- Declare the two job beans with @Order
@Order(1) // The first in the List
@Bean(name = "firstJob")
public Job firstJob() { .... }

@Order(2) // Second job to be launched
@Bean(name = "secondJob")
public Job secondJob() { .... }

2- Inject the list of jobs
@Autowired
List<Job> jobs;

3- Launch them
    public void run(String... args) {
    JobParameters params = new JobParametersBuilder()
            .addString("JobID", String.valueOf(System.currentTimeMillis()))
            .toJobParameters();
    jobs.forEach(job -> {
        try {
            jobLauncher.run(job, params);
        } catch (Exception e) {
            logger.error("Job {} cannot be executed", job.getName());
            e.printStackTrace();
        }
    });
}

I hope this helps new people reading this post


text:
Q: Query alterando join - SequelizeJS Como poderia fazer essa query utilizando Sequelize?
SELECT t1.* FROM Table1 t1 inner join Table2 t2 on t1.id != t2.t1_id

A: Podes fazer uma raw query e manter esse SQL que já tens. Segundo a documentação podes fazer isso com sequelize.query:
sequelize.query("SELECT t1.* FROM Table1 t1 inner join Table2 t2 on t1.id != t2.t1_id", { type: sequelize.QueryTypes.SELECT})
  .then(function(results) {
    // aqui podes usar o results
  })


text:
Q: Plotting multiple columns of data frame with color map on the same graph I want to plot column number 0 vs all the other columns with a colour map.
I have written in following with For loop. However, all the graphs appear separately and not on the same graph. Below, is the code I wrote,
csv_file1    = pd.read_csv(r'file path')
j            = [i for i in range(1,175)]
for i in j:
    csv_file1.plot.scatter(0,i,c=i,colormap='viridis')
    plt.hold()

How to get all the plot of the same graph?

A: Can't speak for pandas.plot, but you can control when canvases are cleared by using plt.scatter and placing plt.show() outside the loop
import pandas as pd
import matplotlib.pyplot as plt

csv_file1    = pd.read_csv(r'file path')
j            = csv_file.columns.tolist()
for i in j:
    plt.scatter(csv_file1.index,csv_file1[i],colormap='viridis')
plt.show()

A: With pandas, you'll need to draw all the plot using the same ax. Supposing you want to use the first column as x and all the other columns as y, everything colored via the y value. You need to suppress the colorbar, as pandas wants to add an individual colorbar for each column.
from matplotlib import pyplot as plt
import pandas as pd

csv_file1 = pd.read_csv(r'file path')

ax = plt.gca()
columns = csv_file1.columns
for col in columns[1:]:
    csv_file1.plot.scatter(x=columns[0], y=col, c=col, colormap='viridis',
        ax=ax, colorbar=False)
plt.show()

Alternatively, if you want to give each column its own color, you could calculate a list of colors (pandas seems to like them in a list of one color):
colors = [[plt.cm.viridis(i / len(columns))] for i in range(len(columns) - 1)]
for col, color in zip(columns[1:], colors):
    csv_file1.plot.scatter(x=columns[0], y=col, c=color, ax=ax, colorbar=False)
plt.show()


text:
Q: How can we programmatically show that a shallow copy is different from a deep copy? # importing copy module
import copy

# initializing list 1
li1 = [1, 2, [3, 5], 4]

# using copy for shallow copy
li2 = copy.copy(li1)
print("Before Edit:", id(li1[0]) == id(li2[0]))
li2[0] = "hi"
print(li2, "vs", li1)
print("After Edit:", id(li1[0]) == id(li2[0]))
print(id(li1[1]) == id(li2[1]))
print(id(li1) == id(li2))

print()

# using deepcopy for deepcopy
li3 = copy.deepcopy(li1)
print("Before Edit:", id(li1[0]) == id(li3[0]))
li3[0] = "bye"
print(li3, "vs", li1)
print("After Edit:", id(li1[0]) == id(li3[0]))
print(id(li1[1]) == id(li3[1]))
print(id(li1) == id(li3))

Based on the output below, id function in Python doesn't seem to be able to distinguish between a shallow copy and a deep copy. How can I prove that they are actually different from a memory/address standpoint?
Before Edit: True
['hi', 2, [3, 5], 4] vs [1, 2, [3, 5], 4]
After Edit: False
True
False

Before Edit: True
['bye', 2, [3, 5], 4] vs [1, 2, [3, 5], 4]
After Edit: False
True
False

A: You could perhaps also usefully look at memory addresses:
import copy

my_list = [[1, 2, 3], [4, 5, 6]]

my_list_s = copy.copy(my_list)
my_list_d = copy.deepcopy(my_list)

print(f"original-> {id(my_list)} shallow-> {id(my_list_s)} deep->{id(my_list_d)}")
print(f"original-> {id(my_list[0])} shallow-> {id(my_list_s[0])} deep->{id(my_list_d[0])}")

which gives on my system:
original-> 2879112284480 shallow-> 2879112248064 deep->2879112098112
original-> 2879102420352 shallow-> 2879102420352 deep->2879112098048

Note that the shallow copy has a different address from the original but contains the same references as the original. The deepcopy contains different references.

A: The main difference is in how the object items are processed.  So you should be comparing the identifiers of the 3rd element (a list object).  Python's integers are immutable so their id is the same for multiple copies of a given value
A = [1,2,[3,4]]

B = copy.deepCopy(A)
C = copy.copy(A)

id(A[2]) # 140369269603272
id(B[2]) # 140369267423560
id(C[2]) # 140369269603272  (same as A[2])


text:
Q: UWP App example with commandbar, splitview and title I am looking for a example code which use top commandbar, splitview with hamburgericon and title of page with backbutton near humbergericon. Something like a MSN Weaher app:

I am looking exactly the same top bar with title and backbutton and left splitview. Do you know about something like this?

A: You can use Template10 to get an implementation of the SplitView with Burger Icon.
Special consideration about the BackButton : in this sample, this is just a simple button, when clicked you have to call the following code:
if (this.Frame.CanGoBack) this.Frame.GoBack();

If you plan to implement this feature, be carefull when your application will be executed in tablet mode or running on a mobile phone. In these situations, you have to manage also hardware/soft back button. Please check Back button navigation documentation.


text:
Q: Sometime AdMob Banner and interstitial does not load I have finance application on google play and I have 800 active users per day in the app. Some time AdMob banner and interstitialAd does not load and it shows white banner in place of the ad. Java code below :
 AdView adView = (AdView) findViewById(R.id.adView);
            AdRequest adRequest = new AdRequest.Builder()
                   .addTestDevice("CA626566A7B365501AE304BBA64A11D9")
                   .build();
            adView.loadAd(adRequest);

test.xml
<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id" />

AdsUtil.java
// This is my interstitialAd java class when user back any screen then i call showInterstitial(); .
public class AdsUtil {

    private InterstitialAd mInterstitialAd;
    private Context context;

    public AdsUtil(Context context){
        this.context=context;
        mInterstitialAd = newInterstitialAd();
        loadInterstitial();
    }

    private InterstitialAd newInterstitialAd() {
        InterstitialAd interstitialAd = new InterstitialAd(context);
        interstitialAd.setAdUnitId(context.getString(R.string.interstitial_ad_unit_id));

        interstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
//                mNextLevelButton.setEnabled(true);
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
//                mNextLevelButton.setEnabled(true);
            }

            @Override
            public void onAdClosed() {
                // Proceed to the next level.
                goToNextLevel();
            }
        });
        return interstitialAd;
    }

    public void showInterstitial() {
        // Show the ad if it's ready. Otherwise toast and reload the ad.
        if(!Utility.getSharedPreferencesBoolean(context, Constant.isPrimeUser) && Constant.adsFlag ) {

            Constant.adsFlag=false;
            timerAds();

            if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
                mInterstitialAd.show();
            } else {
                goToNextLevel();
            }

        }
    }

    private void loadInterstitial() {
        // Disable the next level button and load the ad.
//        mNextLevelButton.setEnabled(false);
        AdRequest adRequest = new AdRequest.Builder().build();
//                .setRequestAgent("android_studio:ad_template").build();
        mInterstitialAd.loadAd(adRequest);
    }

    private void goToNextLevel() {
        // Show the next level and reload the ad to prepare for the level after.
//        mLevelTextView.setText("Level " + (++mLevel));
        mInterstitialAd = newInterstitialAd();
        loadInterstitial();
    }

    private void timerAds(){
        new CountDownTimer(1000*10*1, 1000) {

            public void onTick(long millisUntilFinished) {

            }

            public void onFinish() {
                Constant.adsFlag=true;
            }
        }.start();
    }

}

A: This is because of 2 reasons,

*

*The network will take time to load the AD as it is being requested on activity open.
To solve this, you have to preload the ADs on app starting and request to display on a particular activity where you need to display this.

*It also depends on the internet connectivity. There will be some delay because of the internet connectivity.


text:
Q: Weakening constraints on rank-2 types {-# LANGUAGE RankNTypes #-}

Continuing from a previous series of questions, I have a function with a universally
quantified function as argument, like so:
emap :: (forall a. Expression a -> Expression a) -> Expression b -> Expression b

Which can be used just fine for functions that need no additional constraints, such as:
postmap :: (forall a. Expression a -> Expression a) -> Expression b -> Expression b
postmap f = f . emap (postmap f)

reduce = postmap step

However, I now want to use this function with a function that takes an additional
constraint, but the following does not type-check.
substitute :: Pack a => Identifier -> a -> Expression a -> Expression a
substitute i v (Var x) | x == i = pack v
substitute _ _ x = x

bind :: Pack a => Identifier -> a -> Expression a -> Expression a
bind ident value = postmap (subsitute ident value)

So it seems that I somehow need to 'weaken' or 'specialize' the forall a constraint to a
forall a. Pack a constraint. It seems unnecessary to add the constraint to the
signature of emap itself, but I can't see any other approach to solving this.
I'm not sure how to work around this, but I can see a few options available.

*

*Add the constraint around the signature for bind such that it can be happily
type-checked.

*Create another function emap' with the constraint, and implement emap' in terms of
emap or vice-versa (emap is a boring mechanical definition and it doesn't make
sense to have two identical function bodies differing only by signature).

*Recognise what I'm trying to do as a code smell and proceed with an alternative
solution. (???)

A: Suppose you rewrote everything such that type T = forall a . Expression a -> Expression a and postmap' :: T -> T. I think it should be clear that the type of postmap is the same. (You can try >:t [postmap', postmap]).
Given that substitute :: Pack a => Identifier -> a -> Expression a -> Expression a, consider your definition of bind: you pass an argument to postmap which expects a value of type T; but you have given it a value of type Expression a -> Expression a. Be careful! These types are not the same, since in the latter case, the forall a is somewhere to the left; postmap is expecting a function where it can pick the a, but it has been given a function were the a is already chosen by someone else. Suppose your example were to typecheck, and then you call bind with a ~ (). The type of the function given to postmap must be Expression () -> Expression (), but this is clearly nonsense.
If I am not very clear, consider the "working" version:
type T = forall a . Expression a -> Expression a

postmap :: T -> T
postmap = undefined

-- These two substitutes have different types!
substitute :: Pack a => Identifier -> a -> Expression a -> Expression a
substitute = undefined

substitute' :: Pack a => Identifier -> a -> T
substitute' = undefined

-- Doesn't compile
bind :: Pack a => Identifier -> a -> Expression a -> Expression a
bind ident value = postmap (substitute ident value)

-- Does compile!
bind' :: Pack a => Identifier -> a -> T
bind' ident value = postmap (substitute' ident value)

The important thing to note: whether you define as above or type T = forall a . Pack a => ..., the error is the same. So your problem is at a different point than you think it is.
The easy way to debug these kinds of problems is to use
newtype T = T (forall a . Expression a -> Expression a)

the errors are often much clearer (though not in this case). I apologize that I can't give a real solution, as I don't know exactly what these functions are actually doing. But I suspect #3 is your answer.

A: To start with, let's flesh out your example with enough code to work with. LiteralToken is just made up to represent whatever you are replacing a variable with.
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}

type Identifier = String

data LiteralToken = LiteralToken
    deriving Show

class Pack a where
    pack :: a -> LiteralToken

instance Pack Int where
    pack = const LiteralToken

data Expression a where
    Var :: Identifier -> Expression a
    Lit :: LiteralToken -> Expression a
    Tuple :: Expression a -> Expression b -> Expression (a, b)

deriving instance Show (Expression a)

emap :: (forall a. Expression a -> Expression a) -> Expression b -> Expression b
emap f e = case e of
    Tuple a b -> Tuple (f a) (f b)
    otherwise -> e

postmap :: (forall a. Expression a -> Expression a) -> Expression b -> Expression b
postmap f = f . emap (postmap f)

bind :: Pack a => Identifier -> a -> Expression b -> Expression b
bind ident value = postmap (substitute ident value)

Now, we can implement substitute for an Identifier. To be used in emap or postmap, substitute needs to be able to operate on all parts of the Expression tree, regardless of whether it's the same type as the variable being substituted for. That's why the type variable for the Expressions is different than the type variable for the value (this is also what user2407038 explains).
substitute :: Pack a => Identifier -> a -> Expression b -> Expression b
substitute ident value e = case e of
    Var id | id == ident -> Lit (pack value)
    otherwise            -> e

Now we can try some examples:
example1 :: Expression (Int, Bool)
example1 = Tuple (Var "x") (Var "y")

print . bind "x" (7 :: Int) $ example1
Tuple (Lit LiteralToken) (Var "y")

If we have the wrong type for the identifier, we don't get what we want, it's substituted anyway. That's because substitute had no way to check the type of the variable it was substituting for. In the following example, both Var "x"s are replaced with the literal that was made for an Int, even though the second variable was for a Bool.
example2 :: Expression (Int, Bool)
example2 = Tuple (Var "x") (Var "x")

print . bind "x" (7 :: Int) $ example2
Tuple (Lit LiteralToken) (Lit LiteralToken)

Type safety
If we add a type variable to LiteralToken so that it somehow depends on the type of what it represents
data LiteralToken a = LiteralToken
    deriving Show

class Pack a where
    pack :: a -> LiteralToken a

data Expression a where
    Var :: Identifier -> Expression a
    Lit :: LiteralToken a -> Expression a
    Tuple :: Expression a -> Expression b -> Expression (a, b)

our previous substitute will have a compiler error.
Could not deduce (b ~ a)
...
In the first argument of `pack', namely `value'
In the first argument of `Lit', namely `(pack value)'
In the expression: Lit (pack value)

substitute needs some way to check that the type it is operating on is correct. Data.Typeable solves this problem. It doesn't seem unreasonable to require that any term represented by a variable have a runtime identifiable type, so it's reasonable to add this constraint to the Expression tree itself. Alternatively, we could add a type annotation to the expression tree that can provide a proof that any term is of a specific type. We'll follow this second route. This will require a few imports.
import Data.Typeable
import Data.Maybe

Here's the expression tree extended to include type annotations.
data Expression a where
    Var :: Identifier -> Expression a
    Lit :: LiteralToken a -> Expression a
    Tuple :: Expression a -> Expression b -> Expression (a, b)
    Typed :: Typeable a => Expression a -> Expression a

emap :: (forall a. Expression a -> Expression a) -> Expression b -> Expression b
emap f e = case e of
    Tuple a b -> Tuple (f a) (f b)
    Typed a   -> Typed (f a)
    otherwise -> e

bind and substitute can now only work on Typeable variables. Substituting a variable lacking a type annotation does nothing, the variable remains untouched.
bind :: (Pack a, Typeable a) => Identifier -> a -> Expression b -> Expression b
bind ident value = postmap (substitute ident value)

substitute :: (Pack a, Typeable a) => Identifier -> a -> Expression b -> Expression b
substitute ident value e = case e of
    Typed (Var id) | id == ident -> fromMaybe e . fmap Typed . gcast . Lit . pack $ value
    otherwise                    -> e

All of the type checking and casting work in substitute is done by gcast. Typeable a from the function's signature provides the proof that the a in the LiteralToken a built by Lit . pack $ value has a Typeable instance. The Typed constructor in the case provides the proof that the output expression's type b also has a Typeable instance. Note that the code would still work if fmap Typed were removed; it is simply preserving the type annotation.
The following two functions make it easy to add type annotations
typed :: Typeable a => Expression a -> Expression a
typed t@(Typed _) = t
typed e           = Typed e

typedVar :: Typeable a => Identifier -> Expression a
typedVar = Typed . Var

Our two examples now do what we'd like them to do. Both examples only replace the integer variable, despite both variable names being the same in the second example.  We use the smart typedVar constructor instead of Var to build all of our variables with a type annotation.
example1 :: Expression (Int, Bool)
example1 = Tuple (typedVar "x") (typedVar "y")

print . bind "x" (7 :: Int) $ example1
Tuple (Typed (Lit LiteralToken)) (Typed (Var "y"))

example2 :: Expression (Int, Bool)
example2 = Tuple (typedVar "x") (typedVar "x")

print . bind "x" (7 :: Int) $ example2
Tuple (Typed (Lit LiteralToken)) (Typed (Var "x"))

Type inference
Just for fun, we can implement type inference on expression trees. Unlike Haskell's, this really simple type inference only works from the leaves towards the root.
inferType :: Expression a -> Expression a
inferType e = case e of
    Typed t@(Typed _)             -> t
    t@(Tuple (Typed _) (Typed _)) -> typed t
    otherwise                     -> e

inferTypes = postmap inferType

print . inferTypes $ example1
Typed (Tuple (Typed (Var "x")) (Typed (Var "y")))


text:
Q: javascript/jQuery location.href misses mark I have a page that has a number of elements that are slid up on startup. I want to be able to slide down a particular pane based on the hash in the url my code is
    if (window.location.hash.length>0){

   var id = window.location.hash;

   if (id.length==7){ //expected hash is 7 chars long (inc #)

    console.log('Comment hash in url, finding link');

    $(id).parents('.details_wrapper').parent().show().find('.details_wrapper').addClass('open').slideDown('slow', function(){ //unhide and slidedown pane
     window.location.href = id;
    });
   }
  }

Which sort of works in that the appropriate pane is revealed and slid down, however the window.location.href doesn't seem to be working very well as the window consistently places the page about 800px further down than where the anchor is.
As a possible side note it seems I can't verify the correct href as typing
window.location.href='#c83225';

into the developer console (Safari) gives an error. It works in the Chrome console though.

A: Another option to do that is
window.location.hash = 'c83225';


text:
Q: Why doesn't Integer.valueOf of a digit Character return its value? I have to say that this was found by a mistake, as I was trying to convert a String to an Integer, but I didn't realize that it is a Character type instead of Integer.
But somehow, the Integer.valueOf can still run with a Character parameter although this was not mentioned in JDK documentation?
System.out.println(Integer.valueOf("2"));  // >>> 2
System.out.println(Integer.valueOf('2'));  // >>> 50

While it works fine for String argument of "2", it doesn't provide the expected result for Character argument of '2'. Why does this happen?
I am trying to understand if I miss anything? Why does it return 50 instead of 2?
Thanks

OK, I checked the ASCII table, it is returning 50 because the index for Character '2' is 50.

A: The ASCII representation should give you a clue about why you are getting this behaviour.
Remember that the Integer and Character classes are wrappers for the int and char primitive types. The reason why Integer.valueOf() works with a Character is that there is an implicit cast to Integer. When you cast a Character to Integer, the Integer will hold the ASCII code for that Character. The same thing happens with primitive types. For example
 Character yourChar = new Character('2');
 Integer yourInt = Integer.valueOf(yourChar);    //Implicit casting

 char biz = '2';
 int baz = (int)biz;                            //Explicit casting to int

 System.out.println(baz);
 System.out.println(yourInt);

Here, the value of both yourInt and baz will be 50, because that is the ASCII code for '2'. The implicit and explicit casting do the same thing.
If you actually want to convert a char which holds a digit to the correct integer, use Character.getNumericValue(). E.g.
 char myChar = '2';
 int myInt = Character.getNumericValue(myChar);

Now myInt holds the value 2.
As far as best-practices go, using this type of implicit conversion isn't a good idea. It doesn't make it obvious what you are trying to do.

A: Integer.valueOf(char)) gives the ASCII value.
Integer.valueOf('2');  // >>> 50

If you want to get numeric value then,
Character.getNumericValue('2'));  // >>> 2


text:
Q: IPython Cell Magic to Run this Cell in Client and in All Engines In IPython for parallel execution we have multiple engines.
The jobs are dispatched to them using: %%px cell magics to set up the environment in the clients and then using  DirectView map_sync to run the various experiments.
The experiments return a named-tuple of results.
Thus this named-tuple need to be declared in both the client and in each engine.
Currently each time I run it, I run it twice, one with %%px and once without.
is there a flag of %%px that will make it run both locally and in each engine?

A: As of IPython 1.0, you can instruct %%px to also execute the cell locally.
This is done using the "--local" flag.
%%px --local
http://nbviewer.ipython.org/github/ipython/ipython/blob/2.x/examples/Parallel%20Computing/Parallel%20Magics.ipynb


text:
Q: Inconsistency About Omitting 'return' Keyword to Return Closure Block in Groovy I've just started learning Groovy. And I got into this: https://groovy-lang.org/style-guide.html#_return_keyword_optional
So, 'return' can be omitted at the end in a method definition. Alright.
Even though I would prefer using it personally, I wanted to take a look.
I tested some simple cases to figure out how it works:
e.g. demo.groovy:
def a1 = { return { return 'hi'} }()
println a1

def a2 = { return {'hi'} }()
println a2

def a3 = { {'hi'} }()
println a3

def a4 = { {-> 'hi'} }()
println a4

I ran the script, and the result was:
demo$_run_closure1$_closure5@21c64522
demo$_run_closure2$_closure6@460f76a6
hi
demo$_run_closure4$_closure7@1922e6d

Starting from the case a1, I omitted keywords 'return' one at a time. They are the cases a2, and a3.
What made me scratch my head is the case a3. I expected the closure to be returned like the cases a1 and a2. But it returned 'hi', not the closure itself.
So I added another test case a4 and then it worked as expected.
I tried to search some documentation about it, but couldn't find a proper one.
Why does it return 'hi' not a closure object?
Thanks in advance.
FYI, my groovy version is:

Groovy Version: 3.0.7 JVM: 15.0.1 Vendor: Oracle Corporation OS: Mac OS X

A: What you see in the a3 example is not a nested closure, but a nested code block instead.

Nested code blocks
An infrequently used structure within Java is the anonymous code block. It's generally not encouraged as it's often a sign that refactoring the related code into a method is in order. But it's sometimes useful to restrict scoping and is now available in Groovy:
{
    def a = 1
    a++
    assert 2 == a
}
try {
    a++ // not defined at this point
} catch(MissingPropertyException ex) {
    println ex.message
}
{
    {
        // inner nesting is another scope
        def a = 'banana'
        assert a.size() == 6
    }
    def a = 1
    assert a == 1
}

Be aware though that in Groovy having a code block looking structure after any method call will be seen as an attempt to pass a closure as the last parameter in the method call. This happens even after a new line. So it's safe to start an anonymous code block after any other block (e.g. an if-then-else statement or another anonymous code block). Anywhere else and you might need to terminate the previous statement with a semicolon. In which case, see the note above about refactoring your code! :-)

Source: https://groovy-lang.org/releasenotes/groovy-3.0.html#_nested_code_blocks

You can run this script in the groovyConsole and go to "Script" -> "Inspect AST" to see what the compiler produces in this case:

You can see that a3 is a closure that implicitly returns 'hi'.
The support for nested code blocks was added in Groovy 3. If you run the same example in Groovy 2, you would see the following compilation error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/home/wololock/workspace/groovy-3-sandbox/src/main.groovy: 7: Ambiguous expression could be either a parameterless closure expression or an isolated open code block;
   solution: Add an explicit closure parameter list, e.g. {it -> ...}, or force it to be treated as an open block by giving it a label, e.g. L:{...} @ line 7, column 12.
   def a3 = { {'hi'} }()
              ^

1 error


text:
Q: How can I calculate $\left[{n\atop k}\right]$? $\left[\begin{array}{c}4\\2\end{array}\right]=11;\left[\begin{array}{c}7\\3\end{array}\right]=1624;$ and $\left[\begin{array}{c}7\\2\end{array}\right]=-1764$
How can I calculate $\left[\begin{array}{c}15\\6\end{array}\right]=?$ or $\left[\begin{array}{c}37\\11\end{array}\right]=?$
What a formula hidden behind these brackets? $\left[\begin{array}{c}n\\k\end{array}\right]$

A: That notation usually refers to the unsigned Stirling numbers of the first kind, but your ${7\brack 2}=-1764$ indicates that someone is using it for the signed Stirling numbers of the first kind.
The easiest way to compute them is by using the recurrence
$${{n+1}\brack k}=n{n\brack k}+{n\brack{k-1}}$$
for the unsigned numbers, with initial conditions ${0\brack 0}=1$ and ${n\brack 0}={0\brack n}=0$ for $n>0$. The signed version of ${n\brack k}$ is obtained by multiplying the unsigned version by $(-1)^{n-k}$. There is no nice closed form.


text:
Q: Use of Haskell state monad a code smell? God I hate the term "code smell", but I can't think of anything more accurate.
I'm designing a high-level language & compiler to Whitespace in my spare time to learn about compiler construction, language design, and functional programming (compiler is being written in Haskell).
During the code generation phase of the compiler, I have to maintain "state"-ish data as I traverse the syntax tree. For example, when compiling flow-control statements I need to generate unique names for the labels to jump to (labels generated from a counter that's passed in, updated, & returned, and the old value of the counter must never be used again). Another example is when I come across in-line string literals in the syntax tree, they need to be permanently converted into heap variables (in Whitespace, strings are best stored on the heap). I'm currently wrapping the entire code generation module in the state monad to handle this.
I've been told that writing a compiler is a problem well suited to the functional paradigm, but I find that I'm designing this in much the same way I would design it in C (you really can write C in any language - even Haskell w/ state monads).
I want to learn how to think in Haskell (rather, in the functional paradigm) - not in C with Haskell syntax. Should I really try to eliminate/minimize use of the state monad, or is it a legitimate functional "design pattern"?

A: Have you looked at Attribute grammars (AG)? (More info on wikipedia and an article in the Monad Reader)?
With AG you can add attributes to a syntax tree. These attributes are separated in synthesized and inherited attributes.
Synthesized attributes are things you generate (or synthesize) from your syntax tree, this could be the generated code, or all comments, or whatever else your interested in.
Inherited attributes are input to your syntax tree, this could be the environment, or a list of labels to use during code generation.
At Utrecht University we use the Attribute Grammar System (UUAGC) to write compilers. This is a pre-processor which generates haskell code (.hs files) from the provided .ag files.

Although, if you're still learning Haskell, then maybe this is not the time to start learning yet another layer of abstraction over that.
In that case, you could manually write the sort of code that attributes grammars generate for you, for example:
data AbstractSyntax = Literal Int | Block AbstractSyntax
                    | Comment String AbstractSyntax

compile :: AbstractSyntax -> [Label] -> (Code, Comments)
compile (Literal x) _      = (generateCode x, [])
compile (Block ast) (l:ls) = let (code', comments) = compile ast ls
                             in (labelCode l code', comments)
compile (Comment s ast) ls = let (code, comments') = compile ast ls
                             in (code, s : comments')

generateCode :: Int -> Code
labelCode :: Label -> Code -> Code

A: I've written multiple compilers in Haskell, and a state monad is a reasonable solution to many compiler problems.  But you want to keep it abstract---don't make it obvious you're using a monad.
Here's an example from the Glasgow Haskell Compiler (which I did not write; I just work around a few edges), where we build control-flow graphs.  Here are the basic ways to make graphs:
empyGraph    :: Graph
mkLabel      :: Label -> Graph
mkAssignment :: Assignment -> Graph  -- modify a register or memory
mkTransfer   :: ControlTransfer -> Graph   -- any control transfer
(<*>)        :: Graph -> Graph -> Graph

But as you've discovered, maintaining a supply of unique labels is tedious at best, so we provide these functions as well:
withFreshLabel :: (Label -> Graph) -> Graph
mkIfThenElse :: (Label -> Label -> Graph) -- branch condition
             -> Graph   -- code in the 'then' branch
             -> Graph   -- code in the 'else' branch
             -> Graph   -- resulting if-then-else construct

The whole Graph thing is an abstract type, and the translator just merrily constructs graphs in purely functional fashion, without being aware that anything monadic is going on.  Then, when the graph is finally constructed, in order to turn it into an algebraic datatype we can generate code from, we give it a supply of unique labels, run the state monad, and pull out the data structure.
The state monad is hidden underneath; although it's not exposed to the client, the definition of Graph is something like this:
type Graph = RealGraph -> [Label] -> (RealGraph, [Label])

or a bit more accurately
type Graph = RealGraph -> State [Label] RealGraph
  -- a Graph is a monadic function from a successor RealGraph to a new RealGraph

With the state monad hidden behind a layer of abstraction, it's not smelly at all!

A: I'd say that state in general is not a code smell, so long as it's kept small and well controlled.
This means that using monads such as State, ST or custom-built ones, or just having a data structure containing state data that you pass around to a few places, is not a bad thing. (Actually, monads are just assistance in doing exactly this!) However, having state that goes all over the place (yes, this means you, IO monad!) is a bad smell.
An fairly clear example of this was when my team was working on our entry for the ICFP Programming Contest 2009 (the code is available at git://git.cynic.net/haskell/icfp-contest-2009). We ended up with several different modular parts to this:

*

*VM: the virtual machine that ran the simulation program

*Controllers: several different sets of routines that read the output of the simulator and generated new control inputs

*Solution: generation of the solution file based on the output of the controllers

*Visualizers: several different sets of routines that read both the input and output ports and generated some sort of visualization or log of what was going on as the simulation progressed

Each of these has its own state, and they all interact in various ways through the input and output values of the VM. We had several different controllers and visualizers, each of which had its own different kind of state.
The key point here was that the the internals of any particular state were limited to their own particular modules, and each module knew nothing about even the existence of state for other modules. Any particular set of stateful code and data was generally only a few dozen lines long, with a handful of data items in the state.
All this was glued together in one small function of about a dozen lines which had no access to the internals of any of the states, and which merely called the right things in the proper order as it looped through the simulation, and passed a very limited amount of outside information to each module (along with the module's previous state, of course).
When state is used in such a limited way, and the type system is preventing you from inadvertently modifying it, it's quite easy to handle. It's one of the beauties of Haskell that it lets you do this.
One answer says, "Don't use monads." From my point of view, this is exactly backwards. Monads are a control structure that, among other things, can help you minimize the amount of code that touches state. If you look at monadic parsers as an example, the state of the parse (i.e., the text being parsed, how far one has gotten in to it, any warnings that have accumulated, etc.) must run through every combinator used in the parser. Yet there will only be a few combinators that actually manipulate the state directly; anything else uses one of these few functions. This allows you to see clearly and in one place all of a small amount of code that can change the state, and more easily reason about how it can be changed, again making it easier to deal with.

A: It's possible that you may want an applicative functor instead of a
monad:
http://www.haskell.org/haskellwiki/Applicative_functor
I think the original paper explains it better than the wiki, however:
http://www.soi.city.ac.uk/~ross/papers/Applicative.html

A: I don't think using the State Monad is a code smell when it used to model state.
If you need to thread state through your functions,
you can do this explicitly, taking the the state as an argument and returning it in each function.
The State Monad offers a good abstraction: it passes the state along for you and
provides lots of useful function to combine functions that require state.
In this case, using the State Monad (or Applicatives) is not a code smell.
However, if you use the State Monad to emulate an imperative style of programming
while a functional solution would suffice, you are just making things complicated.

A: In general you should try to avoid state wherever possible, but that's not always practical.  Applicative makes effectful code look nicer and more functional, especially tree traversal code can benefit from this style.  For the problem of name generation there is now a rather nice package available: value-supply.

A: Well, don't use monads. The power of functional programming is function purity and their reuse. There's this paper a professor of mine once wrote and he's one of the guys who helped build Haskell.
The paper is called "Why functional programming matters", I suggest you read through it. It's a good read.

A: let's be careful about the terminology here.  State is not per se bad; functional languages have state.  What is a "code smell" is when you find yourself wanting to assign variables values and change them.
Of course, the Haskell state monad is there for just that reason -- as with I/O, it's letting you do unsafe and un-functional things in a constrained context.
So, yes, it's probably a code smell.


text:
Q: Understanding terms Twist and Wrench In kinematics, physics and especially robotics, we often encounter the terms Twist and Wrench. Twist is (LinearVelocity, AngularVelocity) and Wrench is (Force, Torque). The reason I'm confused is I see different definitions and I'm no longer sure if I'm using these terms correctly...

*

*Per Wikipedia, Twist is defined in context of screw theory and it has linear velocity and angular velocity both along same axis.

*Some robotics literature uses Twist to have linear velocity part as (V + L X W). This allows to computer work more easily.

*In ROS, popular robotics platform, Twist is simply independent linear and angular velocities.

Questions:

*

*Is it correct to use the term Twist simply as combination of individual linear and angular velocities for any body?

*Is there any similar term to describe combined linear and angular accelerations?

A: Both twist and wrenches are screws. "Screw" is the general term, and "Twist" is the specific application to motion whereas "Wrench" is the specific application to forces and momentum. All of them combine the linear and angular aspects of the thing they describe in one 6×1 object. The definitions pertain to rigid body mechanics in general and are not specific to robotics.
I hope the following definitions will help you out:

*

*Ray/Axis
A 3D Screw is an object that represents a line in space (direction & location) in addition to a magnitude and a pitch value. A screw has 6 components and they are arranged as a vector $\mathbf{e}$ of direction and a vector $\mathbf{m}$ of moment. There are two possible ways to represent a screw, a) Direction then Moment or b) Moment then Direction $$ {\rm Screw} = \left\{ \begin{array}{cl}
 \begin{pmatrix} \mathbf{e} \\ \mathbf{m} \end{pmatrix} & \mbox{ray coordinates} \\
 \begin{pmatrix} \mathbf{m} \\ \mathbf{e} \end{pmatrix} & \mbox{axis coordinates}
\end{array} \right. $$

*Line Composition
Consider a line in space with unit direction vector $\hat{\mathbf{e}}$ and any point on the line $\mathbf{r}$. The line object can be represented with the following coordinates $$ {\rm Line} = \left\{ \begin{array}{cl}
 \begin{pmatrix} \hat{\mathbf{e}} \\ \mathbf{r}\times\hat{\mathbf{e}} \end{pmatrix} & \mbox{ray coordinates} \\
 \begin{pmatrix} \mathbf{r}\times\hat{\mathbf{e}} \\ \hat{\mathbf{e}} \end{pmatrix} & \mbox{axis coordinates}
\end{array} \right. $$ The direction vector is such because it remains the same throughout 3D space (free vector), whereas the moment vector needs to be transformed if the location of interest changes (line vector). This is evident above where the moment vector is defined as the cross product between location and the direction vector.

*Screw Composition
Consider the line above, but add a scalar magnitude $s$ and a scalar pitch $h$. The screw object is similar to the line object but with an additional term parallel to the direction $\hat{\mathbf{e}}$ in the moment vector. $$ {\rm Screw} = \left\{ \begin{array}{cl}
 s \begin{pmatrix} \hat{\mathbf{e}} \\ \mathbf{r}\times\hat{\mathbf{e}}+ h\, \hat{\mathbf{e}} \end{pmatrix} & \mbox{ray coordinates} \\
 s \begin{pmatrix}  \mathbf{r}\times\hat{\mathbf{e}}+ h\, \hat{\mathbf{e}} \\ \hat{\mathbf{e}}  \end{pmatrix} & \mbox{axis coordinates}
\end{array} \right. $$ A pitch represents any components of the moment vector that are parallel to the direction vector as a scalar ratio $h = \frac{\| \mathbf{m}_\parallel \|}{\| \mathbf{e} \|}$

*Screw Decomposition For both ray and axis representation the properties of a screw with direction vector (non unit) $\mathbf{e}$ and moment vector $\mathbf{m}$ are found with the following formulas $$\begin{align}
\mbox{Magnitude} & & s & = \| \mathbf{e} \|  \\
\mbox{Unit Direction} & & \hat{\mathbf{e}} &=\frac{\mathbf{e}}{\| \mathbf{e} \|} \\
\mbox{Position Closest To Origin} & & \mathbf{r} & = \frac{\mathbf{e} \times \mathbf{m}}{ \| \mathbf{e} \|^2 }\\
\mbox{Pitch} & & h & = \frac{\mathbf{e} \cdot \mathbf{m}}{ \| \mathbf{e} \|^2 }\\
\end{align}$$ NOTE: $\times$ is the vector cross product, and $\cdot$ the vector dot product.

*Twists A twist is a screw representing motion (infinitesimal rotation, velocity and spatial acceleration, joint axis). The direction vector angular part, and the moment vector is the linear part (at a fixed point A). For example velocities are $$\begin{align} & \mbox{Axis Coordinates} & & \mbox{Ray Coordinates} \\ \mathbf{v}_A & = \begin{pmatrix} \mathbf{v}_A \\ {\boldsymbol \omega} \end{pmatrix} &
\mathbf{v}_A & = \begin{pmatrix} {\boldsymbol \omega} \\ \mathbf{v}_A \end{pmatrix}
\end{align}$$ Axis coordinates are the most common for twists, but not always. A lot of confusion arises from this as people often use twists and axis coordinates interchangingly. Remember, a twist represents some kind of motion and the coordinate representation has to do with the order in which the direction vector and moment vector is represented.

*Wrench A wrench is a screw representing loading (force, momentum, impulse). The direction vector linear part, and the moment vector is the angular part (at a fixed point A). For example forces are $$\begin{align} & \mbox{Axis Coordinates} & & \mbox{Ray Coordinates} \\ \mathbf{f}_A & = \begin{pmatrix} {\boldsymbol \tau}_A \\ \mathbf{F} \end{pmatrix} &
\mathbf{f}_A & = \begin{pmatrix} \mathbf{F} \\ {\boldsymbol \tau}_A \end{pmatrix}
\end{align}$$ Ray coordinates are the most common for wrenches, but not always.

*Interpretation Both twists and wrenches represent an object at distance. For example a force $\mathbf{F}$ though a point A has torque ${\boldsymbol \tau}_A = \mathbf{r}_A \times \mathbf{F}$. And the velocity of a body rotating about a point A is $\mathbf{v}_A = \mathbf{r}_A \times \mathbf{\omega}$. Both are the moment vectors of the corresponding screws. In the most common notation these are $$ \begin{align} \mathbf{v}_A & = \begin{pmatrix} \mathbf{r}_A \times {\boldsymbol \omega} \\ {\boldsymbol \omega} \end{pmatrix} & \mbox{twist in (linear,angular)=axis coordinates} \\
\mathbf{f}_A & = \begin{pmatrix} \mathbf{F}\\ \mathbf{r}_A \times \mathbf{F} \end{pmatrix} & \mbox{wrench in (linear,angular)=ray coordinates} \end{align} $$ You can see that these are identical to the line compositions.

*Twist Example A body in motion has angular velocity $\mathbf{\omega} = (1,0,5)$ and linear velocity a point A $\mathbf{v}_A = (-2,4,1)$. Show the motion as a twist in axis coordinates and decompose it into its properties

*

*Twist in axis coordinates (6×1 quantity) $$\mathbf{v}_A = \begin{pmatrix} \mbox{moment} \\ \mbox{direction} \end{pmatrix} = \begin{pmatrix} \mathbf{v}_A \\ {\boldsymbol \omega} \end{pmatrix} = \begin{pmatrix} \begin{vmatrix} -2 \\ 4 \\ 1 \end{vmatrix} \\ \begin{vmatrix} 1 \\ 0 \\ 5 \end{vmatrix} \end{pmatrix} $$

*Magnitude: $\| \begin{vmatrix} 1 \\ 0 \\ 5 \end{vmatrix} \| = \sqrt{26}$

*Direction: $ \frac{ \begin{vmatrix} 1 \\ 0 \\ 5 \end{vmatrix} }{\sqrt{26}} = \begin{vmatrix} \frac{1}{\sqrt{26}} \\ 0 \\ \frac{5}{\sqrt{26}} \end{vmatrix}$

*Position: $ \frac{\begin{vmatrix} 1 \\ 0 \\ 5 \end{vmatrix} \times \begin{vmatrix} -2 \\ 4 \\ 1 \end{vmatrix}}{\sqrt{26}^2} = \begin{vmatrix} -\frac{10}{13} \\ -\frac{11}{26} \\ \frac{2}{13} \end{vmatrix}$

*Pitch: $\frac{\begin{vmatrix} 1 \\ 0 \\ 5 \end{vmatrix} \cdot \begin{vmatrix} -2 \\ 4 \\ 1 \end{vmatrix}}{\sqrt{26}^2}= \frac{3}{26} $

*Parallel velocity vector: $\mbox{(pitch)} {\boldsymbol \omega} = \frac{3}{26}  \begin{vmatrix} 1 \\ 0 \\ 5 \end{vmatrix} =  \begin{vmatrix} \frac{3}{26} \\ 0 \\ \frac{15}{26} \end{vmatrix}$
The above represents the geometry of the motion in all the detail that is available from the two pieces of information, the linear and angular velocity at one point.
Similarly for wrenches. The 6 components that define them are decomposed into magnitude, direction, position and pitch.
Related posts.  Forces as Screws, Motion Screw and Instant Rotation Axis

For your second question, linear and angular acceleration does not form a twist (motion screw) because they contain centrifugal terms that do not transform like normal screws. This is because regular acceleration tracks a specific particle, and the screw quantities have a point of measurement fixed in space.
You can however construct an acceleration twist, if instead of using the regular (material) acceleration, you use spatial accelerations. At any point A the spatial acceleration vector ${\boldsymbol \psi}_A$ is the material acceleration $\mathbf{a}_A$ minus the centrifugal terms. $$ {\boldsymbol \psi}_A = \mathbf{a}_A - {\boldsymbol \omega} \times \mathbf{v}_A$$
Then the acceleration twist in axis coordinate is defined as:
$${\boldsymbol \psi}_A = \begin{pmatrix} \mbox{moment} \\ \mbox{direction} \end{pmatrix} = \begin{pmatrix} \mathbf{a}_A - {\boldsymbol \omega} \times \mathbf{v}_A \\ {\boldsymbol \alpha} \end{pmatrix} $$
The above is used the 6×6 equations of motion
$$ \mathbf{f}_A = \mathrm{I}_A {\boldsymbol \psi}_A + \mathbf{v}_A \times \mathrm{I}_A \mathbf{v}_A $$
But that is a subject of another question, as the derivation of the spatial equations of motion is rather involved at this stage.

A: The difference, from what you've posted, seems to depend on the presence of absence of force. I'm not familiar with trade-specific robotics terminology but I do notice in your question:

Twist is (LinearVelocity, AngularVelocity) and Wrench is (Force, Torque).

Note that you can have a velocity without a force or an angular velocity without a torque. If you apply a torque to begin a top spinning, it continues to spin after you let go.
In free space you can set a top spinning and push it along the spin axis, and a point in the rim of the top will describe a helix in space as it travels. The specific ratio of the linear and angular momenta describes a particular twist (as I understand the term as you've used it). This can be compared to, for example the 'pitch' of a screw thread - how many threads per inch, for example. Again, a ratio of a rotational measure to a linear measure along the same axis.
On the other hand, wrench relates force (linear) and torque (rotational). Again, it appears to be a ratio. Given a mass, a wrench applied to the mass will transfer a particular combination of linear and angular momenta and result in a particular twist.
In other words, twist references the velocities and wrench references the accelerations.


text:
Q: how to get all tweets of a user using twitteR package I'm a newbie in R and twitteR package. I am not able to scrape all tweets of a given user.
I tried following
user1<-"@IIMAhmedabad"
tweet_data1<-userTimeline(user = user1, n=3200)

the data contains not all tweets, only 888 tweet were retrieved?
How to download all tweets?


text:
Q: Retrieving keys from a name value pair array in groovy I have an array with values similar to below:
def fieldValuesArray = []
fieldValuesArray << ["key1":"value1"]
fieldValuesArray << ["key2":"value2"]

I would like to retrieve the key values of the array while iterating through it, like
fieldValuesArray.each{
    println(it.key())//key1,key2 etc.
}

Any pointers would be helpful.
Thank you,
LJ

A: In your original question you are asking to access a key-value-pair. Those structures are called maps in Groovy. What you are doing in your first line though, is, to create an array not a map.
Furthermore accessing key value pairs with an each loop could require 2 iteration variables: key and value. Just in case you will need both inside the loop it is easier to read for me. But probably a matter of taste.
Your answer is also not a good approach in my opinion. As you first declare fieldValuesArray as an array and in next line you re-assign it to an initialized map. What looks more correct me is the following:
def fieldValuesArray = [:]
fieldValuesArray << ["key1":"value1"]
fieldValuesArray << ["key2":"value2"]

fieldValuesArray.each{ key, value -> println "${key}:${value}" }
// or
// fieldValuesArray.each{ println it.key }

Please note the first line definition with [:] rather than [] and my each-closure.

A: Just in case anyone is interested, here is the correction to the above.
The first line while adding the values, it should have been = and not <<.
Also, its .key and not key()
def fieldValuesArray = []
fieldValuesArray = ["key1":"value1"]
fieldValuesArray << ["key2":"value2"]

fieldValuesArray.each{val->
    println(val.key)//key1,key2 etc.
}


text:
Q: Deploy Cloudwatch Alarm to non-default region in Central monitoring account using Terraform Overview
The AWS account structure:

*

*"Dashboard and Alerting account" (ap-southeast-1)

*"Prod Workload A account" (ap-southeast-1)

*"Prod Workload B account" (us-west-2)

IAM Roles and policies exist in the Prod Workload A and B AWS accounts, which allow the Dashboarding and Alerting AWS account to read metrics and logs e.g. centralised dashboarding.
The Dashboards and Alarms are deployed to the "Dashboarding and Alerting AWS account" using Terraform:
DASHBOARD SNIPPET
resource "aws_cloudwatch_dashboard" "rds_db" {
  for_each       = local.env[var.environment]
  dashboard_name = "${each.key}_rds_db"
  dashboard_body = templatefile("templates/rds_db.tpl", {
    environment = each.value.env,
    account     = each.value.account,
    region      = each.value.region
  })
}

ALARM SNIPPET
resource "aws_cloudwatch_metric_alarm" "rds_cpu_utilisation" {
for_each                  = local.env_map[var.environment]
  alarm_name                = "High_CPU_Utilisation_RDS_${each.value.env}-rds-db"
  comparison_operator       = "GreaterThanThreshold"
  evaluation_periods        = "3"
  threshold                 = "70"
  alarm_description         = "The High CPU Utilisation threshold has been breached."
  insufficient_data_actions = []
  treat_missing_data        = "breaching"
  alarm_actions = [
    aws_sns_topic.rds_db_alert_topic.arn
  ]

  metric_query {
    id          = "m1"
    return_data = "true"
    account_id  = each.value.account
    metric {
      metric_name = "CPUUtilization"
      namespace   = "AWS/RDS"
      period      = "60"
      stat        = "Maximum"
      dimensions = {
        DBInstanceIdentifier = "${each.value.env}-rds-db"
      }
    }
  }
}

Question
When deploying Alarms for the "Prod Workload b account" to the centralised account, the region defaults to that of the "Dashboard and Alerting account", which is ap-southeast-1.
These alarms, therefore, show as having no data as the data for these alarms must be read from the non-default region us-west-2.
This isn't an issue for dashboards because it's possible to specify the region (see the Dashboard snippet above and Terraform dashboard doc).  Also it's not a problem for "Prod Workload b account" Alarms as this account's default region is the same as the "Dashboard and Alerting account".
The region option doesn't exist for the Terraform Cloudwatch Alarm resource.
It is present in the AWS CLI put-alarm and makes me wonder if it should be present as an option in the Terraform Cloudwatch Alarm resource.
What would be the best way to fix this, so Cloudwatch Alarms can be successfully deployed for "Prod Workload B account" using Terraform?

A: The way to do this is to use Terraform providers.  https://github.com/hashicorp/terraform-provider-aws/issues/28971


text:
Q: Run a VS Python module from a VS C++ application I am trying to run a VS Python application module from a VS C++ application.
I have the following snippet.  I have a value for pName but get a NULL for pModule.
pName = PyUnicode_FromString("C:\\PythonApplication2.py");
pModule = PyImport_Import(pName);

The python application runs fine in the python env.  Is there a tutorial or example that will get me past this issue?
Here is the c++ code...
#include <iostream>
#include <Python.h>

int main()
{
std::cout << "Hello World!\n";
PyObject* pName, * pModule, * pDict, * pFunc, * pArgs, * pValue;
Py_Initialize();
pName = PyUnicode_FromString("C:<name of python file>.py");
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "multiply");

Py_Finalize();
}


text:
Q: fractions with negative numerators and denominators I've been having this doubt in my mind.. I really don't get the concept behind fractions with negative numerators and denominators being equal to there positive form. For eg.: $\frac{-2}{-3} = \frac{2}{3}$. I tried to google it but there were no relevant answers. Can anyone help, please?

A: Quite simple with the rules of simplification:
$$\frac{\not ka}{\not kb}=\frac ab, \quad\text{so}\enspace\frac{-2}{-3}=\frac{(-1)2}{(-1)3}=\frac 23.$$
Variant:
$$\frac ab=\frac cd\iff ad=bc,\quad\text{and observe }\;(-2)\,3=(-3)\,2.$$

A: Using the fact that $\frac{a}{a}=1$ for all $a\neq 0$, you get $$\frac{-2}{-3} = \frac{(-1)\cdot 2}{(-1)\cdot 3} = \frac{-1}{-1}\cdot\frac23 = 1\cdot\frac23=\frac23$$

A: On a basic level, when you consider $\frac xy$, you ask how many $y$ go into $x$. E.g. if you do $\frac 42$ you think: how many $2$s go into $4$ and deduce the answer to be $2$.
What about with negative numbers. How many $-2$s go into $-4$? The answer is also $2$ as $2*-2=-4$. This can be represented as $\frac{-4}{-2}=2$, and explains why a negative divided by a negative is positive.


text:
Q: SQL Server : combine multiple records into one field I have created the following SQL script:
SELECT
    E.ID,
    abc = STUFF((SELECT ' ' + E2.ExclusionID
                 FROM Exclusion E2
                 WHERE E.ID = E2.ID
                 FOR XML PATH ('')), 1, 0, '')
FROM
    Exclusion E
GROUP BY
    E.ContractMovementID

It combines all exclusion records for the ID into one record and displays as below:
ID     ExclusionID
-------------------
1      123
2      2345
3      4567

However, I would like it to display as:
ID     ExclusionID
-------------------
1      1 2 3
2      23 45
3      45 67

So that the columns are separated with space, however, I cannot seem to get it to put a space between them. Can anyone help me with this? (I hope this makes sense)
Thanks
Jessica

A: How about this:
SELECT
    E.ID,
    abc = STUFF((SELECT '  ' + E2.ExclusionID
                 FROM Exclusion E2
                 WHERE E.ID = E2.ID
                 FOR XML PATH ('')), 1, 1, '')
FROM
    Exclusion E
GROUP BY
    E.ContractMovementID

A: I have found a solution, because the exclusion.id was an INT data type i had to convert it into a varchar to be able to add a seperator.
SELECT
    E.ID,
    abc = STUFF((SELECT CAST(E2.ExclusionID AS VARCHAR) + ','
                 FROM Exclusion E2
                 WHERE E.ID = E2.ID
                 FOR XML PATH ('')), 1, 0, '')  FROM
    Exclusion E  GROUP BY
    E.ContractMovementID


text:
Q: Changing button text based on language settings need to refresh the page in angular I am using ngx-translate for the internationalization of my app. In my HTML page I am using translate pipe to change the language. The example is below:
<app-pagetitle title="{{ 'PAGES.DASHBOARD' | translate }}"></app-pagetitle>

In one of my form, I need to change the button text based on condition from TS file. Here is the code:
this.translateService.get('BUTTON_TEXT.SAVE_BUTTON').subscribe((translatedString) => {
                    this.saveButtonLabel = translatedString;
                 });

and my language json file is:
    {
    "PAGES": {
            "DASHBOARD": "Dashboard",
            "WHITEBOARD": "Whiteboard"
        },
        "BUTTON_TEXT": {
            "SAVE_BUTTON": "Save",
            "UPDATE_BUTTON": "Update"
        }

}

Now the problem is button text is not changing whenever I change the language from topbar. I need to refresh the page. Can anyone help me?

A: There could be couple of ways to resolve this and the one solution I can think of is to manually triggering Change Detection:
import { ChangeDetectorRef } from "@angular/core";
...
constructor(
  ...
  private cdr: ChangeDetectionRef
) {}
...
this.translateService.get('PAGES.DASHBOARD')
  .subscribe((translatedString) => {
    this.saveButtonLabel = translatedString;
    this.cdr.detectChanges();
});

Another solution that I can think of is to use async pipe & for that you need to tweak your code a bit:
saveButtonLabel: Subject<string> = new Subject<string>();
...
this.translateService.get('PAGES.DASHBOARD')
  .subscribe((translatedString) => {
    this.saveButtonLabel.next(translatedString);
});

<button>{{ saveButtonLabel | async }}</button>


text:
Q: Do derived classes update their parents classes properties? I have several classes that are derived classes from a parent, they all update some values and I don't know if they have their own version of these values or they are actually updating the parent's properties as the app is navigated and different classes are being used, I suspect it's the latter.
It's the sideContent that I'm looking at, and any other property for that matter.
The parent:
export abstract class EngagementGraphNode {

  public sideContent: IEngagementSideContent;

  constructor(json?: IEngagementGraphNode) {
    if (json) {
      this.id = json.id;
      this.name = json.name;
    }
  }

Example of a child component:
export class EngagementProductGroup extends EngagementGraphNode {
  constructor() {
    super();
    this.placeholder = this.getIcon('more');
    this.icon = true;
    this.type = EngagementType.ProductGroup;
  }

  setProperties(json: IEngagementGraphNode, color: string): void {
    this.id = json.id;

      this.sideContent = {
        overview: { isLoading: true, title: 'Overview', id: 0 },
        members: { isLoading: false, title: 'Engaged Individuals', id: 1, individuals: this.individuals }
      }
    }

If this is the case, then I'm guessing at the point that the website is looking at that particular bit of code then that is updating the parent class as it goes along?
Thanks very much if you can help!

A: Every object has its own set of properties (instance variables) depending on how the property is declared.
If the parent property was declared with the static keyword (just like the public access modifier), then modifying the parent property from any of the children object would modify that value among all children objects (since it is being shared).
Since, they are not static in your case, each children has their own copy of the parent variable, which are safe from change when any of the children change their parent's variable.