text:
Q: How to send body with form-data format in mocha chai This is my headers postman:

This is my body form-data in postman:

I am already trying like this
describe('test', function() {
  describe('Get User Data', function() {
    it.only('bla bla bla', function(done) {
      // Send some Form Data
      chai
        .request(app)
        .post('/user/login')
        .send({ username: 'ihdisetiawan', password: 'testing123' })
        .set('Accept', 'application/json')
        .set('x-api-key', '1234567890')
        .end(function(err, res) {
          expect(res.status).to.equal(responseMessageCode.successOk);
          // expect(res.password).to.equal("testing123");
          done();
        });
    });
  });
});

the response get 422
Uncaught AssertionError: expected 422 to equal 200
      + expected - actual

      -422
      +200

A: You need to use multer middleware for handling the request payload with multipart/form-data content type.
Besides, your case only handle a text-only multipart form, you should use the .none() method of multer.
E.g.
server.ts:
import express from 'express';
import multer from 'multer';

const app = express();
const port = 3000;
const upload = multer();
app.post('/user/login', upload.none(), (req, res) => {
  console.log('username:', req.body.username);
  console.log('password:', req.body.password);
  console.log('content-type:', req.get('Content-Type'));
  console.log('x-api-key:', req.get('x-api-key'));
  res.sendStatus(200);
});

if (require.main === module) {
  app.listen(port, () => {
    console.log(`HTTP server is listening on http://localhost:${port}`);
  });
}

export { app };

server.test.ts:
import { app } from './server';
import request from 'supertest';
import { expect } from 'chai';

describe('test', () => {
  describe('Get User Data', () => {
    it('bla bla bla', (done) => {
      request(app)
        .post('/user/login')
        .field({
          username: 'ihdisetiawan',
          password: 'testing123',
        })
        .set('x-api-key', '1234567890')
        .end((err, res) => {
          expect(res.status).to.equal(200);
          done();
        });
    });
  });
});

integration test results with coverage report:
  test
    Get User Data
username: ihdisetiawan
password: testing123
content-type: multipart/form-data; boundary=--------------------------481112684938590474892724
x-api-key: 1234567890
      ✓ bla bla bla (47ms)

  1 passing (66ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files  |   86.67 |       50 |      50 |   86.67 |
 server.ts |   86.67 |       50 |      50 |   86.67 | 16,17
-----------|---------|----------|---------|---------|-------------------


text:
Q: How to convert string to variable name to access value in json object? How can I convert a string to a variable name that I can use to access a value in a json object?
This works, but "fname" is hard coded, not dynamic:
$("#ppl").append(people[i].fname);

I want something like this:
var myString = "fname";

$("#ppl").append(people[i].myString); // doesn't work

or
$("#ppl").append(people[i].window['myString']); // also doesn't work

Help!
Here is the jsfiddle

A: people[i][myString]
Will work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting in Rails: SQLite vs PostgreSQL When I order by a column (id type INT) in Rails 5 with sqlite as the development db, it sorts as expected (1,2,3,4...) but the same thing on my production environment (PostgreSQL) results in unexpected behaviour (1, 101, 102,...2, 201,...) and so on.
If I format the order as per PostgreSQL (MyModel.order('id::integer DESC') then it works fine in PostgreSQL but no longer works in my development sqlite environment.
Am I overlooking something? I'm quite new to programming.

A:
Your data types are messed up. What does .schema your_table say in the
  sqlite3 shell? How about \d your_table from psql? Keep in mind that
  SQLite has a very loose value-based type system rather than a
  column-based one (i.e. you can put a string in a column declared as an
  integer and SQLite won't say a thing). – mu is too short


text:
Q: spaCy NLP extract intent using wordlist I am following an example from the book Mastering spaCy, and I want to extract the intent of a sentence using a wordlist, using the following code:
from spacy.matcher import Matcher
from collections import Counter
from spacy import displacy
import en_core_web_md
import pandas as pd
import spacy

nlp = en_core_web_md.load()

doc = nlp("i want to make a reservation for a flight")
dObj =None
tVerb = None

# Extract the direct object and its transitive verb
for token in doc:
    if token.dep_ == "dobj":
        dObj = token
        tVerb = token.head

# Extract the helper verb
intentVerb = None
verbList = ["want", "like", "need", "order"]
if tVerb.text in verbList:
    intentVerb = tVerb
else:
    if tVerb.head.dep_ == "ROOT":
        helperVerb = tVerb.head

# Extract the object of the intent
intentObj = None
objList = ["flight", "meal", "booking"]

if dObj.text in objList:
      intentObj = dObj
else:
      for child in dObj.children:
        if child.dep_ == "prep":
            intentObj = list(child.children)[0]
            break
        elif child.dep_ == "compound":
            intentObj = child
            break
print(intentVerb.text + intentObj.text.capitalize())

The desired outcome is

wantFlight

but I got this error
34 print(intentVerb.text + intentObj.text.capitalize())
AttributeError: 'NoneType' object has no attribute 'text'

The error comes when I try to extract the helper verb
Any help will be appreciated
Cheers

A: tVerb = None # <- init with None

for token in doc:
    if token.dep_ == "dobj":
        dObj = token
        tVerb = token.head # <- overwrites tVerb for each token, at the end
                           # tverb will be the .head of 'flight'

verbList = ["want", "like", "need", "order"]
if tVerb.text in verbList:
    intentVerb = tVerb # <- 'flight' is not in verbList so intentVerb is never set
                       # and still the init: None

print(intentVerb.text + intentObj.text.capitalize())  # <- None type has no attribute '.text' therefore you get your error.

As a general advise, look up debugging and ideally chose a IDE with debugging support.


text:
Q: Angular-tree-component not displaying any nodes I am very new to Angular and web development in general.
All I want is for the TreeView to show the nodes "Root1" and "Root2".
At the moment, all I get is the label "My Tree View". I am trying to implement the angular2-tree library. The problem is most likely in my HTML. Thanks for any feedback.
Documentation:
https://angular2-tree.readme.io/docs/getting-started

import { Component, OnInit, OnDestroy, NgModule, } from '@angular/core';
import { TreeViewService, } from './tree-view.service';
import { TreeModule } from 'angular-tree-component';

import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/distinctUntilChanged';

@NgModule({
    imports: [TreeModule],

})

@Component({
    selector: 'TreeViewComponent',
    template: '<tree-root [focused] = "true" [nodes]="nodes"></tree-root>'

    //templateUrl: './tree-view.component.html',
    //styleUrls: ['./tree-view.component.css']
})

export class TreeViewComponent {
    nodes = [
        {
            id: 1,
            name: 'root1',
            children: [
                { id: 2, name: 'child1' },
                { id: 3, name: 'child2' }
            ]
        },
        {
            id: 4,
            name: 'root2',
            children: [
                { id: 5, name: 'child2.1' },
                {
                    id: 6,
                    name: 'child2.2',
                    children: [
                        { id: 7, name: 'subsub' }
                    ]
                }
            ]
        }
    ];
    options = {};
}
.tree-children.tree-children-no-padding { padding-left: 0 }
.tree-children { padding-left: 20px; overflow: hidden }
.node-drop-slot { display: block; height: 2px }
.node-drop-slot.is-dragging-over { background: #ddffee; height: 20px; border: 2px dotted #888; }
.toggle-children-wrapper-expanded .toggle-children { transform: rotate(90deg) }
.toggle-children-wrapper-collapsed .toggle-children { transform: rotate(0); }
.toggle-children-wrapper {
  padding: 2px 3px 5px 1px;
}
/* tslint:disable */
.toggle-children {
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAYAAABSO15qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABAhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDY3IDc5LjE1Nzc0NywgMjAxNS8wMy8zMC0yMzo0MDo0MiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ1dWlkOjY1RTYzOTA2ODZDRjExREJBNkUyRDg4N0NFQUNCNDA3IiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOkYzRkRFQjcxODUzNTExRTU4RTQwRkQwODFEOUZEMEE3IiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOkYzRkRFQjcwODUzNTExRTU4RTQwRkQwODFEOUZEMEE3IiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDQyAyMDE1IChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6MTk5NzA1OGEtZDI3OC00NDZkLWE4ODgtNGM4MGQ4YWI1NzNmIiBzdFJlZjpkb2N1bWVudElEPSJhZG9iZTpkb2NpZDpwaG90b3Nob3A6YzRkZmQxMGMtY2NlNS0xMTc4LWE5OGQtY2NkZmM5ODk5YWYwIi8+IDxkYzp0aXRsZT4gPHJkZjpBbHQ+IDxyZGY6bGkgeG1sOmxhbmc9IngtZGVmYXVsdCI+Z2x5cGhpY29uczwvcmRmOmxpPiA8L3JkZjpBbHQ+IDwvZGM6dGl0bGU+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+5iogFwAAAGhJREFUeNpiYGBgKABigf///zOQg0EARH4A4gZyDIIZ8B/JoAJKDIDhB0CcQIkBRBtEyABkgxwoMQCGD6AbRKoBGAYxQgXIBRuZGKgAKPIC3QLxArnRSHZCIjspk52ZKMrOFBUoAAEGAKnq593MQAZtAAAAAElFTkSuQmCC');
  height: 8px;
  width: 9px;
  background-size: contain;
  display: inline-block;
  position: relative;
  top: 1px;
  background-repeat: no-repeat;
  background-position: center;
}
.toggle-children-placeholder {
  display: inline-block;
  height: 10px;
  width: 10px;
  position: relative;
  top: 1px;
  padding-right: 3px;
}
.node-content-wrapper {
  display: inline-block;
  padding: 2px 5px;
  border-radius: 2px;
  transition: background-color .15s,box-shadow .15s;
}
.node-wrapper {display: flex; align-items: flex-start;}
.node-content-wrapper-active,
.node-content-wrapper.node-content-wrapper-active:hover,
.node-content-wrapper-active.node-content-wrapper-focused {
  background: #beebff;
}
.node-content-wrapper-focused { background: #e7f4f9 }
.node-content-wrapper:hover { background: #f7fbff }
.node-content-wrapper-active, .node-content-wrapper-focused, .node-content-wrapper:hover {
  box-shadow: inset 0 0 1px #999;
}
.node-content-wrapper.is-dragging-over { background: #ddffee; box-shadow: inset 0 0 1px #999; }
.node-content-wrapper.is-dragging-over-disabled { opacity: 0.5 }

tree-viewport {
  -webkit-tap-highlight-color: transparent;
  height: 100%;
  overflow: auto;
  display: block;
}
.tree-children { padding-left: 20px }
.empty-tree-drop-slot .node-drop-slot { height: 20px; min-width: 100px }
.angular-tree-component {
  width: 100%;
  position:relative;
  display: inline-block;
  cursor: pointer;
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none;   /* Chrome/Safari/Opera */
  -khtml-user-select: none;    /* Konqueror */
  -moz-user-select: none;      /* Firefox */
  -ms-user-select: none;       /* IE/Edge */
  user-select: none;           /* non-prefixed version, currently not supported by any browser */
}

tree-root .angular-tree-component-rtl {
  direction: rtl;
}
tree-root .angular-tree-component-rtl .toggle-children-wrapper-collapsed .toggle-children {
  transform: rotate(180deg) !important;
}
tree-root .angular-tree-component-rtl .tree-children {
  padding-right: 20px;
  padding-left: 0;
}

tree-node-checkbox {
  padding: 1px;
}

    My Tree View
    <tree-root class="panel-body " [nodes]="Items" [options]="options">
    </tree-root>

A: you are not using the correct selector of the component in the HTML. as your selector name is - 'TreeViewComponent' you should use it like below -

    My Tree View
    <TreeViewComponent></TreeViewComponent>

Here is the code for TreeViewComponent  -
import { Component, OnInit, OnDestroy, NgModule, } from '@angular/core';
import { TreeModule } from 'angular-tree-component';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/distinctUntilChanged';

@Component({
    selector: 'TreeViewComponent',
    template: '<tree-root [nodes]="nodes" [focused]="true" [options]="options"></tree-root>',
    styles:[`.tree-children.tree-children-no-padding { padding-left: 0 }
.tree-children { padding-left: 20px; overflow: hidden }
.node-drop-slot { display: block; height: 2px }
.node-drop-slot.is-dragging-over { background: #ddffee; height: 20px; border: 2px dotted #888; }
.toggle-children-wrapper-expanded .toggle-children { transform: rotate(90deg) }
.toggle-children-wrapper-collapsed .toggle-children { transform: rotate(0); }
.toggle-children-wrapper {
  padding: 2px 3px 5px 1px;
}
/* tslint:disable */
.toggle-children {
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAYAAABSO15qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABAhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDY3IDc5LjE1Nzc0NywgMjAxNS8wMy8zMC0yMzo0MDo0MiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ1dWlkOjY1RTYzOTA2ODZDRjExREJBNkUyRDg4N0NFQUNCNDA3IiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOkYzRkRFQjcxODUzNTExRTU4RTQwRkQwODFEOUZEMEE3IiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOkYzRkRFQjcwODUzNTExRTU4RTQwRkQwODFEOUZEMEE3IiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDQyAyMDE1IChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6MTk5NzA1OGEtZDI3OC00NDZkLWE4ODgtNGM4MGQ4YWI1NzNmIiBzdFJlZjpkb2N1bWVudElEPSJhZG9iZTpkb2NpZDpwaG90b3Nob3A6YzRkZmQxMGMtY2NlNS0xMTc4LWE5OGQtY2NkZmM5ODk5YWYwIi8+IDxkYzp0aXRsZT4gPHJkZjpBbHQ+IDxyZGY6bGkgeG1sOmxhbmc9IngtZGVmYXVsdCI+Z2x5cGhpY29uczwvcmRmOmxpPiA8L3JkZjpBbHQ+IDwvZGM6dGl0bGU+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+5iogFwAAAGhJREFUeNpiYGBgKABigf///zOQg0EARH4A4gZyDIIZ8B/JoAJKDIDhB0CcQIkBRBtEyABkgxwoMQCGD6AbRKoBGAYxQgXIBRuZGKgAKPIC3QLxArnRSHZCIjspk52ZKMrOFBUoAAEGAKnq593MQAZtAAAAAElFTkSuQmCC');
  height: 8px;
  width: 9px;
  background-size: contain;
  display: inline-block;
  position: relative;
  top: 1px;
  background-repeat: no-repeat;
  background-position: center;
}
.toggle-children-placeholder {
  display: inline-block;
  height: 10px;
  width: 10px;
  position: relative;
  top: 1px;
  padding-right: 3px;
}
.node-content-wrapper {
  display: inline-block;
  padding: 2px 5px;
  border-radius: 2px;
  transition: background-color .15s,box-shadow .15s;
}
.node-wrapper {display: flex; align-items: flex-start;}
.node-content-wrapper-active,
.node-content-wrapper.node-content-wrapper-active:hover,
.node-content-wrapper-active.node-content-wrapper-focused {
  background: #beebff;
}
.node-content-wrapper-focused { background: #e7f4f9 }
.node-content-wrapper:hover { background: #f7fbff }
.node-content-wrapper-active, .node-content-wrapper-focused, .node-content-wrapper:hover {
  box-shadow: inset 0 0 1px #999;
}
.node-content-wrapper.is-dragging-over { background: #ddffee; box-shadow: inset 0 0 1px #999; }
.node-content-wrapper.is-dragging-over-disabled { opacity: 0.5 }

tree-viewport {
  -webkit-tap-highlight-color: transparent;
  height: 100%;
  overflow: auto;
  display: block;
}
.tree-children { padding-left: 20px }
.empty-tree-drop-slot .node-drop-slot { height: 20px; min-width: 100px }
.angular-tree-component {
  width: 100%;
  position:relative;
  display: inline-block;
  cursor: pointer;
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none;   /* Chrome/Safari/Opera */
  -khtml-user-select: none;    /* Konqueror */
  -moz-user-select: none;      /* Firefox */
  -ms-user-select: none;       /* IE/Edge */
  user-select: none;           /* non-prefixed version, currently not supported by any browser */
}

tree-root .angular-tree-component-rtl {
  direction: rtl;
}
tree-root .angular-tree-component-rtl .toggle-children-wrapper-collapsed .toggle-children {
  transform: rotate(180deg) !important;
}
tree-root .angular-tree-component-rtl .tree-children {
  padding-right: 20px;
  padding-left: 0;
}

tree-node-checkbox {
  padding: 1px;
}`]

})

export class TreeViewComponent {
    nodes = [
        {
            id: 1,
            name: 'root1',
            children: [
                { id: 2, name: 'child1' },
                { id: 3, name: 'child2' }
            ]
        },
        {
            id: 4,
            name: 'root2',
            children: [
                { id: 5, name: 'child2.1' },
                {
                    id: 6,
                    name: 'child2.2',
                    children: [
                        { id: 7, name: 'subsub' }
                    ]
                }
            ]
        },
        {
            id: 8,
            name: 'root3',
            children: [
                { id: 9, name: 'child1' }
            ]
        }
    ];
    options = {};
}

Here is the complete app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { TreeModule } from 'angular-tree-component';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import {TreeViewComponent} from "./treeview.component"

@NgModule({
  imports:      [ BrowserModule, FormsModule,TreeModule ],
  declarations: [ AppComponent, HelloComponent,TreeViewComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

As you have set [focused]="true" in the template like below
<tree-root [nodes]="nodes" [focused]="true" [options]="options"></tree-root>

The children nodes can be opened only by keyboard keys.
Here is a working demo :
https://stackblitz.com/edit/angular4-kgl5cj?file=app%2Ftreeview.component.ts


text:
Q: nested post object with form data I have my Rails backend organized to receive a POST like this in a controller:
{
    "entry": {
        "title": {
        "media": {
              "description": "some text",
              "image": ...image here,
        }
    }
}

I can create the entry by POSTing a json like the above, with a base64 encoded image, but I would like to do this using formData instead (because the image might be large, or might even be a video...). I have tried this using Postman and I can create the entry with parameters as entry[title] etc, but how do I express the image attribute? Is it even possible? I tried entry[media][image]but that did not work (did not seemed right either...)
Is it possible to nest things like this when using formData?

A: Sure you can.
Do something like this, depending on what is an array or not:
entry[0].title
entry[0].media.description
entry[0].media.image


text:
Q: Angular Google Maps second There are answers to this problem but they don't work on my current situation.

*

*solution 1: resize.
google.maps.event.trigger(map, 'resize');

The resize redraws the map but it doesn't center, the center gets moved to the top left corner.
I tried to also put another event trigger like ...trigger(map, 'center') without success.

*ng-if and refresh=true don't work at all, the map is not rendered as before.

*other questions seem to be solved by using angular ui (not quite sure what they meant by this) but this is based in angular material.
Thanks to all for the help.
When using angular google maps 2.0.19 and angular material, a Google Map displays properly  the first time it loads. But if the user clicks on a different state and then comes back, without reloading, of course, it only displays a corner of the original map.

Notice on the left the angular material look and on the right the empty space in darker gray, where the rest of the map should show.
The configurations is pretty vanilla:
 <ui-gmap-google-map draggable="true"
        pan="true"
        zoom="map.zoom"
        dragging="true"
        center="map.center"
        events="map.events"
        control="map.control"
        refresh="true">

And the loading from the controller also:
$scope.map = addressStore.setMap({lat: address.latitude,
                        lng: address.longitude});
 //...also loads other parameters.

In a previous project had the same problem with Angular UI but got solved with this command at the begining of the controller:
 google.maps.visualRefresh = true;

But then I moved to Angular Material in this app and the problem showed again.
Thanks in advance.


text:
Q: "Cloud" term is being sold and abused, what do I do? I'm employed by an organization that is selling their products by claiming that it's in the "cloud." Their "cloud" is 2 servers with a few external USB hard drives "at the ready."
I told them that we conform to ZERO of the 5 characteristics of "cloud" as defined by the US Government.
I informed them of NIST pub 800-145... but they completely rejected it outright. They still think that "cloud" is only bullshit bingo. The CEO was pissed that I brought it up... and firmly believes his interpretation of "cloud" is the right one.
What do I do? I now fear for my job...

A: Well, if I were you and I'd work in a company that's telling lies to customers, I'd get myself another job. Sooner or later this might blow up and then you'll be that person that worked for that "bad" company.
Step out while you can.


text:
Q: Can I specify double-click selection delimiters in Terminal.app? In Mac OS X's Terminal.app, I'd like to set my own selection delimiters such that if I have the text foo.bar.baz and double click bar, only bar is selected.
Is this possible and if so how?

A: It would appear from this question that it isn't configurable, at least system wide, and that configurable applications are rare. However, iTerm was mentioned as one that is.

A: Shift + Command + double_click
From:
http://discussions.apple.com/thread.jspa?threadID=2400559&start=15&tstart=0


text:
Q: S-Parameters of lossy two-port network I have a lossy passive two-port network with some input mismatch, so, $$ S_{11} \neq 0 $$
By simulation, I find the S11 and S21 parameters. What I would like to know is the losses within the network, when a wave is incident at port 1. I first thought it should be
$$ 1 - |S_{11}|^2 - |S_{21}|^2 $$ because what is not reflected and not transmitted must be lost within the network. However, a discussion with a colleague gave rise to the idea that $$S_{21}$$ is somehow contained within $$S_{11}$$... So, is it possible to find the losses from S-Parameters?

A: How is \$S_{21}\$ contained in \$S_{11}\$? By the definition of S-parameters, \$S_{11}\$ is the amount of wave leaving the two-port from port 1 when all other ports are terminated in a matched load, and a wave is incident on port 1. \$S_{21}\$ is the wave energy leaving port 2 due to an incident wave on port 1. Therefore, your original statement is correct, in that the power lost (assuming all energy absorbed in the two port is loss) is:
$$ 1 - |S_{11}|^2 - |S_{21}|^2 $$
The amount of incident wave power, minus the reflected power, minus the power that makes it through the system. In fact, this equation is often used to define a lossless, passive two-port (although it's usually written in a different form, and it has to apply for both directions). One could write this as:
A passive two port is lossless when:
$$ |S_{11}|^2 + |S_{21}|^2 = 1$$
$$ |S_{22}|^2 + |S_{12}|^2 = 1$$
*Usually this is written in matrix equations, where they have the added benefit that they can be generalized to N-port networks.


text:
Q: How to select a RAW column in an Eloquent Model? I would like to add a custom column in my Eloquent model such as:
class Shape extends Eloquent
{
    public function getAreaAttribute()
    {
        return $this->width * $this->height;
    }
}

Which allows to build a query such as this:
Shape::where('area', '>', 42)->get();

What I could do is:
Shape::select(['*', DB::RAW('width * height AS area')])->where('area', '>', 42)->get();

But this is not in my model. Is it possible to get something like:
class Shape extends Eloquent
{
    public function getAreaColumn()
    {
        return DB::RAW('width * height AS area')
    }
}

A: You can define this in your migration:
$table->integer('area')->virtualAs('height * width');

to be generated on every read, or
$table->integer('area')->storedAs('height * width');

if you want to store the column in the database if you don't want the generation to be always.
and then add the area column to your model. This way you can use the field in both queries and models.

A: I hope this code will help you
$result = DB::table('shape')
                 ->select(DB::raw('width * height AS area'))
                 ->where('area', '>', 42)
                 ->get();


text:
Q: How to use OBEX/Bluecove with Android  I have an task to share an file over bluetooth by programatically.I tried to use few samples provided from stackoverflow.But it failed to recognize the exact solution.Let me know how to use OBEX api on android.
I tried Bluecove jar implementation with android, I added the jar in build path, when I run the App it shows an error like - BlueCove native library version mismatch can you please provide me necessary solution to fix this problem.
when i use loadlibrary, it usually points that
 javax.bluetooth.BluetoothStateException: BlueCove native library version mismatch.
Help me to fix this issues.
Thanks in advance.

A: A simple approach is to use an existing application to send a file via BT (sharing functionality is one of the architectural goals of Android). Install an app (search for bluetooth in the playstore) and use a method similar to the following one to send your file:
private File exportFile;  // set when creating the file

/**
 * Send the export file via an intent with the send action.
 */
private void doSendFile() {
    final Intent i = new Intent(Intent.ACTION_SEND);
    i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(this.exportFile));
    i.setType("text/*");
    final Intent chooser = Intent.createChooser(i, this.global.getText(R.string.txt_send_chooser_title));  // R.string.... is the label's ID for the chooser headline
    chooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    this.startActivity(chooser);
}


text:
Q: app crashes when changing viewcontroller I have two view controllers that both return to the home VC using
[self dismissModalViewControllerAnimated:NO];

One of them works and triggers it using a storyboard created button, whilst the one that doesn't work triggers it using a programmatically created button.
When the button on the second one is pressed it does move to the home VC, but instantly crashes
Update:
New Output

** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '_questioner_session=BAh7BkkiD3Nlc3Npb25faWQGOgZFRkkiJTYxYWQ0YjBlMTY1MGIwZjZlMDA5NDkxNmI2MzQxZmFhBjsAVA%3D%3D--15054ec7f94935cfc07bad559f1d52cd65ea5e4b: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
  Key path: scoringData
  Observed object:

It seems to crash when it gets to this point

+(void)processScoringData:(NSMutableData*)response
  {
      [DataStore dataStore].scoringData = [[NSMutableDictionary alloc]init];

After adding an exception break point I get this beside the output. Not sure if it helps?
ServerInterface
(Class) [0] = <error: unknown Class>

response = (NS MutableData*)
NSData  NSData
NSObject    NSObject
isa Class   0x3c35b9ac
[0] Class   <error: unknown Class>

A: [self dismissViewControllerAnimated:NO completion:nil]; use instead of your dismiss controller method because your method is deprecated.
Definitely work for You.


text:
Q: Embedding Form Filter on Multiple Fields I'm trying to create a search on two related tables on multiple fields.
I'm embedding the form filters everything renders fine. When I'm trying to validate the form(s), the form fails to execute getName().
I've read some articles about this and one of the tips was to override the addFieldNameColumnQuery() function.
My question is: Is this the only/best way to do it? Should I override a function for every field in the embedded form?


text:
Q: django-tables2: Set template for TemplateColumn at runtime In django-tables2 is it possible to set the template_name for a TemplateColumn inside the Table's constructor? I would like to be able to chose the template at runtime.
From the docs the only way to set the template is like this:
class ExampleTable(tables.Table):
    foo = tables.TemplateColumn('{{ record.bar }}')
    # contents of `myapp/bar_column.html` is `{{ value }}`
    bar = tables.TemplateColumn(template_name='myapp/name2_column.html')

In my app there are different templates for one column depending on the state for the app and I would like to avoid creating a different Table class for each state and instead just swap the template at runtime.

A: You can try to change template at runtime in this way:
e  = ExampleTable( your_query )
e.columns['bar'].column.template_name = 'your_template'

Disclaimer: Not tested. Please, test you it and come back. I will delete answer if don't run.


text:
Q: Visual C++ - qSort with Strings Yes, I want to use the qsort() function with  two strings, most likely those will be tested as character arrays. When I run it,I get an unhandled exception in qsort.c at the line(151):
    if (__COMPARE(context, lo, mid) > 0) {
        swap(lo, mid, width);
    }

This is my code:
#include <iostream>
#include <iomanip>
using namespace std;

struct SaleSlip{
    char name[20];
    int ProdID;
    double value;
};
int compare(void const *a, void const *b);
ostream& operator<<(ostream& out, SaleSlip& sales);

int main(){
    SaleSlip sales[17] = {
        {"Eric",   1, 200000.00},
        {"Sookie", 2,    200.00},
        {"Sookie", 4,    200.50},
        {"Bill",   3,   5000.00},
        {"Bill",   5,   7500.00},
        {"Tara",   4,    350.50},
        {"Eric",   2,    200.00},
        {"Tara",   2,    200.00},
        {"Tara",   4,    350.50},
        {"Bill",   5,   2500.00},
        {"Sookie", 1,  50000.00},
        {"Sookie", 2,    200.00},
        {"Eric",   5,  10000.00},
        {"Tara",   2,    200.00},
        {"Tara",   4,    150.50},
        {"Bill",   5,   1000.00},
        {"Sookie", 4,    400.50}
    };
    cout << "The array before sorting is: " << endl;
    for(int i = 0; i < 17; i++)
        cout << sales[i];
    qsort(sales[0].name, 17, (sizeof(sales)/sizeof(char*)), compare);
    cout << "The array after sorting is: ";

    system("pause");
    return 0;
}

ostream& operator<<(ostream& out, SaleSlip& sales){
    out << setiosflags(ios::left | ios::fixed) << setw(7) << sales.name << setw(3) << sales.ProdID
        << setprecision(2) << sales.value << endl;
    return out;
}

int compare(void const *a, void const *b) {
    return strcmp(*(const char **)a, *(const char **)b);
}

I am testing in compare properly? Am I calling qsort properly?

A: You probably want your compare function to take SaleSlip pointers as the argument.  In the compare function do strcmp(a->name,b->name).  Of course your arguments to qsort will change to become SaleSlip structs.

A: What you are doing wrong is:
I. You pass in 17 as both the element size and the element count to qsort(). That's wrong, the 2nd argument is the number of elements in the array, the 3rd one is the size of one individual element.
II. you want to sort the array, but you don't pass in the address of its first element, but a pointer to the name member of the first element. Take this and the incorrect element size, and from now on, all the pointers qsort() operates on are quite arbitrary, and using them is not any good. What you could do is:
I. Write a proper comparator function and don't try to include nasty tricks:
qsort(sales, sizeof(sales) / sizeof(sales[0]), sizeof(sales[0]), comp);

int comp(const void *a, const void *b)
{
    // the two lines below are the aesthetic reason
    // for NOT using qsort() in C++. The ugly cast is not needed in C.

    const SaleSlip *s1 = static_cast<const SaleSlip *>(a);
    const SaleSlip *s2 = static_cast<const SaleSlip *>(b);

    return strcmp(s1->name, s2->name);
}

II. Or, even better: use std::sort, std::string and define SaleSlip::operator <:
class SaleSlip {
    bool operator <(const SaleSlip &that) {
        return this->name < that.name;
    }
};

std::sort(sales, sales + sizeof(sales) / sizeof(sales[0]));

Bonus: don't use hard-coded sizes and types. 17 is dangerous, sizeof(array) / sizeof(SaleSlip) is better but still not perfect, sizeof(array) / sizeof(array[0]) is entirely safe, no matter what you do with the base type and the element count of the array.

A: Use std::sort : qsort is harder to use in almost every case, and less efficient.
First, write a order function:
    struct SaleSlip{
      char name[20];
      int ProdID;
      double value;
    };
    bool order( SaleSlip const& lhs, SaleSlip const& rhs ) {
      return strncmp(lhs.name, rhs.name, sizeof(lhs.name))<0;
    }
then feed this to std::sort:
std::sort( &sales[0], &sales[sizeof(sales)/sizeof(sales[0])], order );

and your are done.
In C++11, that line is better:
std::sort( std::begin(sales), std::end(sales), order );

You can also replace name with a std::string rather than work with a fixed sized buffer, but I understand there are reasons to work with raw char buffers.  If you do so, simply change order to return lhs.name < rhs.name.
The problems in your original code, above and beyond the choice to use qsort, is that the blocks of memory you are sorting are SaleSlip objects, not char* objects.  First, fix your compare function (and give it a better name):
int compare_pvoid_SaleSlips(void const *a, void const *b) {
  SalesSlip const* lhs = static_cast<SalesSlip const*>(a);
  SalesSlip const* rhs = static_cast<SalesSlip const*>(b);
  return strncmp(lhs->name, rhs->name, sizeof(lhs->name)/sizeof(lhs->name[0]));
}

Next, fix your call to qsort:
qsort(&sales[0], 17, (sizeof(sales)/sizeof(sales[0])), compare_pvoid_SaleSlips);

which should work.  However, following this method will be slower, more error prone, more brittle, and in every way worse in a C++ program than the std::sort solution.

A: Three problems:

*

*The first argument should just be sales - the array you want to sort.

*The size argument should be sizeof(SaleSlip) - the size of each element.

*The comparison is doing something very strange. To get a pointer to the name, you want static_cast<const SaleSlip*>(a)->name (or (const char*)a if you like to live dangerously).

These problems can be avoided by using the C++ std::sort function (and std::string for the string), which is type-safe and (often) more efficient than qsort. Then you simply do
std::sort(std::begin(sales), std::end(sales),
    [](SaleSlip const & a, SaleSlip const & b) {return a.name < b.name;});


text:
Q: How can I display local images if I don't know their location before runtime? var imageSource = require('./images/test.png')
<Image source={imageSource} style={s.userPic} />

That works great, but I need to show local photos just taken with the device (iPad) camera, so I won't know the local file location, stored in "user.imageLoc"...
var imageSource = eval("require('" + user.imageLoc + "')")
<Image source={imageSource} style={s.userPic} />

But that doesn't work. "Unknown module named (insert file location here)"
How can I display local images if I don't know their file name/address before runtime?

A: Pass image source as prop to your component :)
<MyCustomImageComponent imageSource={require(user.imageLoc)} />

A: If you want to access photos from your gallery or taken with the camera, maybe the best approach is to use the CameraRoll API from RN. v
This is the documentation:
https://facebook.github.io/react-native/docs/cameraroll.html
If that doesn't work or it's not what you want, we can try to find other solutions.


text:
Q: MsBuild to build and create a deployment package I was trying to use the following command to build my solution, but that was giving me an error saying MSBuild target package not found

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe"
  "C:\Users\FullPath\SolutoinName.sln" /T:Build;package
  /p:Configuration=DEBUG /p:OutputPath="obj\DEBUG"
  /p:DeployIisAppPath="/bidmc-defaul" /p:VisualStudioVersion=10.0

I have tried MSBuild target package not found but that did not help, then I removed package from target and ran the command and it was successful
Then I ran the following command to create a package zip

"C:\Program Files (x86)\IIS\Microsoft Web Deploy\msdeploy.exe"
  -verb:sync -source:package="C:\Users\Full Path\Website\obj\Debug_PublishedWebsites\defaul_Package\myPackage.zip"
  -dest:auto,computerName=localhost -allowUntrusted=true

Now this says object of type package and path cannot be created, the zip package could not be loaded, could not find part of the path
Update

fix to my first command to create package. I was giving my solution name SolutoinName.sln, I replaced it with my main project in solution myproject.csproj, with corresponding paths. That resolved my first error.

now second error has changed to "the applicatoin pool that you are
  trying to use has the managedRuntimeVersion property set to v4.0 the
  application required 4.5"

How should I address this, just install .NET 4.5 on build machine?

A: It seems you're attempting to build a VS2012.NET 4.5 or higher solution with MSBuild 4.0. That's supported, provided you install the full .NET 4.5 Framework and the required SDK's and targeting packs for VS 2012, VS 2013 and more.
Alternatively, you can upgrade to MSBuild 2013 v12.0 (for VS 2013 solutions support) or MSBuild 2015 v14.0 (VS 2015).

A: You need to change the VisualStudioVersion to 11 on the MSBuild call.
/p:VisualStudioVersion=11.0

A: Use IIS Manager to upgrade the .NET Framework version assigned to your app pool (or change your project properties to downgrade the .NET Framework version your web application targets).


text:
Q: Sublime Text 2 - Focus a column (like in iTerm?) I am using Sublime Text 2. I like to to use the 2 column layout so I can see 2 source files as once. However sometimes I want to expand one column to the full window (Similar to the shift+command+return command in iTerm).
I can use option+command+1 and option+command+2 to toggle between a 2 and 1 column layout but the problem is, when going from 2 to 1 and back to 2 columns, all the files that were previously in the second column are all put into the first column and now the 2nd column is empty.
Is there a plugin (or command I am unaware of) that does this?

A: https://github.com/SublimeText/Origami
This one does it, but I am sure there was something in the default keymap


text:
Q: pip install git+url issue || Google colab enter image description hereI just created a set of functions for retrieving data of API so I shared it on my githhub website.
I tried to install my packages on google colab using pip install git+url but the only a get is the following error:

*

*Exit code 1

note: This error originates from a subprocess, and is likely not a problem with pip.
Preparing metadata (setup.py) ... error
error: metadata-generation-failed
× Encountered error while generating package metadata.
╰─> See above for output.
note: This is an issue with the package mentioned above, not pip.
I'm new at github so i don't know if there is something that I'm missing at setting up my packages.
I would be grateful if someone can help me
I left my git below
https://github.com/maxelOA/py_erpy2set.git

A: There's a syntax error in your setup.py script. You have two ++ at the bottom. Try removing those, should solve this error.
This is why it's helpful to get the full error message (stack trace), when I tried running this on my console I got error message:
    ERROR: Command errored out with exit status 1:
     command: /home/matthias/projects/playground/as_env/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/home/matthias/projects/playground/as_env/src/erpy2set/setup.py'"'"'; __file__='"'"'/home/matthias/projects/playground/as_env/src/erpy2set/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-4we41jtq
         cwd: /home/matthias/projects/playground/as_env/src/erpy2set/
    Complete output (6 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/home/matthias/projects/playground/as_env/src/erpy2set/setup.py", line 17
        ++
          ^
    SyntaxError: invalid syntax
    ----------------------------------------
WARNING: Discarding git+https://github.com/maxelOA/erpy2set#egg=erpy2set. Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
ERROR: Could not find a version that satisfies the requirement erpy2set (unavailable) (from versions: none)
ERROR: No matching distribution found for erpy2set (unavailable)
WARNING: You are using pip version 21.2.3; however, version 23.0.1 is available.
You should consider upgrading via the '/home/matthias/projects/playground/as_env/bin/python -m pip install --upgrade pip' command.

Which then prompted me to look at the setup.py file.
The error message you posted must be just the error from google colab or whatever ide you are using, there must be some way to see the "see the above for output" part to get the more relevant info.


text:
Q: i am getting wrong value in calculating heikin ashi using python code I get a different value for only the Open price while finding out the Heikin Ashi candlestick pattern using Python code. Below is the python function to generate the HA Candlestick.
The open price for 2022-07-11 is as follow :
123.92 - in heikin ashi value. (source data from broker python api)
124.25 - in fyers web chart.
123.92 - in google finance
I found there is a difference in the Open price, but the rest of the columns look fine. Could anyone please suggest if the python code is wrong?
def heikin_ashi(df):
df = df
print(df)
# to find Hikin Ashi pattern.
df['ha_open'] = ((df['open'] + df['close'])).shift(1) / 2
df['ha_close'] = (df['open'] + df['high'] + df['low'] + df['close']) / 4
df['ha_high'] = df['high']
df['ha_low'] = df['low']
# to create xlsx file with OHLC data.
# df.to_excel(report_dir + "OHLC_" + report_name, sheet_name='candle')
df = df.round({'ha_open': 2, 'ha_high': 2, 'ha_low': 2, 'ha_close': 2})

df = df[['timestamp','open','high','low','close','volume','ha_open','ha_high','ha_low','ha_close']]
return df

This takes a pandas dataframe as a input paramater and generate Heikin Ashi OHLC value. Example for dataframe output.
enter image description here


text:
Q: How to determine angular velocity from a video? Consider a video of a rotating wheel that has been read in as a grayscale. Within this video I have marked a Region of Interest:

Within the ROI I have taken a threshold on the pixel intensities: Every pixel with an intensity less than 50 is floored to 0 and every pixel with an intensity greater than 50 is scaled to 255.
From this information I have created a .txt-file with two columns: One contains a timestamp and the other contains the mean of the pixel-intensities within the ROI: here
It should be possible to determine the angular velocity of the wheel from this information. But I am not sure as on how to do this. Does anyone have an idea?
Here is what I have tried so far:
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

VideoData = pd.read_csv('myData.txt', sep='\t')
VideoPixelMean = VideoData.iloc[:,1].values.tolist()
VideoTimestamp = VideoData.iloc[:,0].values.tolist()

SpokeList = []
for idx,el in enumerate(VideoPixelMean):
    if el >= 150:
        SpokeList.append(idx)
VideoVelocity=[]
VelocityTime = [0]
for idx,el in enumerate(SpokeList):
    if idx == 0:
        VideoVelocity.append(0)
    else:
        framesPassed = SpokeList[idx] - SpokeList[idx-1]
        if framesPassed > 2:
            velocity = 2*np.pi/360 * 72 * 50 * 30/framesPassed #each wheel has 5 spokes (the angle between two spokes is 72°) and a radius of 50mm; fps = 30
        else:
            velocity = 0
        VideoVelocity.append(velocity)
        velocityTime = VideoTimestamp[el]
        VelocityTime.append(velocityTime)

I am pretty sure the result is not correct though.

A: Interesting problem! Take my word with a grain of salt.
For our stationary ROI, the velocity can be determined by:
Measuring the time taken to get to the next spoke. To do this you can measure the first occurrence of a light pixel and the next occurrence of a light pixel, after encountering a dark pixel.
D-L-L-L-L-D-D-D.....D-L-L-L-L
  ^                   ^

When you identify these points, get the difference in time in seconds (t) to get the time passed.
Distance as you have calculated:
2π(r)(θ/360)

You can get the perpendicular velocity by:
v_perp = 2π(r)(θ/360) / t

Now you can divide it by r to get angular velocity:
v_angular = 2πθ/360t

spoke_start_time, spoke_end_time = None, None

for idx, pixel in enumerate(VideoPixelMean):
     if pixel > 150 and VideoPixelMean[idx-1] < 150:
            if not spoke_start_time:
                spoke_start_time = VideoTimestamp[idx]
            else:
                spoke_end_time = VideoTimestamp[idx]
                break
     else:
        last_pixel = 0

t = spoke_end_time - spoke_start_time # This should be in seconds

THETA = 72
v_angular = (2 * np.pi * THETA) / (360 * t)


text:
Q: How to change programmatically Quick Action image/colour from inside an AppleScript I am working on a Quick Action in Automator to mute/unmute a mic on a MacBook. The quick action is then assigned to Apple Touch Bar so the mic can be easily toggled from anywhere.

What I am having problem with is to programatically change the button colour. When the mic is disabled I want to change the colour to black. While when the mic in enabled I want the colour of the button to be red.

The colour of the button is stored in the action 'plist' file. My idea was to edit the file from inside the script. However editing the file does not take effect. When I change the colour of the button from Automator, it re-creates the entire action, what refreshes the button.
The other option I am considering is to have 2 buttons - one for enable the mic (black) the other to disable it (red). The script would have to assign/deassign the right action button.


text:
Q: excel vba userform afterupdate fires when text box cleared I have a simple userform with 5 text boxes. I can process the data using an "ADD" command button but, given that there could be 100 entries in one session it would be a bit quicker and easier if the procedure is fired with a sub [last textbox]_afterupdate().
Problem: when clearing the textboxes, the last one fires the procedure again. Here is the code:
Private Sub txtagainst2_afterupdate()

Set rTeam = [A4:A50].Find(txtTeam, lookat:=xlWhole)
Set rTeam = rTeam.Resize(1, 15)
With rTeam
    code to do stuff with the textbox values
End With
txtTeam = ""
txtFor1 = ""
txtAgainst1 = ""
txtFor2 = ""
txtAgainst2 = ""
txtTeam.SetFocus

End Sub

I've tried a few possibilities, but cannot crack it.
Any advice or solution would be truly appreciated.
Thank you, Peter

A: To prevent the code from triggering itself (or any other code), you need to temporarily disable events around the line(s) of code that trigger events to run:
Instead of just:
txtAgainst2 = ""

Use:
Application.EnableEvents = False
txtAgainst2 = ""
Application.EnableEvents = True

This will prevent the "AfterUpdate" event being triggered when the textbox is updated.

A: Michael. Thank you
Your solution was one I did try before posting, but, for some reason, the step-through returns to the beginning of the procedure and runs it a second time (as before). I tried it again just now with the same result. It does not update the second time because the txtAgainst2 is empty.
But...tried an if statement at the start of the procedure (below). Had to set all but the textboxes tabstop to =false because would not setfocus to textbox1. This seems to work. Still not sure of the rationale.
private sub txtagainst2_afterupdate()
If txtAgainst2 = "" Then GoTo handler:

Set rTeam = [A4:A50].Find(txtTeam, lookat:=xlWhole)
Set rTeam = rTeam.Resize(1, 15)
With rTeam
do stuff
End With
txtTeam = ""
txtFor1 = ""
txtAgainst1 = ""
txtFor2 = ""
txtAgainst2 = ""
txtTeam.SetFocus
Exit Sub

handler:
    txtTeam.SetFocus
    Exit Sub
End Sub
Thank you again for your help.


text:
Q: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference For some reason in my application, when I try to call openFileOutput(), it throws a NullPointerException and I am not sure what is causing it. I have made sure that all the parameters of the method are not null, but for some reason my app still throws a NullPointerException. Any suggestions?

My MainActivity class
    public class MainActivity extends AppCompatActivity {

    private static final String TAG_NEWS_FRAGMENT = "news_fragment";
    private static final String TAG_SPORTS_FRAGMENT = "sports_fragment";

    Context context = MainActivity.this;
    private final String[] CATEGORY_NAMES = {"news", "sports"};
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ProgressBar mProgressBar;
    private CoordinatorLayout coordinatorLayout;
    private PUNewsFragment mPUNewsFragement;
    private PUSportsFragment mPUSportsFragement;
    private List<NewspaperMetaObject> newsItems;
    private List<List<NewspaperMetaObject>> categories;
    private boolean doesFileExist;
    private boolean isWebsiteOnline;
    private FragmentManager fm;
    private ProgressBar pb;
    private boolean doRefresh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        doRefresh = false;

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        Toast.makeText(this, "Loading...", Toast.LENGTH_SHORT).show();
        pb = (ProgressBar) findViewById(R.id.progressBar);

        try {
            isWebsiteOnline = new checkWebsiteStatus().execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        doesFileExist = new File(context.getFilesDir() + "/news").exists();

        new RetrieveNewspaperMeta().execute(CATEGORY_NAMES);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new PUNewsFragment(), "News");
        adapter.addFragment(new PUSportsFragment(), "Sports");

        viewPager.setAdapter(adapter);
    }

    public void refresh(String[] str) {
        doRefresh = true;
        new RetrieveNewspaperMeta().execute(str);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

    private class RetrieveNewspaperMeta extends AsyncTask<String, Integer, Wrapper> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Wrapper doInBackground(String... params) {

            Document doc = null;

            categories = new ArrayList<>();

            if (!doesFileExist && doRefresh) {
                for (int i = 0; i < params.length; i++) {
                    newsItems = new ArrayList<>();
                    try {
                        Log.i("DEBUG", params[i]);
                        URL url = new URL("http://www.dailyprincetonian.com/category/" + params[i] + "/");
                        doc = Jsoup.connect(url.toString()).get();
                        Elements content = doc.select("article.tease-post");
                        System.out.println();
                        System.out.println(content);
                        int count = 0;
                        NewspaperMetaObject parser;
                        while (!content.eq(count).isEmpty()) {
                            parser = new NewspaperMetaObject(content.eq(count));
                            newsItems.add(parser);
                            count++;
                        }
                        categories.add(newsItems);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    for (NewspaperMetaObject o : newsItems) {
                        try {
                            Elements text = Jsoup.connect(o.getDoc().select("h3.h2 a").attr("href")).get().select("section.article-content").select("div.article-bd").select("p");
                            o.setArticleText(text.toString());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                return new Wrapper(categories, params);
            } else {
                for (int i = 0; i < params.length; i++) {
                    newsItems = new ArrayList<>();
                    try {
                        FileInputStream fis = openFileInput(params[i]);
                        ObjectInputStream is = new ObjectInputStream(fis);
                        newsItems = (List<NewspaperMetaObject>) is.readObject();
                        is.close();
                        fis.close();
                        categories.add(newsItems);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (StreamCorruptedException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                return new Wrapper(categories, params);
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
        }

        @Override
        protected void onPostExecute(final Wrapper wrapper) {
            super.onPostExecute(wrapper);
            android.os.Handler mHandler = new android.os.Handler();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!doRefresh) {
                        PUNewsFragment.newsItems = categories.get(0);
                        PUSportsFragment.newsItems = categories.get(1);

                        setupViewPager(viewPager);

                        tabLayout.setupWithViewPager(viewPager);

                        fm = getSupportFragmentManager();
                        mPUNewsFragement = (PUNewsFragment) fm.findFragmentByTag(TAG_NEWS_FRAGMENT);
                        mPUSportsFragement = (PUSportsFragment) fm.findFragmentByTag(TAG_SPORTS_FRAGMENT);

                        if (mPUNewsFragement == null && mPUSportsFragement == null) {
                            mPUNewsFragement = new PUNewsFragment();

                            mPUSportsFragement = new PUSportsFragment();

                            fm.beginTransaction().add(mPUNewsFragement, TAG_NEWS_FRAGMENT).commit();
                            fm.beginTransaction().add(mPUSportsFragement, TAG_SPORTS_FRAGMENT).commit();
                        }
                    } else {
                        for (int i = 0; i < wrapper.params.length; i++) {
                            switch (wrapper.params[i]) {
                                case "news":
                                    PUNewsFragment.newsItems = categories.get(0);
                                    PUNewsFragment.adapter.notifyDataSetChanged();
                                    break;
                                case "sports":
                                    PUSportsFragment.newsItems = categories.get(1);
                                    PUSportsFragment.adapter.notifyDataSetChanged();
                                    break;
                            }
                        }
                    }

                    if (pb != null) {
                        pb.setVisibility(View.GONE);
                    }
                    Log.i("DEBUG", "DONE!");

                    if (doRefresh) {
                        context = MainActivity.this;
                        for (int i = 0; i < wrapper.params.length; i++) {
                            try {
                                FileOutputStream fos = context.openFileOutput(wrapper.params[i], 0);
                                ObjectOutputStream os = new ObjectOutputStream(fos);
                                os.writeObject(newsItems);
                                os.close();
                                fos.close();
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    doRefresh = false;
                }
            }, 1000);

        }
    }

    private class checkWebsiteStatus extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                URL url = new URL("http://www.dailyprincetonian.com/");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.connect();
                urlConnection.disconnect();
                return true;
            } catch (IOException e) {
            }
            return false;
        }
    }

    private class Wrapper {
        List<List<NewspaperMetaObject>> categories;
        String[] params;

        public Wrapper(List<List<NewspaperMetaObject>> categories, String[] params){
            this.categories = categories;
            this.params = params;
        }
    }
}

Snippet of where the Exception is being thrown
            if (doRefresh) {
                context = MainActivity.this;
                for (int i = 0; i < wrapper.params.length; i++) {
                    try {
                        FileOutputStream fos = context.openFileOutput(wrapper.params[i], 0);
                        ObjectOutputStream os = new ObjectOutputStream(fos);
                        os.writeObject(newsItems);
                        //os.flush();
                        os.close();
                        fos.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

A: It looks like the wrapper variable is declared (therefore you can do a
for (int i = 0; i < wrapper.params.length; i++)

without any problem) but all items in the array may be null referenced, wich is the cause of the NPE.


text:
Q: How to open a link as Tab in same webpage I have seen many web applications which contains single web window with many links. On clicking the links concerned form gets open as new tab in the same web page of the application. So my concern is how to get that?
How to get the link open as new tab and later can be closed in the same window?

A: This can be done using target option
<a href="http://www.facebook.com" target="_blank">Visit facebook </a>

There are many option for this.

*

*_blank Opens the linked document in a new window or tab.

*_self Opens the linked document in the same frame as it was clicked (this is default).

*_parent Opens the linked document in the parent frame.

*_top Opens the linked document in the full body of the window.

*framename Opens the linked document in a named frame.

A: Here's one example that may help you get on your way to add dynamic tabs:
http://www.jeasyui.com/tutorial/layout/tabs2.php
I'm sure there are others.


text:
Q: Filter to date range AFTER grouping by most recent occurrence - SQL I'm trying to write some SQL that will pull out the most recent login of a user on our site, and then filter that to be in the date range of between 60-90 days ago. Accounts are made inactive after 90 days so we send a warning email (just to add flavour to this query).
I can do both halves of this, getting most recent and getting a range, but am having trouble putting them together.
The query pulls from two tables, as the table with log in dates only has a user ID, so I inner join the table that has user ID and username (email address), tables below and each has more columns than listed.
Table 1 = "time.log"

log in date
user id
application

25/02/2022
123
website

Table 2 = "users.id"

user id
username
name

123
john@smith.com
John Smith

Current code
SELECT MAX(t.log_time) AS 'Date',
u.username AS 'Email'

FROM time.log t
    INNER JOIN users.id u ON t.user_id = u.user_id

WHERE t.log_time BETWEEN Convert(DATE,GETDATE()-90) AND Convert(DATE,GETDATE()-60)

GROUP BY u.username

The result I am getting is the top log in date in that range, rather than it being the range of users who last logged in during that period. That makes sense when you read the query through but I can't seem to filter it after the GROUP BY has occurred.
I am using SQL Server Management Studio incase that is relevant - if you can't tell I am a SQL newbie.
I also tried using a second SELECT sequence but I can't get the query to execute at all (it seems to want something after the bracket but I don't know what.
SELECT MAX(t.log_time) AS 'Date',
u.username AS 'Email'

FROM time.log t
    INNER JOIN users.id u ON t.user_id = u.user_id

INNER JOIN(
    SELECT MAX(t2.log_time)
    FROM time.log t2
    INNER JOIN users.id u2 ON t2.user_id = u2.user_id
    GROUP BY u2.username) ON

    t.user_id = t2.user_id AND t.log_time = t2.log_time

Help very much appreciated.

A: Run this in SSMS and apply to your scenario
declare @t table (the_name varchar, the_date date)
insert into @t
select 'a', '01-jan-2022' union
select 'a', '02-jan-2022' union
select 'b', '03-jan-2022' union
select 'b', '04-jan-2022'

select * from @t

select *, row_number() over(partition by the_name order by the_date desc) as the_number
from @t

select * from (
    select *, row_number() over(partition by the_name order by the_date desc) as the_number
    from @t
) z
where the_number = 1
and the_date between '01-jan-2022' and '02-jan-2022'

A: You can simply add having clause to check if the maximum date is contained in the desired range.
Create Schema [time]
Create Table [time].[log] (log_time Date, [user_id] Int, [application] VarChar(100))

Create Schema [users]
Create Table [users].[id] ([user_id] Int, username VarChar(100), name VarChar(100))

Insert Into [users].[id] ([user_id], username, name)
Values (123, 'john@smith.com', 'John Smith'),
       (124, 'mary@cole.com', 'Mary Cole')

Insert Into [time].[log] (log_time, [user_id], [application])
Values ('20211201', 123, 'web'),
       ('20211210', 123, 'web'),
       ('20211215', 123, 'web'),
       ('20220201', 124, 'web')

Declare @Date_From Date = Convert(DATE,GETDATE()-90)
Declare @Date_To Date = Convert(DATE,GETDATE()-60)

Select Max(t.log_time) As 'Date', Max(u.name) As 'Name', Max(u.username) As 'Email'
From [time].[log] t Inner Join users.id u On (t.[user_id] = u.[user_id])
Group by u.[user_id]
Having Max(t.log_time) Between @Date_From And @Date_To

dbfiddle

Date
Name
Email

2021-12-15
John Smith
john@smith.com


text:
Q: Python: How to terminate a blocking thread
Possible Duplicate:
Is there any way to kill a Thread in Python?

So this question is a follow up to a solution posted previously.  Basically it deals with programatically terminating a thread:  http://sebulba.wikispaces.com/recipe+thread2
However it doesnt work... and I was wondering if someone can explain how one could terminate a thread that is blocking? My only guess is the fact that I am not providing the right thread id, but I did some testing and am pretty sure I can just use iden
If it is the thread ID, how can I go about getting the correct Thread ID?
Test Code:
class BlockingTestThread(Thread):

    def __init__(self):
        self._running_flag = False
        Thread.__init__(self, target=self.test_method)

    def test_method(self):
        try:
            while(not self.stopped()):
                self._running_flag = True
                time.sleep(100)
        finally:
                self._running_flag = False

def _async_raise(tid, exctype):
    '''Raises an exception in the threads with id tid'''
    if not inspect.isclass(exctype):
        raise TypeError("Only types can be raised (not instances)")

    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
    time.sleep(0.1)

if __name__ == "__main__":
    thread = BlockingTestThread()
    thread.start()

    _async_raise(thread.ident, SystemExit)
    print "Joining thread"
    thread.join()
    print "Done Joining thread"
    #will never get here!

A: Here is a better way to do it, use the "wait" command on the event, asssuming you want to use sleep.
class BlockingTestThread(Thread):
    def __init__(self):
        self._running_flag = False
        self.stop  = threading.Event()
        Thread.__init__(self, target=self.test_method)

    def test_method(self):
        try:
            while(not self.stop.wait(1)):
                self._running_flag = True
                print 'Start wait'
                self.stop.wait(100)
                print 'Done waiting'
        finally:
                self._running_flag = False

    def terminate(self):
         self.stop.set()

if __name__ == "__main__":
    thread = BlockingTestThread()
    thread.start()

    time.sleep(2)
    print 'Time sleep 2'
    thread.terminate()
    print "Joining thread"
    thread.join()
    print "Done Joining thread"

Obviously you are going to need to wrap your blocking thread in something that uses the pattern above, but if you can't the other option is to cause your process to throw an exception, in our case we basically kill the underlying connection, which causes an exception, and when that exception happens if the stopped flag is set, we ignore it.

A: You are right about ident, from the docs, ident variable doesn't map to thread id, it's just a reference-

thread.get_ident()
Return the 'thread identifier' of the current thread. This is a nonzero integer. Its value has no direct meaning; it is intended as a magic cookie to be used e.g. to index a dictionary of thread-specific data. Thread identifiers may be recycled when a thread exits and another thread is created.

See http://bytes.com/topic/python/answers/45247-terminating-thread-parent re: killling, not sure if it's exactly what you are looking for unfortunately.


text:
Q: Token can't store in .NET Core I have a project using .NET core version 3.1 and I'm using token for logging in. Everything works perfectly when testing with Postman, it created token and I can use it to access the Home page.
The problem is, when I started testing on client side, it doesn't work. I debugged and saw after logging in, the token is generated but I can't access the HomeController because of [Authorize] attribute.
This is my code to generate token:
public async Task<HttpResponse<LoginResult>> GetTokenAsync(LoginRequest loginInfo)
{
    var audience = await _audiences.FindAsync(a => a.Id == loginInfo.ClientId);
    string message = string.Empty;

    if (audience != null)
    {
        bool audienceIsValid = _jwtProvider.ValidateAudience(audience.Issuer
                    , audience.SecretKey
                    , ref message);

        if (audienceIsValid)
            return await GenerateToken(loginInfo);
        else
            message = ErrorMessages.Login_AudienceInvalid;
    }
    else
        message = string.Format(ErrorMessages.Login_Not_Permitted, "Your client Id");
    return HttpResponse<LoginResult>.Error(message, HttpStatusCode.BadRequest);
}

I guess that token couldn't be stored correctly.
What am I missing?
UPDATE
This is my code in login
[HttpPost]
[Route("login")]
[AllowAnonymous]
public async Task<ActionResult> Login([FromForm]LoginRequest model)
{
      model.ClientId = 1;
      var response = await _services.GetTokenAsync(model);
      if (response.StatusCode == 200)
      {
           return RedirectToAction("Index", "Home");
      }
      return RedirectToAction("Login");
}

And this is what I'm trying to access
[HttpGet]
[Route("index")]
[Authorize]
public IActionResult Index()
{
     return View();
}

A: You need to create a custom policy to specify in the Authorize attribute that is configured to use a custom requirement handler
First you lay out the requirement of the custom policy via a class that inherits IAuthorizationRequirement
public class TokenRequirement : IAuthorizationRequirement
{
}

This is where you would optionally accept parameters if you need them. But normally you pass a token in the header of a request which your custom policy's requirement handler would have access to without the need for explicit parameters.
Your requirement's requirement handler to be used by your custom policy would look something like this
public class TokenHandler : AuthorizationHandler<TokenRequirement>
{
    //Some kind of token validator logic injected into your handler via DI
    private readonly TokenValidator _tokenValidator;

    //The http context of this request session also injected via DI
    private readonly IHttpContextAccessor _httpCtx;

    //The name of the header your token can be found under on a Http Request
    private const string tokenHeaderKey = "authToken";

    //Constructor using DI to get a instance of a TokenValidator class you would
    //have written yourself, and the httpContext
    public TokenHandler(TokenValidator tokenValidator, IHttpContextAccessor httpCtx)
    {
        _tokenValidator = tokenValidator;
        _httpCtx = httpCtx;
    }

    //Overriden implementation of base class AuthorizationHandler's HandleRequirementAsync method
    //This is where you check your token.
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context
        ,TokenRequirement requirement)
    {
        if (context.Resource is Endpoint endpoint)
        {
            HttpRequest httpReqCtx = _httpCtx.HttpContext.Request;
            string token =
                httpReqCtx.Headers.TryGetValue(tokenHeaderKey, out StringValues tokenVal)
                    ? tokenVal.FirstOrDefault()
                    : null;

            if (string.IsNullOrWhitespace(token))
            {
                context.Fail();
            }
            else
            {
                bool tokenIsValid = await _tokenValidator.ValidToken(token);
                if(tokenIsValid)
                    context.Succeed(requirement);
                else
                    context.Fail();
            }
        }
        return Task.CompletedTask;
    }
}

You'd register your custom requirement handler on a custom policy name in Startup.cs like so
//This is a framework extension method under Microsoft.Extensions.DependencyInjection
services.AddHttpContextAccessor();

//Your custom handler
services.AddSingleton<IAuthorizationHandler, TokenHandler>();

//Your custom policy
services.AddAuthorization(options =>
{
    options.AddPolicy(
        //Your custom policy's name, can be whatever you want
        "myCustomTokenCheckerPolicy",
        //The requirement your policy is going to check
        //Which will be handled by the req handler added above
        policy => policy.Requirements.Add(new TokenRequirement())
    );
});

The impl on the attribute would look like this
[HttpGet]
[Route("index")]
[Authorize(Policy = "myCustomTokenCheckerPolicy")]
public IActionResult Index()
{
    return View();
}


text:
Q: Python Jira: Get version release date by version name I've below code to read fix version name:
from jira import JIRA

jira_options = {'server': 'URL'}
jira = JIRA(basic_auth=('username', 'pwd'), options = {'server': 'username'})
fix_version = getparsedstring(issue.fields.fixVersions) #since fix Versions is not readable version name, using getparsedstring custom function to get readable string

Objective is  to get release date of the version from issue, as I will be reading all issues of project through iterations.
As per answer given in this question, below would retrieve release date:
i = jira.version(v.id, expand="ReleaseDate")
i.releaseDate

How do I get release date using issue details through JIRA library?
Note: I do not want to read it through REST API
Thanks in advance!

A: Getting Release Date information directly from Issue
issue = jira.issue('PRJ-1234')

# iterate through all fixVersions of the current issue
for fixVersion in issue.fields.fixVersions:
    # print fixVersion Name and respective Release Date
    print(f'{fixVersion.name} has the release date: {fixVersion.releaseDate}')

Getting Release Date information from mapping table in a dictionary
Another option is to create a release map:
# create dictionary with release name as key and release date as value
def createReleaseVersionMap(jira, project):
    versions = jira.project_versions(project)

    # Make a map from version name -> version release date
    for version in versions:
        try:
            prjVersionList[version.name] = version.releaseDate

        # if no release date is set for this version,
        # do something else, e.g., use the name as value instead of the date
        except AttributeError:
            prjVersionList[version.name] = version.name

    return prjVersionList

And then just use the dictionary in your code to retrieve the respective release dates:
my_release_map = createReleaseVersionMap(jira, 'PRJ')
release_date_I_need = my_release_map['Release Name']


text:
Q: Problems with Sticky Footer I've been trying various techniques to implement Ryan Fait's Sticky Footer technique and none seem to work. My footer content always overlaps my main content when the browser is vertically challenged. It could be because I have many fixed positioned DIVs nested within the footer. When I wrap these DIVs around a parent DIV (#footer), this parent DIV doesn't seem to even appear, nor can I apply styles to it to control its position (and the content within).
HTML:

 Juicy stuff goes here

Contains other Text

CSS:
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -240px;
}
.footer, .push {
    height: 240px;
}
#print_blank {
    padding-top: 0px;
    bottom: 160px;
    position: fixed;
    z-index: 11000;
    width: 100% !important;
    text-align: center;
    min-width: 980px;
}
#logo {
    width: 180px;
    padding-top: 5px;
    bottom: 86px;
    position: fixed;
    z-index: 9999999;
    left: 45px;
}
#nav_bar {
    padding-top: 0px;
    bottom: 77px;
    position: fixed;
    z-index: 99999;
    width: 100% !important;
    text-align: center;
    min-width: 980px;
}
#footerarea {
    bottom: 0px;
    position: fixed;
    width: 100%;
    padding-top: 20px;
    background-color: #F16924;
    height: auto;
    text-align: justify;
    min-width: 960px;
    z-index: 999999;
}

Thanks!

A: This is a better way to do it:
<!DOCTYPE html>

<meta charset="utf-8">

Juicy stuff goes here

The limitation of sticky footers is that the footer must stay at a fixed height. But the elements you have in there shouldn't affect the layout as long as you are careful.
EDIT: Here's a revised template with the footer elements included:
<!DOCTYPE html>

<meta charset="utf-8">

Juicy stuff goes here

Contains other Text


text:
Q: Compute the integral $ \int_{Re(s)=2}\frac{x^{-s}}{s^3}ds\quad\text{for real}\ x>0. $
Use the residue theorem to compute the integral
  $$ \int_{Re(s)=2}\frac{x^{-s}}{s^3}ds\quad\text{for real}\ x>0, $$
  where the contour is oriented upwards. (Hint: treat the cases of $ x<1 $ and $ x\ge 1 $ separately.)

My Attempt:
Draw the semicircle $ \Gamma: 2+R\exp(i\theta), \theta\in[\frac \pi 2, \frac {3\pi}2], R>2 $.
Then $$\begin{align} \int_{\Gamma}\frac{x^{-s}}{s^3}ds &=\int\limits_{\substack{Re(s)=2\\Im(s)=-R}}^{\substack{Re(s)=2\\Im(s)=R}}\frac{x^{-s}}{s^3}ds+\int_{\frac \pi2}^{\frac {3\pi}2}\frac{x^{-2-R\exp(i\theta)}}{(2+R\exp(i\theta))^3}R\exp(i\theta)id\theta.
 \end{align}
 $$
Now let $ R\to\infty $ and by the standard trick we know that the second term on the right tends to zero and the first term on the right is $ \int_{Re(s)=2}\frac{x^{-s}}{s^3}ds\quad\text{for real}\ x>0. $ By the residue theorem,
$$ \begin{align} \int_{\Gamma}\frac{x^{-s}}{s^3}ds &=2\pi i Res(\frac{x^{-s}}{s^3}, 0)\\
&=2\pi i\frac{\ln^2 x}{2}\\
&=\pi i\ln^2 x .\end{align}$$
Therefore, $$ \int_{Re(s)=2}\frac{x^{-s}}{s^3}ds=\pi i\ln^2 x\quad\text{for real}\ x>0. $$

Am I right? I am confused that the hint says that we should treat the cases of $ x<1 $ and $ x\ge 1 $ separately, but I didn't use this fact, why?

A: The half-plane where $x^{-s}$ decays depends on the sign of $\log x$.

*

*For $x \in (0,1)$ then $$\int_{\Re(s)=2} s^{-3}x^{-s}ds = \lim_{R \to \infty} \int_{\partial ([-R,2] +i[-R,R])} s^{-3}x^{-s}ds =2i\pi Res(s^{-3}x^{-s},s=0) = i\pi \log^2 x$$

*For $x \ge 1$ then $$\int_{\Re(s)=2} s^{-3}x^{-s}ds = -\lim_{R \to \infty} \int_{\partial ([2,R] +i[-R,R])} s^{-3}x^{-s}ds =0$$

A: Let $I(x)$ be given by the integral
$$\begin{align}
I(x)&=\int_{\text{Re}(s)=2}\frac{x^{-s}}{s^3}\,ds\tag1
\end{align}$$
For $0<x<1$, $\log(x)<1$ and we evaluate the integral of $\frac{x^{-s}}{s^3}$ over the closed contour, $C_R$,  comprised of $(i)$ the straight line segment from $2-iR$ to $2+iR$ and $(ii)$ the circular arc of radius $\sqrt{R^2+4}$ starting from $2+iR$ traversed counterclockwise and ending at $2-iR$.  Proceeding, we have
$$\begin{align}
\oint_{C_R}\frac{x^{-s}}{s^3}\,ds&=\int_{2-iR}^{2+iR}\frac{x^{-s}}{s^3}\,ds +\int_{\arctan(R/2)}^{3\pi/2+\arctan(2/R)}\frac{x^{-\sqrt{R^2+4}e^{i\theta}}}{(\sqrt{R^2+4}e^{i\theta})^3}\,i\sqrt{R^2+4}e^{i\theta}\,d\theta\tag2\\\\
&=2\pi i \text{Res}\left(\frac{x^{-s}}{s^3},s=0\right)\\\\
&=(2\pi i )\frac1{2}\left.\frac{d^2}{ds^2}\left(s^3\,\frac{x^{-s}}{s^3}\right)\right|_{s=0}\\\\
&=i\pi\log^2(x)
\end{align}$$
Letting $R\to\infty$, the second integral on the right-hand side of $(2)$ approaches $0$ and we find for $0<x<1$
$$I(x)=i\pi\log^2(x)$$
Similarly, for $x>1$, we close the contour in the right-half plane.  Inasmuch as no poles are enclosed, we find $I(x)=0$ for $x>1$.
Putting it together reveals
$$I(x)=\begin{cases}i\pi\log^2(x)&,0<x\le 1\\\\0&, x>1\end{cases}$$

A: Deleted comment as was unclear, so I will make it an answer; the main issue is that for $x>1$, the exponential term on the circular integral is high since $\cos(\theta) \leq 0$ on your domain, so the integral doesn't go to zero and the result is valid only for $x \leq 1$. For $x>1$ we can use the circular domain to the right so $-\frac{\pi}{2} \leq \theta \leq \frac{\pi}{2}$ and same argument works but no residue, so answer zero, or just move the vertical $s$ line to the right towards $\infty$ and use rectangles and no residue again to get zero this way


text:
Q: Bot is not waiting for the message I'm trying to make the bot wait for a specific message(from a specific author and some specific things) But the bot is just waiting for any message and it makes the command.
Here's the function:
async def check(message):
    if type == "netflix":
      c.execute("SELECT price FROM netflix")
      neprice = c.fetchall()
      netprice= neprice[0][0]
      netfprice = netprice*amount
      nettax = await tax(args=netfprice)
      try:
        return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content
      except IndexError:
        return False

Here's where I call the function:
      await bot.wait_for('message', check=check, timeout=60)

Here's the full command:
@bot.slash_command()
@discord.ext.commands.cooldown(1,60, discord.ext.commands.BucketType.user)
async def buy(message, type: str, amount:Optional[int]):
  if amount == None:
    amount = 1
  if amount < 0:
    await message.respond("You cannot buy negative amount of accounts")
  member = message.author
  con = sqlite3.connect("db.sqlite")
  c = con.cursor()
  async def check(message):
    if type == "netflix":
      c.execute("SELECT price FROM netflix")
      neprice = c.fetchall()
      netprice= neprice[0][0]
      netfprice = netprice*amount
      nettax = await tax(args=netfprice)
      try:
        return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content
      except IndexError:
        return False
    elif type == "spotify" or "crunchyroll":
      c.execute("SELECT price FROM spotify")
      spotiprice = c.fetchall()
      spotprice = spotiprice[0][0]
      newspot = spotprice*amount
      spotytax = await tax(args=newspot)
      print(spotiprice[0][0])
      try:
        return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(newspot + spotytax) in message.content
      except IndexError:
        return False
if type == "netflix":
    c.execute('SELECT *, COUNT(*) AS "count" FROM netflix GROUP BY price')
    netamount= c.fetchall()
    print(netamount[1])
    if netamount[0][3] < amount:
      await message.respond(f"We do not have this amount of accounts in the stock")
    else:
      c.execute("SELECT price FROM netflix ")
      netfprice = c.fetchall()
      netprice = netfprice[0][0]
      newnet = netprice*amount
      withtax = await tax(args=newnet)
      embed = discord.Embed(title="transfer",description=f"Please transfer :{newnet + withtax}")
      embed.add_field(name=f"c <@994347081294684240> {newnet + withtax}",value="**Copy paste the message for no error**")
      embed.set_footer(text=f"Sidtho Host. | Requested by - {message.author}")
      print("Sent embed, Waiting for receiving the credits")
      await message.respond(embed=embed)
      await bot.wait_for('message', check=check, timeout=60)
      c.execute("SELECT email, password FROM netflix")
      netres = c.fetchmany(size=amount)
      # print(netres)
      embed = discord.Embed(title=f"حساب {type}", description="")
      embed.add_field(name="Sidtho Host.",value=" ",inline=False)
      for thisamount in netres:
        try:
          email = thisamount[0]
          password= thisamount[1]
          embed.add_field(name=f"Email: {email}", value=f"Password: {password}", inline=False)
          # print(f"The email is {email} \n The password is {password}
        except TypeError as err:
          print(f"Gave A TypeError. Where {err} ")
      await member.send(embed=embed)
      c.execute("DELETE FROM netflix WHERE email=? AND password=?",(email, password))

There is no traceback So no error.
Please note that the check function is a Function, not a command.
and the await bot.wait_for is on a command.
Please note too that type is a value that the user will give to the bot, and its not the python built.

A: In your code, you wrote await message.respond(...).
There isn't a respond() function in both discord.py and pycord, as far as I know. Try changing it to reply(...) and see if it works.

A: async def buy(message, type: str, amount:Optional[int]):
      #type here the stuff that u want make before the check
      def check(m):
                return m.mentions[0].id == 994347081294684240 and m.author.id == 282859044593598464 and int(nettax + netfprice) in m.content
            try:
                response = await client.wait_for('message', check=check, timeout=30.0)
            except:
                #here u can send a message when the time is done
                message.send("timeout")
                return

so yeah it should look like this u take the response and run any checks on or save to db.


text:
Q: Running play Framework app as a service with YAJSW I'm trying to run a play framework app as a service with the YAJSW service wrapper as descriped here.
Every thing works fine until I start the service over "startService.bat". There is no problem if I run the "runConsole.bat".
It also doesn't start if I use the taskmanager, but it is installed.
I have no clue what is wrong. I hope someone can help me find the problem.
startService.bat output
...
C:\my_app\yajsw-stable-11.11\bat>"java" -Xmx30m -Djna_tmpdir="C:\my_app\yajsw-stable-11.11\bat\/../tmp" -Djava.net.preferIPv4Stack=true -jar "C:\my_app\yajsw-stable-11.11\bat\/../wrapper.jar" -t "C:\my_app\yajsw-stable-11.11\bat\/../conf/wrapper.conf"
YAJSW: yajsw-stable-11.11
OS   : Windows Server 2008 R2/6.1/x86
JVM  : Oracle Corporation/1.7.0_60/C:\Program Files (x86)\Java\jdk1.7.0_60\jre/32
************* STARTING AppSoftware ***********************
Service AppSoftware NOT started


text:
Q: Can't alter database roles on a restored database My SSMS Login (using an AD group) is allocated all server roles apart from sysadmin so I have quite a lot of access.
Using this Login, I have restored a database from its .bak file. However, my Login wasn't mapped to a User before this database was backed-up so when it is restored, I am not mapped to any Users. But, if I go into database Properties > Files, the Owner is me (although it is my personal Windows accounts not my AD Group Login I use within SQL).
I'm not sure how this affects things but it means I can still read/write to all the tables in the database, even though my Login is not a User in this database. I therefore then want to create a User on this database for my AD Group Login which works successfully. But then when I try to allocate this new User to any database roles, it says that I do not have permission.
What steps am I missing? What permissions do I need to allocate database roles to a new User on this restored database?

A: Despite the fact that you're seeing your login as the owner of the database, I don't believe that information is accurate because of the output you got from select user_name() and select is_member('db_owner'). I think SQL Server is misleading you. The permission to read/write every table on the database could be explained by the public database role.
About not being able to add a new member to the roles:
Since you're not a member of db_owner, you won't be able to add a user on a database role. The doc says that:

to change the membership in a fixed database role you need:

*

*Membership in the db_owner fixed database role

The problem taking the ownership:
When you tried to take ownership of the database (which is a way of being added to the db_owner role) you got the error

Cannot find the principal '[domain login]', because it does not exist
  or you do not have permission.

Because by being member of all server roles except sysadmin, as you described, doesn't grant you the TAKE OWNERSHIP or IMPERSONATE permissions and the ALTER AUTHORIZATION for databases doc says those permissions are needed:

Requirements for the person executing the ALTER AUTHORIZATION statement:
If you are not a member of the sysadmin fixed server
  role, you must have at least TAKE OWNERSHIP permission on the
  database, and must have IMPERSONATE permission on the new owner login.

You can check if you have those permissions from sys.fn_my_permissions running the following queries while connected to your restored database:
SELECT * FROM fn_my_permissions (NULL, 'DATABASE')
WHERE permission_name = 'TAKE OWNERSHIP';

SELECT * FROM fn_my_permissions (NULL, 'SERVER')
WHERE permission_name = 'IMPERSONATE ANY LOGIN';

If no rows are returned, it means you won't be able to alter the owner of the database and to change that you probably need a sysadmin to execute the ALTER AUTHORIZATION  or grant you enough privileges to do so.
Granting the needed privileges:
GRANT TAKE OWNERSHIP ON DATABASE::YourDatabase TO [YourDomain\YourGroupOrLogin];
GRANT IMPERSONATE ANY LOGIN TO [YourDomain\YourGroupOrLogin];

Note: The login that is going to be the owner of the database cannot be an existent user on that database, or you'll get the following error:

Msg 15110, Level 16, State 1, Line 1   The proposed new database owner
  is already a user or aliased in the database.

Further reading: the
Chart of SQL Server Permissions contains all the permissions you get from being a member of fixed roles (server and database level).

A: To solve this, I allowed my User to impersonate the dbo User so that I could then change fixed database roles.
USE [database]
GO
GRANT IMPERSONATE ON User::dbo TO [Domain\Login];

USE [database]
GO
EXECUTE AS User = 'dbo'
GO
ALTER ROLE [db_owner] ADD MEMBER [Domain\Login]
GO


text:
Q: prevent cross domain requests to my wcf services I use wcf ui services communicate between my javacsript (jquery) and server side code. I find this work effectively.
However I want to make it more secure. I can I set up wcf so that the requests to the services can only be made from within the same domain, to prevent external clients from making such requests to my services.
So for example, my service opertion url is http://www.website.com/Service.svc/GetProducts. I want to set up wcf so that only requests from pages in the http://www.website.com are allowed. I presume this is in the realm of cross domain wcf requests but need some assistance in setting this up. Help would be great.

A: This simply isn't possible if your services are exposed to the web.
If something about your services isn't secure enough for that, you should look into fixing that problem - not trying to prevent people from making requests.
Anyone can always use a debugging proxy like Fiddler, Charles, etc. or a tool like WireShark to send any data they want to your services - including a complete replay of a request made via the browser. (Including referrer http headers, etc).
If your situation allows for it, perhaps you might consider using a VPN appliance or something similar, and restrict access to users inside your network (or coming in through the VPN). That way there is less concern about your security of the services.... however it's a known fact that "internal attackers" are just as prevalent, if not more so, than external ones... so don't get too comfy.
Let me head this argument off at the pass too, while I'm at it; someone might suggest that browsers already prevent cross site scripting like that. Yes, that's true. But usually it would be the developer of the other application adding the client side script to call those services - and he/she could just as easily make that request on the server side and proxy the results along to the client.


text:
Q: Np Value Error: setting an array element with a sequence I am tried to solve a stochastic differential equation. After running my code for the 10th times I got this error, which I cannot address. Some help would be nice:
ux = np.zeros(N+1)
uy = np.zeros(N+1)
t = np.zeros(N+1)

def f(u1, u2, t, alpha):
    return -alpha * u1* (1-1/(np.sqrt(u1**2+u2**2)))

def ForwardEuler_iso(f, nin, nfin, dt, ux, uy, t):
    for k in range(nin+1, nfin):
        t[k+1]=t[k]+dt
        ux[k+1]=ux[k]+dt*f(ux[k], uy[k], t, alpha)+k_delta*np.sqrt(dt)*np.random.randn()
        uy[k+1]=uy[k]+dt*f(uy[k], ux[k], t, alpha)+k_delta*np.sqrt(dt)*np.random.randn()
    return ux, uy, t

ux, uy, t = ForwardEuler_iso(f_pol, N_pol+1, N, dt, ux, uy, t)

The error is given on ux, uy, t....


text:
Q: App Store Connect license agreement API I manage many iOS App Store Connect (Itunes Connect) accounts and am interested in whether or not there is an API that exposes the status of the license agreement for an account, similar to how https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/user/detail exposes app name, contentProviderId, etc. as JSON. I can't find anything in apple docs, and it's annoying to find out the license agreement expired while trying to upload a build.

Apparently this is off-topic....please enlighten me as to where a post such as this should go?


text:
Q: Input to Keras layer I am having input sequences  with the following shape.
shape(1434, 185, 37)

There are total 1434 sequences, each with the length of 185 characters and the total number of unique characters is 37. So in a way, we have the vocab size as follows.
vocab_size=37

Now when I define my keras input to an embedded layer as follows,
user_input = keras.layers.Input(shape=((185,37)), name='Input_1')
user_vec = keras.layers.Flatten()(keras.layers.Embedding(vocab_size, 50, input_length=185, name='Input_1_embed')(user_input))

I get the following error.
Error:
ValueError: "input_length" is 185, but received input has shape (None, 185, 37)

Now when I do the following, I don't get any error but I have doubt if it is right or not.
user_input = keras.layers.Input(shape=((185, )), name='Input_1')
user_vec = keras.layers.Flatten()(keras.layers.Embedding(vocab_size, 50, input_length=185, name='Input_1_embed')(user_input))

A: As mentioned in the comments section, embedding layer takes integer values as input, not one-hot encoded vectors. That's why your second solution works but not the first one. See this answer for more explanation.
However, if each timestep in your sequences is a vector of integers representing word indices (for example in each document you have 185 sentences where each sentence has 37 words), then you need to use TimeDistributed wrapper to apply the Embedding layer to each timestep:
user_input = keras.layers.Input(shape=((185,37)), name='Input_1')
emb_layer = keras.layers.Embedding(vocab_size, 50, input_length=37, name='Input_1_embed')
user_vec = keras.layers.TimeDistributed(emb_layer)(user_input)

The shape of user_vec would be (None, 185, 37, 50), i.e. an embedding vector of size 50 for each word in each timestep of each sequence.


text:
Q: Google API Gateway OpenApi Swaagger 2.0 to CloudRun Parameter configured for Path turns out in query instead of path I'm testing an API Gateway setup on Google Cloud to access specific endpoints on a service deployed on Cloud Run.  I'm following the steps shown here. We need to authenticate using an API Key, so the API Key specific configuration that went into the API Gateway config was picked from this documentation.
The API Gateway config is as shown below:
# api_gateway_config.yaml
swagger: '2.0'
info:
  title: myappapi
  description: API with Cloudrun Backend
  version: 1.0.0
schemes:
  - https
produces:
  - application/json
paths:
  /:
    get:
      summary: Greet a User from service
      operationId: hello
      x-google-backend:
        address: https://myappapi-asldfjoiewjfv-uc.a.run.app/
      security:
      - api_key: []
      responses:
        '200':
          description: A successful response
          schema:
            type: string
  /reports/results/{id}:
    get:
      summary: Get Report Results for specified report id
      operationId: GetReportResults
      x-google-backend:
        address: https://myappapi-asldfjoiewjfv-uc.a.run.app/v1/reports/results/{id}
      parameters:
        - in: path
          name: id
          required: true
          type: integer
      security:
      - api_key: []
      responses:
        '200':
          description: A successful response
          schema:
            type: string

securityDefinitions:
  # This section configures basic authentication with an API Key.
  api_key:
    type: "apiKey"
    name: "key"
    in: "query"

For a sample call to the /reports/results endpoint as http://myappapi/reports/results/1,
the expectation is for calls to get converted to https://myappapi-asldfjoiewjfv-uc.a.run.app/v1/reports/results/1?key=MyAPIKeyHere.  But instead they turn out as https://myappapi-asldfjoiewjfv-uc.a.run.app/v1/reports/results?key=MyAPIKeyHere&id=1
Is there a way to get the API calls go as https://myappapi-asldfjoiewjfv-uc.a.run.app/v1/reports/results/1?key=MyAPIKeyHere ?
Thanks in Advance!

A: As mentioned in this documentation

Set path_translation as part of setting x-google-backend:
   x-google-backend:
     address: https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello
     path_translation: [ APPEND_PATH_TO_ADDRESS | CONSTANT_ADDRESS ]

The default value of path_translation depends on where you set x-google->backend in your OpenAPI spec:

*

*When x-google-backend is used at the top level of the OpenAPI specification, path_translation defaults to APPEND_PATH_TO_ADDRESS.

*When x-google-backend is used at the operation level of the OpenAPI specification, path_translation defaults to CONSTANT_ADDRESS.

For more details on path translation, please see the Understanding path translation section. You can also check this stackoverflow thread.