text:
Q: is it wrong to store single big indexes in JS arrays? I have an upload handler connected to my js script.
(This upload handler is written in c++ and thus I'm unable to pass js objects around)
this upload handler starts the upload and immediately returns an UID (based on the current timestamp in milliseconds. looks like this :
var transferUid = fileTransfers.addFileTransfer(sourcePath,destination);

I'd like to add a callback function to this.
When the transfer is finished.
This js function is automatically executed when finished :
filetransfersfinished(uid){...}

is it reasonable to do something like this :
var finishFunctions = [];
finishfunctions [transferUid] = function(){/*callbacks*/}

transferUid could be like 184548178452 ...
and call it when the automatic function is called :
filetransfersfinished(uid){  finishfunctions[uid]();  }

Or is there a better solution you can think of?

A: Answering the question
Using Heap profiling tools in chrome, giving an array a huge size for little content does not seems to cause problems or a peak in heap allocation.
That's confirmed here as "Sparse Arrays vs. Full Arrays", and confirmed with this jsperf.
In substance : sparse arrays are slow, but not expected to be slower than objects properties.
Anyway, i'd suggest you use objects as it's more intuitive :
Answering your particular case
Best way would be to use an object (javascript equivalent to an "associative array") as pointed out in comment.
There is many ways to do it but to keep the syntax you used as much as possible, i'd do it like this :
var finishFunctions = {};
finishfunctions [transferUid.toString()] = function(){/*callbacks*/}

And then your callback :
filetransfersfinished(uid){  finishfunctions[uid.toString()]();  }

Note: With this method, you could use any convenient format for your uid, not just numbers. If it's of any value for you.


text:
Q: CString += operator performance issues I am working on an older MFC/C++ project that parses large text files using MFC's CString class to handle strings. I noticed that during the parsing process there's a lot of adding of small parts to an overall large CString object as such:
//'strContainer' = CString
//'tag' = CString of a much smaller size
strContainer += L"<" + tag + L">";

The operator above seems to be slowing the overall performance of CString when strContainer variable reaches a certain larger size. I'm supposing that such happens because of the often re-allocation of memory done by the += operator.
So I was curious, is there any way to improve this?
PS1. I do not know the size of the result string up front to pre-allocate it.
PS2. I have to stick with CString due to complexity of the project itself. (Or, I can't switch to Boost or other newer implementations.)

A: With std::string, += is usually quite fast as it can just copy bytes into already allocated buffers.  Usually, the L"<" + tag + L">"; will require three or more memory allocations, which are completely unnecessary, if you simply replace that line of code with three +=.  Additionally, allocations are REALLY REALLY SLOW if you have Visual Studio start the program for you, even release builds.  Run your program manually without Visual Studio, and see if that solves your performance problems.
I dug into the MFC source to very this.  (And dug and dug and dug...) and found that ATL::CSimpleStringT::PrepareWrite2(int nLength) will grow exponentially (1.5x bigger each allocation, completely normal, std::string is the same, except...
If the MFC string is over 1G, it only adds 1M each allocation after that.
So there's two conditions:
If strContainer is over 1G, you should manually reserve memory (Preallocate a large number of bytes.  It doesn't have to be exact, or even greater than the real number.).
Otherwise, simply replace the + with +=.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Looping through Interactive installer using expect I am trying to automate screen input of an interactive installer using expect and would like to use a loop which loops through lines of an answer file as input for part of the installer.
The installer has several sections to it, some of which are easily handled with simple expect/send responses. However there is a section in the installer which loops asking for data until you press a key to finish input. Then the rest of the installer continues.
The looping section looks like this on screen:
-------------------------------------------------------------------------------------------
Please enter ID details:
Please select an option: [A]dd [D]elete [I]mport [E]xport [F]inish =>A

Path: /opt/scanner/REF1/dump
ID: REF1

Please enter ID details:
Please select an option: [A]dd [D]elete [I]mport [E]xport [F]inish =>A

Path: /opt/scanner/REF2/dump
ID: REF2

Please select an option: [A]dd [D]elete [I]mport [E]xport [F]inish =>F

Rest of installer....
-------------------------------------------------------------------------------------------

Part of my expect script for the above looks like this:
expect -exact "Please select an option: \[A\]dd \[D\]elete \[I\]mport \[E\]xport \[F\]inish =>"
send -- "A\r"

expect -exact "Path: "
send -- "/opt/scanner/REF1/dump"
expect -exact "/opt/scanner/REF1/dump"
send -- "\r"

expect -exact "Please select an option: \[A\]dd \[D\]elete \[I\]mport \[E\]xport \[F\]inish =>"
send -- "A\r"

expect -exact "Path: "
send -- "/opt/scanner/REF2/dump"
expect -exact "/opt/scanner/REF2/dump"
send -- "\r"

expect -exact "Please select an option: \[A\]dd \[D\]elete \[I\]mport \[E\]xport \[F\]inish =>"
send -- "F\r"

Please excuse the verbosity as I have not been using expect long. This works but is not very efficient.
Ideally the answer file contains the REF1, REF2, until EOF (one per line) and a loop to read each line and send to the screen.
I have seen this solution but not sure how this fits in with the above.
I have been playing around with this Tcl code which may form a solution?
puts "/opt/scanner/$LINE/dump"
puts "$LINE"

Where $LINE is REF1, REF2 from the answer file.
Thanks in advance.

A: The first things to do to reduce the verbosity are: put the prompt into a variable; send the carriage return with the path.
set prompt "Please select an option: \[A\]dd \[D\]elete \[I\]mport \[E\]xport \[F\]inish =>"

expect -exact $prompt
send -- "A\r"
expect -exact "Path: "
send -- "/opt/scanner/REF1/dump\r"

expect -exact $prompt
send -- "A\r"
expect -exact "Path: "
send -- "/opt/scanner/REF2/dump\r"
send -- "\r"

expect -exact $prompt
send -- "F\r"

We could put this into a loop, but it adds some complexity
set refs [list "REF1" "REF2"]
set count 0
expect $prompt {
    if {$count == 2} {
        send -- "F\r"
    } else {
        send -- "A\r"
        expect -exact "Path: "
        set ref [lindex $refs $count]
        send -- "/opt/scanner/$ref/dump\r"
        incr count
        exp_continue
    }
}

The exp_continue command "loops" back to the "outer" expect command.


text:
Q: Accessing individual elements of an encrypted list in python I have a list of strings, and I am using AES encryption to encrypt each of the strings and stores them in a different list.
When I print the entire list, all the encrypted strings can be seen. But when trying to access individual strings, the output is different. What is causing this?
Here is the code
from Crypto.Cipher import AES

keywords = ['country', 'state', 'nation', 'area']
i = 0
encryptlist = []

while i < len(keywords):
    obj = AES.new('samplekey1234567',AES.MODE_CFB,'sampleiv12345678')
    encryptlist.append(obj.encrypt(keywords[i]))
    i = i+1

print encryptlist
print encryptlist[0]

This is what the output looks like
['&\x8cj\xbay\x93\xb9', '65\xfe\xf9s', '+\n\xe1\xa8\xdd~', '$tI\xc7']

&Œjºy"¹

A: print on a list invokes __repr__ on each element, while print on a string calls __str__
>>> '&\x8cj\xbay\x93\xb9'.__str__()
&îj║yô╣

>>> '&\x8cj\xbay\x93\xb9'.__repr__()
'&\x8cj\xbay\x93\xb9'

so:
>>> print '&\x8cj\xbay\x93\xb9'
&îj║yô╣

while
>>> print ['&\x8cj\xbay\x93\xb9']
['&\x8cj\xbay\x93\xb9]


text:
Q: React key on grouped list I'm getting the error that I need to have a unique key prop for each child in a list. However I'm adding li elements to a ul in groups based on the dates supplied. So I don't have a parent element to attach a key prop to. As you can see from the code below I've attempted to add it to each li element inside the fragment but it's not good enough for react apparently.
Any suggestions?
export const DeskBookCard: React.FC<Props> = ({ desk, dates, bookAction }: Props) =>{

return

{desk.name}

  <form onSubmit={() => bookAction()}>

    {
      dates.map(date => {
        const DATE_FORMAT = 'EEEE, do LLLL'
        return <>
          <li key={`${format(date, 'T')}-am`}>

              <input type="checkbox" name={`${format(date, 'T')}-am`} id={`${date}-am`}/>
              {format(date, DATE_FORMAT)} - AM

          <li key={`${format(date, 'T')}-pm`}>

              <input type="checkbox" name={`${format(date, 'T')}-pm`} id={`${date}-pm`}/>
              {format(date, DATE_FORMAT)} - PM

        </>
      })
    }

  <button type="submit">Book a desk</button>
  <button>cancel</button>
  </form>

A: I switched to using the longform React.Fragment instead of the <> shorthand and I was able to apply a key prop to that:
e.g. <React.Fragment key={format(date, 'T')}>


text:
Q: How to launch background cycle from bash-script from Ansible-playbook I'm creating a simple Traffic simulator: a client that curl a Webserver every 10 seconds. The client(Debian) and the WebServer are configured using Ansible. The background-cycle is closed when the Ansible-SSH connection is closed.
At first I launched the command:
$ while true; do curl python_webserver:8000; sleep10; done </dev/null >/dev/null 2>&1 &;
$ disown

And It works fine from Bash, but if I put it into a script, it exit at ssh-connection end.
I try some other solutions, like using:
$ nohup [command]
$ nohup /bin/bash -c '[command]

or using "deamonize" but nothing worked. Nothing I found online works; maybe I'm missing something important. (Writing the pid is important, but not fundamental)
I here the script, maybe there is a big newbie error.
#!/bin/bash
PORT=8000
while true; do
    curl python_webserver:$PORT
    sleep 10
done >/dev/null 2>&1 &
ANSIBLE_CLIENT_PID=$!
echo $ANSIBLE_CLIENT_PID >> /tmp/ANSIBLE_PID.txt
disown

A: The answers is
nohup sh -c 'while true; do curl python_webserver:'"$PORT"'; sleep 10; done >/dev/null 2>&1' &

Probably I made a mistake with quotation marks.
Thank you all for you help
(especially Kamil Cuk for the solution)


text:
Q: Webpack with sourcemap can't resolve variables in production mode I would like to generate source maps for our production build with Webpack. I managed to generate it, but when I stop on a breakpoint in the debugger, variables are not resolved:

What am I doing wrong? How can I generate a source map that lets the chrome devtools resolve the variables once I stopped on a breakpoint in the debugger?
These are my webpack configurations:
webpack.config.js:
const path = require('path');
const ROOT = path.resolve( __dirname, 'src/main/resources/packedbundle' );

const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
context: ROOT,

resolve: {
    extensions: ['.ts', '.js']
},

module: {
    rules: [
        {
            test: /\.ts$/,
            exclude: /node_modules/,
            use: [
                {
                    loader: 'eslint-loader',
                    options: {
                        failOnError: true,
                        quiet: true
                    }
                }
            ],
            enforce: 'pre'
        },

        {
            test: /\.ts$/,
            exclude: [ /node_modules/ ],
            use: [
                'ng-annotate-loader',
                'awesome-typescript-loader'
            ]
        },

        {
            test: /\.scss$/,
            use: ExtractTextPlugin.extract({
                fallback: 'style-loader',
                use: ['css-loader', 'sass-loader'],
                publicPath: '../'
            }),
        },

        {
            test: /\.(jpg|png|gif)$/,
            use: 'file-loader'
        },

        {
            test: /\.(svg|woff|woff2|eot|ttf)$/,
            use: 'file-loader?outputPath=fonts/'
        },

        {
            test: /.html$/,
            exclude: /index.html$/,
            use: 'html-loader'
        }
    ]
},

plugins: [
    new HtmlWebpackPlugin({
        title: 'AngularJS - Webpack',
        template: 'index.html',
        inject: true
    }),
    new LoaderOptionsPlugin({
        debug: true
    }),
    new ExtractTextPlugin('css/style.css')
],

entry: './index.ts'

};
webpack-prd.config.js:
const path = require('path');
const webpackMerge = require('webpack-merge');
const commonConfig = require('./webpack.config.js');
const DESTINATION = path.resolve( __dirname, 'dist/packedbundle' );

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = webpackMerge(commonConfig, {
    devtool: 'module-source-map',
    mode: 'production',
    output: {
        path: DESTINATION,
        filename: 'js/[name]-bundle-[chunkhash].js'
    },

    optimization: {
        minimizer: [
            new UglifyJsPlugin({
                sourceMap: true
            })
        ]
    }
});

package.json:
{
  "name": "com.avon.maps.packedbundle.webcontent",
  "version": "1.0.0",
  "description": "Packed bundle creation screen frontend",
  "main": "index.js",
  "scripts": {
    "prestart": "rimraf dist",
    "start": "node node/node_modules/npm/bin/npx-cli.js check-node-version --package && webpack --config webpack-dev.config.js",
    "prebuild": "rimraf dist",
    "build": "node node/node_modules/npm/bin/npx-cli.js check-node-version --package && webpack --config webpack-prd.config.js",
    "test": "mocha -r ts-node/register -r ignore-styles -r jsdom-global/register __tests__/**/*.spec.ts"
  },
  "author": "BlackBelt",
  "private": true,
  "engines": {
    "node": "11.10.0"
  },
  "devDependencies": {
    "@types/angular": "1.6.51",
    "@types/angular-loading-bar": "0.0.35",
    "@types/chai": "4.1.7",
    "@types/core-js": "2.5.0",
    "@types/jquery": "3.3.29",
    "@types/kendo-ui": "2019.1.1",
    "@types/mocha": "5.2.6",
    "@types/node": "10.12.0",
    "@types/underscore": "1.8.13",
    "@types/webpack-env": "1.13.6",
    "@typescript-eslint/eslint-plugin": "1.6.0",
    "@typescript-eslint/parser": "1.6.0",
    "acorn": "6.1.1",
    "awesome-typescript-loader": "5.2.1",
    "chai": "4.2.0",
    "check-node-version": "3.2.0",
    "css-loader": "1.0.0",
    "eslint": "5.16.0",
    "eslint-config-airbnb-base": "13.1.0",
    "eslint-loader": "2.1.2",
    "eslint-plugin-import": "2.16.0",
    "extract-text-webpack-plugin": "v4.0.0-beta.0",
    "file-loader": "2.0.0",
    "html-loader": "0.5.5",
    "html-webpack-plugin": "3.2.0",
    "ignore-styles": "5.0.1",
    "istanbul-instrumenter-loader": "3.0.1",
    "jsdom": "14.0.0",
    "jsdom-global": "3.0.2",
    "mocha": "6.1.2",
    "ng-annotate-loader": "0.6.1",
    "node-sass": "4.11.0",
    "rimraf": "2.6.2",
    "sass-loader": "7.1.0",
    "style-loader": "0.23.1",
    "ts-node": "8.0.3",
    "typescript": "3.4.2",
    "uglifyjs-webpack-plugin": "2.0.1",
    "webpack": "4.23.1",
    "webpack-cli": "3.1.2",
    "webpack-merge": "4.1.4"
  },
  "dependencies": {
    "angular": "1.7.5",
    "core-js": "3.0.1",
    "growl": "1.10.5",
    "jquery": "3.3.1",
    "underscore": "1.9.1"
  }
}

I cannot share the source code, but I used this angularjs webpack starter project to start mine.

A: Issues with invalid sourcemaps in Webpack and terser-webpack-plugin are addressed starting with webpack 4.39.2 and terser-webpack-plugin 1.4.0.
v4.39.0 release log:

webpack-sources + terser-webpack-plugin comes with quality optimizations for SourceMaps

There was an additional issue, whose fix was published later. It was included for webpack-sources v1.4.2/webpack 4.39.2. In conclusion 4.39.2or latest version is the one to go.
Details
Sourcemaps in production mode seem to work as expected in most cases now. Unfortunately, if you have non trivial code transformations like inlining of functions (that exist in source code, but are dissolved from webpack) in the course of uglyfying/minification/optimization, breakpoints sometimes still don't get mapped well. Part of the reason is, that the sourcemap spec is vague concerning those aspects.


text:
Q: Using Ajax Form and Pagination - losing search parameters on next page selection Ok - someone must have done this before me.
I have a an Ajax form (Ajax form helper) that has a search box and some checkboxes to filter stuff.  The search results are rendered beneath by way of a partial view.  See below:

Here is the code:
Search.cshtml
@using (Ajax.BeginForm("SearchStuff", "FooController", new AjaxOptions
{
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "GET",
    OnFailure = "searchFailed",
    LoadingElementId = "progress",
    UpdateTargetId = "search-results",
}))
{

                <input type="checkbox" name="chkAll" checked />
                All
                <input type="checkbox" name="chkJournal" />
                Journal
                <input type="checkbox" name="chkBook" />
                Book
                <input type="checkbox" name="chkBookChapter" />
                Book Chapter
                <input type="checkbox" name="chkReport" />
                Report
                <input type="checkbox" name="chkWebsite" />
                Website
                <input type="checkbox" name="chkPersComm" />
                Personal Comm
                <input type="checkbox" name="chkConference" />
                Conference
                <input type="checkbox" name="chkMap" />
                Map
                <input type="checkbox" name="chkThesis" />
                Thesis

            <input type="search" name="q" autocomplete="off"/>
            <input class="submit-button" type="submit" value="Search" />

}

Problem with Pagination
I have now started to try and get a bit clever and I have included an Ajax Pager to have pagination returned in the first set of search results.

Problem is, I have to retain all values in the ajax search form when the user selects the next page to render, but when I debug back at the SearchStuff method in FooController - it doesn't know anything about the search parameters.  Can anyone suggest what I should do to send the search parameters on?

    @Html.Raw(
        Ajax.Pager(new AjaxOptions
        {
            UpdateTargetId = "search-results",
            OnBegin = "beginPaging",
            OnSuccess = "successPaging",
            OnFailure = "failurePaging"
        },
                      Model.PageSize,
                      Model.PageNumber,
                      Model.TotalItemCount,

                      new { controller = "FooController", action = "SearchStuff"})
    )

A: Use HttpMethod="Get" in new AjaxOptions. and change your controller with Request[] to get the search parameters.
Refer
Filter is getting lost in WebGrid + Paging + Sorting + Filtering in .NET 4.0


text:
Q: How many integers from $1$ through $999,999$ contains digit $1$? How many integers from $1$ through $999,999$ contains digit $1$?
I have no idea to solve this problem. Have anyone give me some advice?
Thanks in advance!!

A: HINT: Consider those integers as six character strings over the alphabet $\{0,1,2,3,4,5,6,7,8,9\}$. How many strings don't contain $1$? It might be helpful to add $0$ to your range of integers first.

A: How many numbers don't contain a 1?
First lets extend our range: $0 = 000000$ to $999999$
From this We can work out the probability that the number does not contain a 1
$$\left(\frac{9}{10} \right)^{6}$$
And the total number
$$10^6 \times \left(\frac{9}{10} \right)^{6} = 531441$$
Now we have over counted by 1 because we extended the range so there are $531440$ numbers that don't contain any 1 so there must be $999999 - 531440 = 468559$ that do contain at least one 1.

A: While Asaf's answer is the simplest, we can also use the Inclusion-Exclusion Principle to answer this question.
Let $A_i$ be the set of numbers with a '$1$' in digit $i$. The sum of the intersection of $k$ of the $A_i$'s is
$$
10^{6-k}\binom{6}{k}
$$
That is for each of the $\binom{6}{k}$ choices of the $A_i$'s, there are $10^6-k$ numbers with a '$1$' in the specified digit. The Inclusion-Exclusion Principle says that the count of numbers containing a $1$ is
$$
\sum_{k=1}^6(-1)^{k-1}10^{6-k}\binom{6}{k}
$$
which is
$$
\begin{align}
&10^5\binom{6}{1}-10^4\binom{6}{2}+10^3\binom{6}{3}-10^2\binom{6}{4}+10^1\binom{6}{5}-10^0\binom{6}{6}\\
&=600000-150000+20000-1500+60-1\\[8pt]
&=468559
\end{align}
$$


text:
Q: Technology advice - Tablet based web application - (Platform independent) -Sort Of Enterprise Management System I'm planning to develop a tablet based web application that is compatible on all platforms (iOS, Android, Blackberry etc). I need your advice in choosing the right technology.
Project Description: This web application should have the capability to generate user specific information, generate reports for high level managers (dynamic data) and ability to link with various systems belonging to multiple departments of an enterprise (say, HR & Manufacturing). Sort of a dashboard used for Content & User management.
Most importantly, ability to link with  previously build PHP applications and .Net applications.
Sample Scenario:
Lets say, a facility manager is in charge of 200 buildings, this application should be able to generate specific information for each levels across various buildings.
And normal residents on a level in a building, should be able to receive their specific information once they log in on to the system.
My Research:

*

*Drupal 7 offers great content management facilities, and some of its themes work on tablets and mobiles with ease. Only customization is required.

However, I doubt if we can link with our previously build .NET applications. This re

*

*jQuery Mobile & jQuery frame work has the framework for building the interface, but content management requires lot of coding.

My skill set: Intermediary skills in PHP & MySQL; Beginner in Drupal 7.
Is there a technology that can offer all of these like Content & user Management, inter connectivity with other applications, etc in one go with less coding & time.
I appreciate your efforts in giving me suggestions.

A: I would recommend you keep it simple and use a web based interface i.e. plain old HTML/css and JavaScript.
All of the devices mentioned have full function web browsers supporting the latest HTML and CSS standards. You may need to tailor your css to cope with differing screen sizes.
It should be relatively each to develop a dynamic .NET based web front end to the existing applications.


text:
Q: Why a 2D array is used for stack? Why cant a 1D array be used for a stack? Here, s[20][20] is declared in function pre_post. But the push operation involves pushing a string into stack s. How is that done? Why cant we execute the program with a 1D array for s like s[20] for stack??
#include<stdio.h>
#include<string.h>
#include<ctype.h>
void push(char item[],int *top,char s[][20])    //Pushes the symbol item onto stack s
{
  *top=*top+1;                                  //Top is incremented
  strcpy(s[*top],item);                         //Item is actually written onto stack
}

char *pop(int *top,char s[][20])                //Pops out the topmost element of stack s
{
  char *item;
  item=s[*top];
  *top=*top-1;
  return item;
}

void pre_post(char prefix[],char postfix[])     //Function to convert prefix to postfix
{
  char s[20][20];
  int top,i;
  char symbol,ch[2];
  char *op1,*op2;

  top=-1;
  for(i=strlen(prefix)-1;i>=0;i--)              //Scans the expression in   reverse manner
  {
    symbol=prefix[i];                           //The last symbol is scanned first
    ch[0]=symbol;
    ch[1]='\0';
    switch (symbol)                             //Checks whether the symbol is one among fiveoperators given.(next line)
                                                //If yes then execute the corresponding statements
    {
      case '+':
      case '-':
      case '*':
      case '/':
      case '^':
        op1=pop(&top,s);                        //The topmost operand of stack s is popped and stored as op1
        op2=pop(&top,s);                        //The next operand of stack s is popped and stored as op2

        strcpy(postfix,op1);                    //Copies the op1 into postfix
        strcat(postfix,op2);                    //Concatenates the op2 with postfix
        strcat(postfix,ch);                     //Concatenates the ch with postfix
        push(postfix,&top,s);                   //Pushes the postfix onto stack s
        break;
      default:
        if(isalnum(symbol))                     //It means that switch case is not satisfied i.e. symbol is a operand
          push(ch,&top,s);                      //Pushes the operand onto the stack s
    }
  }

}

int main()
{
  char prefix[20];
  char postfix[20];
  printf("\n\n Enter the prefix expression \n\n");
  gets(prefix);
  pre_post(prefix,postfix);
  printf("\n\n The postfix expression is %s \n\n",postfix);
  return 0;
}

A: You need a 1-d array of characters to represent a string.
char str[20]; // An array of characters that can hold a string
              // of up to 19 characters.

Then, you need a 2-d array of characters to represent an array of strings.
char str[100][20]; // An array 100 strings. Each element of the array
                   // can hold a string of up to 19 characters.


text:
Q: MySQL Triggers not working from PHP page but work for manual DB updates via phpMyAdmin I have the following two Triggers in my MySQL DB that fire BEFORE/UPDATE and AFTER/UPDATE on the house_report_details table. The first deletes all records in my scratch table tmp_house_rpt_details and the second inserts a single record into this scratch table for use in subsequent PHP code:
Trigger 1 (BEFORE/UPDATE on house_report_details):
DELETE FROM tmp_house_report_details

Trigger 2 (AFTER/UPDATE on house_report_details):
CREATE TRIGGER `trg_create_tmp_house_rpt_detail` AFTER UPDATE ON `house_report_details`
   FOR EACH ROW
      INSERT INTO tmp_house_report_details
         (rpt_week_num, client_id, residence_id, curr_step, curr_step_dur,
          prev_wk_step, prev_wk_step_dur, prev_bal, wkly_rent, curr_bal)

      SELECT (NEW.rpt_week_num + 1), NEW.client_id,
             vw_next_wk_house_assignments.residence_id, NEW.curr_step,
             (NEW.curr_step_dur + 1), NEW.curr_step, NEW.curr_step_dur,
             NEW.curr_bal, vw_next_wk_house_assignments.rent_amt,
             (NEW.curr_bal + vw_next_wk_house_assignments.rent_amt)

        FROM vw_next_wk_house_assignments
       WHERE vw_next_wk_house_assignments.client_id = NEW.client_id
      ON DUPLICATE KEY UPDATE
             residence_id = vw_next_wk_house_assignments.residence_id,
             curr_step = NEW.curr_step,
             curr_step_dur = (NEW.curr_step_dur + 1),
             prev_wk_step = NEW.curr_step,
             prev_wk_step_dur = NEW.curr_step_dur,
             prev_bal = NEW.curr_bal,
             wkly_rent = vw_next_wk_house_assignments.rent_amt,
             curr_bal = (NEW.curr_bal + vw_next_wk_house_assignments.rent_amt)

Here are sample rows from the 'master' table - house_report_details - that has the two triggers. The temp/scratch table, tmp_house_report_details, that the triggers delete/insert into has the exact same schema as the master:
SELECT * FROM `house_report_details` LIMIT 3

id rpt_week_id rpt_week_num client_id residence_id curr_step curr_step_dur prev_wk_step prev_wk_step_dur num_mtgs sponsor_contact chores_flg prev_bal wkly_rent other_chgs amt_paid curr_bal last_updated_by last_updated_dt

9   10         10           3         1            3         2             3
        1                9        5               Y          0.00     -125.00
0.00       125.00   0.00     Elvis Presley   Mar-6-2019 03:37pm CST

10  10         10           6         1            3         3             3
        2              9          7               Y          -150.00  -75.00
0.00       225.00   0.00     Elvis Presley   Mar-6-2019 03:22pm CST

11  10         10           9         1            7         1             6
        4              9          6               Y          0.00     -100.00
0.00       100.00   0.00     Elvis Presley   Mar-13-2019 08:26am CST

The triggers work perfectly in my local dev environment and work on my hosted server environment if I manually update information in the house_report_details table using phpMyAdmin.
The BEFORE/UPDATE trigger to delete the scratch table record also works when the table updates are made from my PHP web pages but the AFTER/UPDATE trigger does not work for some reason and causes my entire table update transaction to fail (as failed trigger execution should).
I cannot find anything to help tell me why a trigger will work when manually invoked (via phpMyAdmin, for example) but not when the same DB update is performed via PHP/MySQL code in my web pages.
My hosting provider is BlueHost and I am running MySQL v5.6.41-84.1 and PHP v7.0.33.
I really want to be able to use the power that triggers provide and hope I can get this resolved quickly so I don't have to convert my triggers into PHP/MySQL code in my PHP pages instead.
This is my first question here, so I hope I have provided enough information to troubleshoot this issue. Happy to provide additional details, if needed.
Thank you,
Steve.

A: Type SHOW CREATE TRIGGER trigger_name into the query window. This will give you the SQL code that creates trigger.
You can then add it to your question so we can help you with it.
Also, when modifying your trigger, instead of using GUI, use the query window. Just put DROP TRIGGER trigger_name in the top of your trigger script.


text:
Q: function calculation based on condition I am practising and new to create a function in Python with conditions:
create a function that takes an input of an integer number (for example m, where m is between 2 to n, and n is the maximum number of rows). This function calculates the 'Sum A' and 'Sum B' from the last m-days. There will be no value for the first m-days
The original data:
V       TP         A                   B             Sum A   Sum B
3509    47.81
4862    48.406667   235353.2133
1810    49.26           89160.6
3824    49.263333   188382.9867
2209    47.386667                   104677.1467
4558    45.573333                   207723.2533
3832    44.396667                   170128.0267
3778    43.75                          165287.5
1005    44.64           44863.2
4047    43.76                         177096.72
2201    44.383333   97687.71667                     655447.7167 824912.6467
2507    45.156667   113207.7633                     533302.2667 824912.6467
4392    44.4333                        195151.2     444141.6667 1020063.847
3497    43.296667                   151408.4433       255758.68 1171472.29
1181    43.07                          50865.67       255758.68 1117660.813
1971    42.89                          84536.19       255758.68 994473.75
4994    43.563333   217555.2867                     473313.9667 824345.7233
2017    44.816667   90395.21667                     563709.1833 659058.2233
2823    44.936667     126856.21                     645702.1933 659058.2233
2774    45.13         125190.62                     770892.8133 481961.5033

Continue original data
Day
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

The attempt that I have done so far is and it shows error KeyError 'A':
curret_period = int(input("enter days: "))
sumA = curret_period * ((df["A"] < df["A"]),'')
sumB = curret_period * ((df["B"] >= df["B"]),'')
print(sumA)
print(sumB)

I am wondering is there a better way to create the function? I also wonder if below is the one that I need?
def function_name()
    print()

Expected result when m= 10:
    A                     B                        Sum A       Sum B
0
1   235353.21333333332
2    89160.59999999999
3   188382.98666666663
4                        104677.1466666667
5                       207723.25333333333
6                       170128.02666666667
7                                 165287.5
8   44863.200000000004
9                                177096.72
10   97687.71666666666                          655447.7167    824912.6467
11  113207.76333333334                          533302.2667    824912.6467
12                                195151.2      444141.6667    1020063.847
13                       151408.4433333333        255758.68     1171472.29
14                       50865.66999999999        255758.68    1117660.813
15                       84536.19000000002        255758.68      994473.75
16  217555.28666666665                          473313.9667    824345.7233
17   90395.21666666666                          563709.1833    659058.2233
18           126856.21                          645702.1933    659058.2233
19  125190.61999999998                          770892.8133    481961.5033

Any suggestion? Thank you in advance.

A: You can utilize df.tail() to get the last m rows of the dataframe and then simply sum() each column.
We can also check if m is not greater than the length of the dataframe, however even if you did not have this it would just sum the entire dataframe.
def sumof(df, m):
    if m <= len(df.index):
        rows = df.tail(m)
        print(rows['A'].sum())
        print(rows['B'].sum())
    else:
        print("'m' can not be greater than length of dataframe")


text:
Q: VideoCapturer.startCamera(width, height, fps) crops the Camera with different width,height android I want to open my camera and capture video for video call in an Android application.
First i create a videoCapturer with this
private fun createCameraCapturer(): VideoCapturer? {
        val enumerator: CameraEnumerator = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            Camera2Enumerator(context)
        } else {
            Camera1Enumerator(false)
        }

        // Try to find front facing camera
        enumerator.deviceNames.forEach {
            if (enumerator.isFrontFacing(it)) {
                videoCapturer = enumerator.createCapturer(it, null)
                if (videoCapturer != null) return videoCapturer
            }
        }

        // Front facing camera not found, try something else
        enumerator.deviceNames.forEach {
            if (!enumerator.isFrontFacing(it)) {
                videoCapturer = enumerator.createCapturer(it, null)
                if (videoCapturer != null) return videoCapturer
            }
        }

        return null
    }

After i get a non-null videoCapturer i start the cameraCapture with given width,height and fps.
videoCapturer?.initialize(surfaceTextureHelper, context, videoSource?.capturerObserver)
videoCapturer?.startCapture(width, height, fps)

The possible combinations of width and height are the following
0 -> VideoHeader(fps: 5, height: 128, width: 96
1 -> VideoHeader(fps: 5, height: 320, width: 240
2 -> VideoHeader(fps: 10, height: 480, width: 360
3 -> VideoHeader(fps: 10, height: 640, width: 480
4 -> VideoHeader(fps: 15, height: 960, width: 720

I notice that there is a crop in the video that i get in the UI view according to the VideoHeader. For example if i have the case: 0  then the participant is cropped in the right top side of his face. Like there is a zoom or something.
Is there any way that i could solve this issue?

A: Use the below code on SurfaceViewRenderer instance:
surfaceviewrenderer.setScaleType(Scaletofit)

This would not give zoom effect on stream and not cropped the stream.
You can play around setScaleType as per your need


text:
Q: Same method name as in Base Class with a different return type in derived class With the code below.
class Program
{
    static void Main(string[] args)
    {
        BaseClass obj = new BaseClass();
        DerivedClass obj2 = new DerivedClass();

        var x = obj.Method(2);
        var z = obj2.Method(1);
    }
}

class BaseClass
{
    public int Method(int i) { return i; }
}

class DerivedClass : BaseClass
{
    public string Method(int i) { return i.ToString(); }
}

Why is that when I have the method in the derived class, the derived class object is calling its own function and if I do not have it, the derived class object is calling the base function?

A: If you want to override this behavior then you can mark a method with the new modifier which will explicitly hide a member in the class you derive from.
public new string Method(int i) { return i.ToString(); }

A: You should have received a warning from the compiler about this. Your new Method() method is implicitly hiding the base's (you can make this explicit using the new keyword, which will also silence the compiler warning). See also http://msdn.microsoft.com/en-us/library/aa691135%28v=vs.71%29.aspx.
Note that in C# there is no such thing as overloading a method based only on its output type. Just because your new method happens to return a string doesn't make its signature any different from the base's.
Note the following caveat about the dangers of hiding, which may also help to illustrate what is going on:
static void Main(string[] args)
{
    BaseClass obj = new BaseClass();
    DerivedClass obj2 = new DerivedClass();

    var x = obj.Method(2); //returns 2
    var z = obj2.Method(1); //returns 2 (2*2)
    var a = ((BaseClass)obj2).Method(1); //returns 1 (base's implementation!)
}

class BaseClass
{
    public int Method(int i) { return i; }
}

class DerivedClass : BaseClass
{
    public int Method(int i) { return i * 2; }
}

This is unlike the behavior in the following code, which adds a new Method(string) overload:
static void Main(string[] args)
{
    BaseClass obj = new BaseClass();
    DerivedClass obj2 = new DerivedClass();

    var x = obj.Method(2); //returns 2
    var z = obj2.Method("1"); //returns "1"
    var a = ((BaseClass)obj2).Method("1"); //returns "1"
}

class BaseClass
{
    public int Method(int i) { return i; }
}

class DerivedClass : BaseClass
{
    public string Method(string s) { return s; }
}

A: Inheritance means that your DerivedClass automatically has all the members that BaseClass has. Therefore it also has the Method which returns int.
It's a bad idea to introduce a new method with the same name and the same arguments, in the DerivedClass. Because then DerivedClass has two methods with the same signature. That's why you get a warning from the compiler. Even if the warning goes away when you use the modifier of the new keyword, it's still a bad idea to have two methods with the same signature.
Instead, choose an unused name for the method in DerivedClass.
To answer your question more directly: When you have one method Method only, the one you wrote inside BaseClass, all is good. The DerivedClass inherits this method. This is why you can call it on obj2. But when you introduce a second method in DerivedClass, the call obj2.Method(1); needs to choose between two methods, because unfortunately there are two methods with the same signature. The rule in this case is to choose the method defined in DerivedClass. But note that it's the compile-time type that matters here. So if you said
BaseClass obj3 = new DerivedClass();
var w = obj3.Method(42);

even if the run-time type of obj3 is DerivedClass, it's the first method that gets called because of the compile-time type. Like I said, obj3 possesses both methods.

A: this is because , you hide the base method in derived class and when you create a object of derived class , it will call its own implementation. Compiler shouts when you do it without proper mechanism ( By using new keyword) and when you don't have the method in derived class then base class implementation kicked in.


text:
Q: Is this reflexive? I would like to know whether the following "$\sim$" is reflexive and/or symmetric or not according to the following definition:

Suppose $\sim$ is defined on the set of the integers as follows : $a\sim b$ iff $ab ≤ a|b|$

How do I proceed to solve this problem? Please help. Thanks!

A: A relation $R$ is reflexive when :

for all $x : xRx$.

Thus $\sim$ is reflexive iff for all $a : aa ≤ a|a|$.
Consider now $a := -2$ : $aa= (-2)(-2) = 4 > -4 = (-2)(|-2|)$.
Conclusion : not reflexive.

For symmetry :

is it true that, if $ab \le a|b|$, then $ba \le |b|a$ ?

In general, for $a,b < 0$ we have that $ab > 0$ while $a|b| < 0$ ($+ \times - = -$) and thus $ab > a|b|$.
Also, for $a,b \ge 0$ we have that $a|b| = ab = |b|a$. Thus $ab \le a|b|$ and also $ba \le |b|a$.
Conclusion, we have only to take care of the cases : $a > 0$ and $b < 0$ and $a < 0$ and $b > 0$.


text:
Q: Complication works on Simulator, but not on Device I have a complication that works on Simulator, but doesn't work on an actual device when I TestFlight it to test on an actual device (and for clarity sake if there is any confusion, I'm not talking about debugging via device, but just testing if it works on a device).
Specifically, on the Watch device:

*

*I select the Complication on the Watch thru customizing the clock face, which gives me the placeholder text (so far so good because
getPlaceholderTemplateForComplication works on Simulator too)...

*but then the Complication always stays as the placeholder text (not
correct because getCurrentTimelineEntryForComnplication works on
Simulator)...

*even when scrolling thru Time Travel the placeholder text doesn't change but just dims (not correct because getTimelineEntriesForComplication:afterDate works on Simulator)...

Info on iPhone:
    game.duel = playoffs["Duel"] as! String
    game.tv = playoffs["TV"] as! String
    game.td = playoffs["TD"] as! AnyObject
    let dictionary = ["Duel" : game.duel, "TV" : game.tv, "TD" : game.td]
    let transferComplication = WCSession.defaultSession().transferCurrentComplicationUserInfo(dictionary)

ExtensionDelegate in WatchKit Extension:
    var duelArray = [String]()
    var tvArray = [String]()
    var tdArray = [NSDate]()
    let defaults = NSUserDefaults.standardUserDefaults()

        if let duel = userInfo["Duel"] as? String, let tv = userInfo["TV"] as? String, let td = userInfo["TD"] as? String {
            duelArray.append(duel)
            tvArray.append(tv)
            tdArray.append(td as! NSDate)
            defaults.setObject(duelArray, forKey: "DuelSaved")
            defaults.setObject(tvArray, forKey: "TVSaved")
            defaults.setObject(tdArray, forKey: "TDSaved")
}

ComplicationController in WatchKit Extension:
    func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
switch complication.family {
        case .ModularLarge:
            let mlTemplate = CLKComplicationTemplateModularLargeStandardBody()
                if let currentDuel = defaults.arrayForKey("DuelSaved") as? [String] {
                        let firstDuel = currentDuel[0]
                        let headerTextProvider = CLKSimpleTextProvider(text: firstDuel)
                        mlTemplate.headerTextProvider = headerTextProvider
                } else {
                    // …

                }
                if let currentTV = defaults.arrayForKey("TVSaved") as? [String] {
                    let firstTV = currentTV[0]
                    let body1TextProvider = CLKSimpleTextProvider(text: firstTV)
                    mlTemplate.body1TextProvider = body1TextProvider
                } else {
                    // …
                }
                if let currentTD = defaults.arrayForKey("TDSaved"){
                        let firstTD = currentTD[0]
                        let body2TextProvider = CLKTimeTextProvider(date: firstTD as! NSDate)
                        mlTemplate.body2TextProvider = body2TextProvider
                } else {
                    // …
                }
                let timelineEntry = CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: mlTemplate)
                handler(timelineEntry)
    // …
}

    func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
        let headerArray = defaults.arrayForKey("DuelSaved")
        let body1Array = defaults.arrayForKey("TVSaved")
        let body2Array = defaults.arrayForKey("TDSaved")

        guard let headers = headerArray, texts = body1Array, dates = body2Array else { return }
        var entries = [CLKComplicationTimelineEntry]()
for (index, header) in headers.enumerate() {
            let text = texts[index]
            let date1 = dates[index]
            let headerTextProvider = CLKSimpleTextProvider(text: header as! String, shortText: headerShort as? String)
            let body1TextProvider = CLKSimpleTextProvider(text: text as! String)
            let timeTextProvider = CLKTimeTextProvider(date: date1 as! NSDate)
            let template = CLKComplicationTemplateModularLargeStandardBody()

            template.headerTextProvider = headerTextProvider
            template.body1TextProvider = body1TextProvider
            template.body2TextProvider = timeTextProvider

            switch complication.family {
            case .ModularLarge:
                let timelineEntry = CLKComplicationTimelineEntry(date: date1 as! NSDate, complicationTemplate: template)
                entries.append(timelineEntry)
            // …
}

    func requestedUpdateDidBegin() {
        let server=CLKComplicationServer.sharedInstance()
        for comp in (server.activeComplications) {
            server.reloadTimelineForComplication(comp)
        }
    }

This is the flow of the data:
transferCurrentComplicationUserInfo passes data to the Watch ExtensionDelegate wherein the data is saved in NSUserDefaults. ComplicationController then pulls its initial data from NSUserDefaults.

A: At first glance:

*

*This doesn't appear to be working code, as you'd be seeing a lot of Xcode fix-it errors about "Unicode curly quote found, ...".

*Please avoid force downcasting with as! as it can fail and your code will crash. You've got lots of unnecessary type casting taking place. As I mentioned before, you should be typing your variables to allow the compiler to catch any programmer errors.
For example, if your dictionary's keys and values are both strings, then safely type it as:
var playoffs: [String: String]

*Your extension delegate code may conditionally fail, if the as? downcast is not possible (because you passed something different than what you expected to receive). Make sure you're passing the types of values that you expect, or that whole block won't run.  You can easily check that in the debugger by setting a breakpoint and stepping through that code.
You also need to explicitly update your complication, once the info is received.
func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]) {
    if let ... { // Retrieve values from dictionary

        // Update complication
        let complicationServer = CLKComplicationServer.sharedInstance()
        guard let activeComplications = complicationServer.activeComplications else { // watchOS 2.2
            return
        }

        for complication in activeComplications {
            complicationServer.reloadTimelineForComplication(complication)
        }
    }
}

*It's really convoluted what you're doing with the arrays and NSUserDefaults. While it's perfectly appropriate to persist data between launches, NSUserDefaults is never meant to be a way to "pass" details from one part of your code to another.
Your complication data source should get its data from a model or data manager, instead of from NSUserDefaults.

*The getCurrentTimelineEntryForComplication if let ... { } else { code makes no sense. If you didn't get an array of strings, what do you expect to do in the else block?
You can also prepare your data before the switch statement, to make your code more readable and compact, like so:
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
    // Call the handler with the current timeline entry

    let recentData = DataManager.sharedManager.complicationData ?? "???"

    let template: CLKComplicationTemplate?
    let simpleTextProvider = CLKSimpleTextProvider(text: recentData)

    switch complication.family {
    case .ModularLarge:
        let modularLargeTemplate = CLKComplicationTemplateModularLargeStandardBody()
        modularLargeTemplate.headerTextProvider = CLKSimpleTextProvider(text: "Update Complication", shortText: "Update")
        modularLargeTemplate.body1TextProvider = simpleTextProvider
        template = modularLargeTemplate
    case .UtilitarianLarge:
        let utilitarianLargeTemplate = CLKComplicationTemplateUtilitarianLargeFlat()
        utilitarianLargeTemplate.textProvider = simpleTextProvider
        template = utilitarianLargeTemplate
    case .CircularSmall:
        let circularSmallTemplate = CLKComplicationTemplateCircularSmallSimpleText()
        circularSmallTemplate.textProvider = simpleTextProvider
        template = circularSmallTemplate
    case .ModularSmall:
        let modularSmallTemplate = CLKComplicationTemplateModularSmallSimpleText()
        modularSmallTemplate.textProvider = simpleTextProvider
        template = modularSmallTemplate
    case .UtilitarianSmall:
        let utilitarianSmallTemplate = CLKComplicationTemplateUtilitarianSmallFlat()
        utilitarianSmallTemplate.textProvider = simpleTextProvider
        template = utilitarianSmallTemplate
    }
    let timelineEntry = CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: template!)
    handler(timelineEntry)
}

The likely issue is that ClockKit asked for complication data, well before your extension even received it, so your complication data source had no data to provide, and no entries appear.
Even though something happens to work on the simulator, it doesn't mean your code is robust to also work on the actual device. There are all sorts of differences that can account for why it won't work on the real hardware, which is why you absolutely need to debug interactively on the device. It will help you realize why your code isn't working as intended.
Ideally, you should be doing this type of interactive debugging and solving those other issues before coming here, so you can ask a very specific question with a minimal working block of code. Questions which require someone to broadly debug your code really aren't useful to others in general.


text:
Q: Android Studio XML error "Corresponding method handler not found" on onClick Why do I get error "Corresponding method handler not found" on the XML onClick line, after naming the onClick in XML and calling it on Main Activity?
Snippet from activity_main.xml:
        <Button
            android:id="@+id/buPercentage"
            android:layout_width="30pt"
            android:layout_height="30pt"
            android:layout_weight="1"
            android:background="@color/lightgray"
            android:onClick="buPercentageEvent" //Error says Corresponding method handler not found
            android:text="%"
            android:textSize="18sp" />

Snippet from MainActivity.kt
fun buPercentageEvent()
{
    val convertToDecimal = displayText.text.toString()
    val newNumber = convertToDecimal.toDouble() / 100
    displayText.setText(newNumber.toString())
}

A: Do this
fun test(view: View){
        Log.e("Click","Yes")
    }

This will work.


text:
Q: Copying an array to another array as reversed and display in Assembly I am trying to copy an array to another array, but the order of elements should be reversed and displayed. My program file compiles but does not run and causes a Windows stop error each time (Windows dialog box).
I'm not sure what I'm doing wrong. Please advise.
INCLUDE Irvine32.inc

.data
sarray DWORD 500h, 400h, 300h, 200h, 100h
darray DWORD 5 DUP(?)

.code
main PROC

    mov eax, 0
    mov esi, OFFSET sarray ;move first element address to esi
    mov edi, OFFSET darray + SIZEOF darray - TYPE darray  ;move last element address to edi
    mov ecx, LENGTHOF sarray  ;sets the counter in the reverseLoop

  reverseLoop:
    mov eax,sarray[esi]     ;move 1st sarray element to eax
    mov darray[edi],eax     ;move 1st sarray element as last element on darray
    call WriteInt
    call Crlf
    add esi, TYPE sarray
    sub edi, TYPE darray
    call WriteInt
    loop reverseLoop

    exit
main ENDP

END main

Edit: My problem was that esi and edi had the address already added (OFFSET sarray) but in the loop I added the start again (mov eax, sarray[esi]).
After the fix, I had to add another loop to print the second darray (new one)

A: My problem was that esi and edi with the address already added OFFSET sarray, but in the loop I added the start again (mov eax, sarray[esi]).
After fixing this, I also had to add another loop to print the second array (the reversed one).
Here is the working code:
INCLUDE Irvine32.inc

.data
sarray DWORD 500h, 400h, 300h, 200h, 100h
darray DWORD 5 DUP(?)

.code
main PROC

    mov esi, OFFSET sarray                                ;move first element address to esi
    mov edi, OFFSET darray + SIZEOF darray - TYPE darray  ;move last element address to edi
    mov ecx, LENGTHOF sarray                              ;sets the counter in the reverseLoop

reverseLoop:
    mov eax,[esi]       ;move 1st sarray element to eax
    mov [edi],eax       ;move 1st sarray element as last element to the darray
    add esi, TYPE sarray
    sub edi, TYPE darray
    loop reverseLoop
    call clrscr

    mov esi, OFFSET darray
    mov ecx, LENGTHOF darray
    mov ebx, 0

printerLoop:
    mov eax,[esi]
    call WriteHex
    call Crlf
    add esi, TYPE darray
    loop printerLoop

    call Crlf

    exit
main ENDP

END main


text:
Q: Accessing USB Smart Card data from a browser I am building an enterprise browser based application, which works on a dedicated PC with a touch screen (think of it as a Kiosk, sort of). So, the application itself is built on NodeJS and the user makes choices on the browser and inserts their Smart Card. Since JavaScript can't directly read and decrypt the Smart Card data, a Java program running on this PC detects the inserted Smart Card and reads the data. Now, the problem is to send this Smart Card details (name, address etc..) to the JS code. I'm not really sure how to solve this, the following are a few ideas:

*

*The Java Smart Card reader, after reading the data, outputs it to as a keyboard input. The JS code then listens to this specific keyboard event and reads all the data. Kind of like how a bar-code scanner works.

*The Java Smart Card reader and the browser are connected to a cloud and have a WebSocket channel established. The Java program after reading the data, pushes it to the cloud server and the cloud server then pushes it to the Browser via WebSockets.

*Run the Java Smart Card reader as a web-server (localhost) with a self-signed SSL certificate. Add a local domain name to the server in the hosts file. Now, the browser can directly talk to the Java web-server through a Http API.

*Run the Java Smart Card reader with gRPC (localhost) and connect the browser to it via gRPC-web. (I have no experience in gRPC, but maybe this is possible?)

Each of the above have their own pitfalls. I'm not sure how other Kiosk based systems work, so any suggestions or improvements on the above ideas would be great.

A: The best solution here would probably be to host a WebSocket using Jetty in your java application at 127.0.0.1 and have your javascript connect to that directly. No cloud server would be needed as WebSockets aren't bound to the same origin policy or cross origin resource sharing.
Another potential solution is to have an embedded browser in your java program using javafx's webkit or other java browser implementation and share data through that. This is less than ideal because javafx's webkit has it's own weird quirks and commercial embedded browsers for java cost thousands.
I would use the websocket solution.


text:
Q: Parametric equation for cylindrical surface I have the following problem:

A cylindrical surface is given partially by its directrix: $(x,y)=\bigg(u-\sin(u),1-\cos(u)\bigg),u\in[0,4\pi]$ and partially by $z\in[0,y]$.
Determine a parametric equation, $r(u,v)$, for the surface, such that the normal vector, $N=r'_u \times r'_v$ is pointing towards the positive y-direction, in the point $(\pi,2,1)$.

My solution
One parametric equation could be: $$r(u,v)=\bigg(u-\sin(u),1-\cos(u),v \bigg),u\in[0,4\pi] \; v\in[0,y] $$
Finding the normal vector we get: $N=\begin{bmatrix} 1-\cos(u)\\\sin(u)\\0 \end{bmatrix}\times \begin{bmatrix}0\\0\\1 \end{bmatrix}=\begin{bmatrix} \sin(u)\\ \cos(u)-1\\0 \end{bmatrix}$
Inserting the values of $u$ and $v$ corresponding to the point $(\pi,2,1)$ we find the normal vector to be:
$$N(\pi,1)=\begin{bmatrix} 0\\-2\\0 \end{bmatrix} $$
However, this doesn't satisfy the requirement that the normal vector should point towards the positive y-direction. Can anybody spot a mistake, or help me with this problem?


text:
Q: Does WKC have its own version, or is it just CP4D's version? I can't find a WKC specific version in the IBM docs. Does WKC have its own versioning, or is it just (lite/full) version for a specific version of Cloud Pak 4 Data?

A: The version of services are related to the version of CPD.  Under the covers, the service is a collection of microservices which are versioned.  But that should be transparent to end users.


text:
Q: python opencv: cannot capture a window Sorry I paste mirror parts at worng place, and as frame is null during mirror part, I made it into a comment while running
Looks like my cap.read() can't read anything
This is really a simple python code of opencv for just capturing a window and make webcamera work. But when I ran it, no window shown but no bugs shown either. How can I know what's wrong readily?
How can I know if the webcamera is 0 or sth else?
Why the mirror part doesn't work?
Could someone recommend me some good examples for opencv on python?
Thank you!!
import cv2

def capture_camera(mirror=True, size=None):
    cap = cv2.VideoCapture(0)

    while True:
        ret, frame = cap.read()
        #if mirror is True:
            #frame = frame[:,::-1]
        if size is not None and len(size) == 200:
            frame = cv2.resize(frame, size)
            cv2.imshow('camera capture', frame)
            k = cv2.waitKey(100)
            if k == 27:
                break
    cap.release()
    cv2.destroyAllWindows()

capture_camera()

A: Your code is not executiong below if statement
    if size is not None and len(size) == 200:

because size is tuple and len(size) will return 2 since you defined
     size = (800,600)

2nd mistake : you were changing frame array before it is initialized.
first you need to get frame array which is returned by cap.read() then you can check if mirror is True if yes then reverse the array by frame = frame[:,::-1]
try this code  :
import cv2

def capture_camera(mirror=True, size=None):
    cap = cv2.VideoCapture(0)

    while True:
        ret, frame = cap.read()
        if mirror is True:
           frame = frame[:,::-1]

        size = (800,600)
        if size is not None:
            frame = cv2.resize(frame, size)
            cv2.imshow('camera capture', frame)
            k = cv2.waitKey(100)
            if k == 27:
                break
    cap.release()
    cv2.destroyAllWindows()

capture_camera()

A: Try this code. It works for me:
import cv2

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    cv2.imshow('Webcam (close with q)' ,frame)

    if(cv2.waitKey(1) & 0xFF == ord('q')):
       break

cap.release()
cv2.destroyAllWindows()

BTW:
Your code throws an error:
Traceback (most recent call last):
File "C:/Python/Scripts/OpenCV/Scripts/so_test.py", line 21, in <module>
capture_camera()
File "C:/Python/Scripts/OpenCV/Scripts/so_test.py", line 7, in capture_camera
frame = frame[:,::-1]
UnboundLocalError: local variable 'frame' referenced before assignment


text:
Q: Java - How to get the default font size of a JTextPane I have a JTextPane, and I'm trying to get the default font size of the JTextPane.
I've tried looking for methods such as getFontSize() and getTextSize(), but none seem to exist. I'm clearly missing something, so can anyone help out with this?

A: I think you want:
int size = yourTextPane.getFont().getSize();

Or even more generic:
Font defaultFont = UIManager.getDefaults().getFont("TextPane.font");
int defaultSize = defaultFont.getSize();


text:
Q: Spring Integration Channels on Content I have used Spring Integration in my current successfully for some of the needs. Awesome..
There is some weird behavior observed on a heavy load  where-in the same message seems to be processed more than once. I can confirm that because there are multiple rows in the database which is typically the last command on the chain that is configured over the channel.
Digging into the manual further, it looks seems like load-balancing is done automatically by spring. The manual says that the message is balanced between multiple message handlers.
Question is:

*

*How many handlers are present on a channel by default? The spring XML that gets loaded does not seem to have that configuration. All i do is this (per the recommendation in the manual):

<int:channel id="SwPath.Channel"/>
<int:chain id="SwPath.chain" input-channel="SwPath.Channel">
</int:chain>

I can disable the fail-over but I am curious to know how many are present by default.

A: It's been a while since I worked on those load balancers, but I remember that the default number of threads in the thread pool was somewhere between 2 and 10.
It is possible that you have found a concurrency bug.
If you turn on TRACE logging the load balancer will give you a lot of information, but that could easily hide the problem.
If you would create a JIRA issue with a JUnit test case, I'm sure it would be much easier to figure out what happens exactly.


text:
Q: Trigger on calculated date on Google AppMaker I have function called alertnotice(to, message, body) that will be executed on a user onClick() event. The function will execute sendEmail(to, message, body) to send the email base on a calculated trigger as in variable triggerDay such as below:
function alertnotice(to, subject, body, dueDate, notifyBeforeDay) {//start of this class

  function sendEmail(to, subject, body){
    try {
      MailApp.sendEmail({
        to: to,
        subject: subject,
        htmlBody: body
      });
    } catch(e) {
      console.error(JSON.stringify(e));
    }
  }

  //check if there is an existing trigger for this process
  var existingTrigger = PropertiesService.getScriptProperties().getProperty("sendEmailTrigger");

  //set the renewal notice day
  var triggerDay = (dueDate - notifyBeforeDay) / (1000*60*60*24);

  //if the trigger already exists, inform user about it
  if(existingTrigger) {

    return "Alert notice had been sent";

  } else { // if the trigger does not exists, continue to set the trigger to send alert notice

    //runs the script every day at 1am on the time zone specified
    var newTrigger = ScriptApp.newTrigger('sendEmail')
    .timeBased()
    .atTime(triggerDay)
    .create();

    var triggerId = newTrigger.getUniqueId();

    if(triggerId) {
      PropertiesService.getScriptProperties().setProperty("autoExportTrigger", triggerId);
      return "Alert notice send successfully!";
    } else {
      return "Failed to send alert notice. Try again please";
    }
 }

}//end of this class

So for example, if the dueDate is 30/07/2018 and the notifyBeforeDay = 30, the function should send the email 30 days before the due date. I tried to achieve that but not so sure whether my algorithm will work. Can anyone give advice on this?

A: This implementation looks fragile to me. I would rather go with single trigger to avoid any possible duplicated emails and ensure at least one. Smth like this:
// I am server script, trigger me on schedule (for instance nightly)
function sendAlerts() {
  var query = app.models.Customers.newQuery();

  // query only for non-notified customers with upcoming due date
  query.filters.NorificationAttempts._lessThan = ATTEMPTS_THRESHOLD;
  query.filters.Notified._equals = false;
  query.filters.DueDate._lessThan = <dueDate>;

  var customers = query.run();

  customers.forEach(function(customer) {
    var success = sendNotification(customer);

    if (success) {
      customer.Notified = true;
    } else {
      customer.NorificationAttempts++;
    }

    // performance trade off in favor of consistency
    app.saveRecords([customer]);
  });
}

Trigger for such script can be installed by app's admin, you can find similar implementation in People Skills template.


text:
Q: Client-side calls code-behind every 5 seconds in ASP.NET Web Form I'm creating a meteo page where the actual weather conditions are displayed.
For this I need a label to be updated every 5 seconds. I don't know if this is something that's possible with webforms, since I want to change its value after the page is loaded. I can load the initial value with the code in the page_LoadComplete event, but when I try to loop it, it doesn't update the label text.
Thanks
Code:
    public Wind Icarus = new Wind();

    public string degToCompass(double i)
    {...}

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void Page_LoadComplete(object sender, EventArgs e)
    {
        System.Timers.Timer aTimer = new System.Timers.Timer();
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Interval = 5000;
        aTimer.Enabled = true;
    }

    protected void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        string[] metingen = IcarusFTP.GetTXT();
        Icarus.Gust = Decimal.Parse(metingen[4], CultureInfo.InvariantCulture);
        Icarus.Speed = Decimal.Parse(metingen[6], CultureInfo.InvariantCulture);
        Icarus.Dir = Int32.Parse(metingen[7]);
        labelSpeed3.Text enter code here= Icarus.Speed.ToString();
        labelGust3.Text = "Gust: " + Icarus.Gust.ToString();
        labelDir3A.Text = degToCompass(Icarus.Dir);
        labelDir3B.Text = Icarus.Dir.ToString()+ "°";
    }
}

HTML inside a table cell:
<asp:label id="labelSpeed3" runat="server"></asp:label>

<asp:label id="labelGust3" runat="server"></asp:label>

A: This can be best handled through AJAX call from the client side. Or if you want it to be done in the ASP.NET Webforms way - try making a  __doPostBack() call with appropriate eventArgs in the second params.
Still, AJAX would be the way to go.

A: The easiest way is to use Ajax (not ASP.NET Ajax) and call WebMethod from code-behind.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Sample.aspx.cs"
   Inherits="AspNetWebForm.Sample" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

        <asp:Label runat="server" ID="CurrentDateLabel" />

    </form>

Code Behind
using System;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace AspNetWebForm
{
    public partial class Sample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Initialize date if you want to
                CurrentDateLabel.Text = DateTime.Now.ToString("hh-mm-ss");
            }
        }

        [WebMethod]
        public static string GetCurrentDate()
        {
            return new JavaScriptSerializer().Serialize(DateTime.Now.ToString("hh-mm-ss"));
        }
    }
}


text:
Q: ADO.NET Не удается подключиться к БД MS SQL Server Есть БД, в консольном приложении C# пытаюсь плодключиться к БД и считать содержимое таблицы следующим образом:
string cs= @"Data Source=.\SQLEXPRESS;Initial Catalog=ShopDB;Integrated Security=True;";
string command = "SELECT * FROM Customers";

DataTable customers = new DataTable();

using (SqlConnection connection = new SqlConnection(cs))
{
    connection.Open();
    SqlCommand cmd = new SqlCommand(command, connection);
    SqlDataReader dr = cmd.ExecuteReader();
    customers.Load(dr);
    dr.Close();
}

При попытке открытия соединения получаю ошибку
System.Data.SqlClient.SqlException: 'Cannot open database "ShopDB" requested by the login. The login failed.
Login failed for user 'MicrosoftAccount\mail@yahoo.com'.'

Использую БД MS SQL Server Express 2016, ОС Windows 10, VS 2017.
В БД Метод аутентификации выбран Windows Authentication.
При попытке указать в строке подключения имя пользователя, которое отображается при подключении к БД (в неактивных полях) и пароль, который соответствует этому пользователю, появляется ошибка
System.Data.SqlClient.SqlException: 'Login failed for user 'DESCTOP-5HGPGMV\username'.'

Подскажите, пожалуйста, в чем ошибка.

A: В вашей строке подключения фигурирует Integrated Security=True. Это означает, что для подключения к SQL серверу будет использоваться логин пользователя, из-под которого запущена программа. Например, если программу запустит пользователь mydomain\Ivanov, то для подключения к MS SQL серверу будет использоваться логин mydomain\Ivanov, а если программу запустит mydomain\Petrov - то логин mydomain\Ivanov.

При попытке указать в строке подключения имя пользователя, которое отображается при подключении к БД (в неактивных полях) и пароль, который соответствует этому пользователю

Логин и пароль в строке подключения для этого режима вводить не надо!
Просто запустите sql server management studio и в Security - Logins убедитесь, что пользователь  DESCTOP-5HGPGMV\username есть в списке плюс имеет достаточные права к БД вашего приложения.

Альтернативно, вы можете убрать Integrated security и вот тогда вам будет необходимо указать и логин и пароль от какой-либо учётки SQL Server.
Для общего понимания можете почитать вот эти вопросы на so:

*

*Подключение к SQL Server на C# для чайника


text:
Q: "new songs with the authority that their old songs had..."
Q. On that tour, you performed a number of excellent songs you've still never released. I'm thinking of titles like Traces, Love-Art Blues and Pushed It Over The End. What happened to those songs?
A. Well they'll probably be out on the anthology too. Listen, if they'd had new songs with the authority that their old songs had, we could've knocked off four and five of mine so that just the best two surfaced... That would have truly been CSN&Y. But it wasn't to be, so the record never came out.

" if they'd had new songs with the authority that their old songs had, we could've knocked off four and five of mine so that just the best two surfaced..."
Hello, could anyone help me understand what he's saying above?
I don't understand what "with the authority" really means in this context.
Is he saying that if new songs were as good as their old ones, they would have put these new songs on the album instead of four or five of his songs?

A: Yes, that is what he's saying. The word authority has more to it, though.
In particular note definition 3b:

b: convincing force
lent authority to the performance

see
[1]: https://www.merriam-webster.com/dictionary/authority


text:
Q: Find the determinent of a $4 \times 4$ matrix with the letter $a$ in it Any idea how to compute the determinant of $4 \times 4$ matrix $A$ when
\begin{equation}
A = \begin{bmatrix} 1 & 4 & 8 & 1\\ 0 & 30 & 1 & 0 \\ 0 & 2 & 0 & 0 \\ 1 & 2 & 9 & a \end{bmatrix}.
\end{equation}
The $a$ in the $A_{44}$ location is really confusing me!

A: Just expand across the third row, as @Surb suggested:
\begin{equation}
|A| = -2 \left|
\begin{pmatrix}
1 & 8 & 1\\
0 & 1 & 0 \\
1 & 9 & a
\end{pmatrix} \right|
=-2 \left|
\begin{pmatrix}
1 & 1 \\ 1 & a
\end{pmatrix} \right| = -2(a - 1) = 2 - 2a.
\end{equation}
Another option is to expand down the fourth column:
\begin{align}
| A| &=
-1 \left|\begin{pmatrix} 0 & 30 & 1 \\ 0 & 2 & 0 \\ 1 & 2 & 9 \end{pmatrix} \right| + a \left |
\begin{pmatrix} 1 & 4 & 8 \\ 0 & 30 & 1 \\ 0 & 2 & 0 \end{pmatrix} \right |.
\end{align}
The two determinants on the right simplify greatly by expanding down the first column:
\begin{equation}
\left|\begin{pmatrix} 0 & 30 & 1 \\ 0 & 2 & 0 \\ 1 & 2 & 9 \end{pmatrix} \right|
= 1\left| \begin{pmatrix} 30 & 1 \\ 2 & 0 \end{pmatrix} \right| = -2
\end{equation}
and
\begin{equation}
\left |
\begin{pmatrix} 1 & 4 & 8 \\ 0 & 30 & 1 \\ 0 & 2 & 0 \end{pmatrix} \right |
= 1 \left| \begin{pmatrix} 30 & 1 \\ 2 & 0 \end{pmatrix} \right| = -2.
\end{equation}
So we see that $|A| = 2 - 2a$.

A: In your case, the determinant of A is a function of a.
Here is how to solve 4x4 matrix
https://www.sophia.org/tutorials/finding-the-determinant-of-a-4x4-matrix--5
but when you encounter a, you should keep it untouched. You can still use basic algebra to keep equations simple. For example, (3*a + 4) + (4*a + 5) = 7a+9 etc.
Here is Maple doing the calculation for you:

with(LinearAlgebra):
    M:=Matrix(4,[[1,4,8,1],[0,30,1,0],[0,2,0,0],[1,2,9,a]]);
    Determinant(M);
        -2 a + 2

What you actually need to calculate in general case of 4x4 matrices is:
M:=Matrix(4,[[a11,a12,a13,a14],[a21,a22,a23,a24],[a31,a32,a33,a34],[a41,a42,a43,a44]]);
Determinant(M);

which yields:
a11 a22 a33 a44 - a11 a22 a34 a43 - a11 a23 a32 a44 + a11 a23 a34 a42 + a11 a24 a32 a43 - a11 a24 a33 a42 - a12 a21 a33 a44 + a12 a21 a34 a43 + a12 a23 a31 a44 - a12 a23 a34 a41 - a12 a24 a31 a43 + a12 a24 a33 a41 + a13 a21 a32 a44 - a13 a21 a34 a42 - a13 a22 a31 a44 + a13 a22 a34 a41 + a13 a24 a31 a42 - a13 a24 a32 a41 - a14 a21 a32 a43 + a14 a21 a33 a42 + a14 a22 a31 a43 - a14 a22 a33 a41 - a14 a23 a31 a42 + a14 a23 a32 a41

here you can see this rule
https://en.wikipedia.org/wiki/Determinant#n.C2.A0.C3.97.C2.A0n_matrices
used.


text:
Q: ¿Actualizar la vista en Angular 5? Estoy usando un metodo que me borra los archivos de la base de datos pinchando en la papelera cuando pincho me los borra pero en la vista no se me actualiza si no hago f5 en el navegador como podría hacer esto sin tener que actualizar la pagina
import { Component,DoCheck } from '@angular/core';
import { Http } from '@angular/http'
import {HttpClient} from '@angular/common/http';
import {LoginService} from '../api/login/login.service';

@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css'],
providers:[LoginService]
})
export class MainComponent implements DoCheck {

public archivo;

constructor(private _http: HttpClient,
public _servicio:LoginService) {

}

borrar(archivo){

console.log(archivo);

this._servicio.borrararchivos(archivo).subscribe(data => {

}, error => {

console.log('error');

});

 }

aqui esta mi aplicacion como veis me borra el objeto pero no se actualiza ni me lo borra en la vista

y mi servicio es el siguiente
 borrararchivos(id): Observable<any>{

 const url = `http://localhost/api/public/delete/${id}`;

 let headers = new HttpHeaders().set('token',this.token);

 return this._http.delete(url,{headers:headers});

 }

A: Según lo que muestras, tienes en tu componente una variable archivo que es la que se muestra en la vista, entonces con esto seria suficiente:
borrar(archivo){
  console.log(archivo);
  this._servicio.borrararchivos(archivo).subscribe(data => {
    this.archivo = null;
// Haces null la variable de tu archivo, también puede ser {} (Objeto vació)
  }, error => {
    console.log('error');
  });

}

Recuerda que this.archivo = null;, hace referencia a la variable archivo en tu component, no la que te llega como parámetro ya que en un futuro podrías tener una lista de elementos y tendrías que eliminar el elemento (llamado archivo aquí) de dentro de la lista del component.

Recuerda que Angular vincula tus variables directamente a la vista y refleja sus cambios de forma automática, por la tanto siempre que modifiques tus variables esto se va a ver reflejado en la vista y no tenes que hacer F5.


text:
Q: React Props with same type/ value and different types I have a following Text filed which has been created through Material-ui.
 <TextField
                  error = {this.props.projectNameErrorStatus}
                  required = {this.props.projectNameRequiredStatus}
                  className={classes.textField}
                  margin="normal"
                  id="projectName"
                  name="projectName"

                />

However, I have 4 different TextFields which I am going to set error props to them with different name that take state of parent container. this issue will force me to have 8 different props and state's names. this will make my code larger and less readable.
For example I have to initiate state:
state = {
projectNameErrorStatus :true,
NameErrorStatus :true,
FamilyErrorStatus :true,
EmailErrorStatus :true,
projectNameRequiredStatus: true,
NameRequiredStatus: true,
FamilyRequiredStatus: true,
EmailRequiredStatus: true,

}

state = {this.state}

and then pass them as props to child component. After that I should use all them as props in.
let {

state = {
projectNameErrorStatus,
NameErrorStatus,
FamilyErrorStatus,
EmailErrorStatus,
projectNameRequiredStatus,
NameRequiredStatus,
FamilyRequiredStatus,
EmailRequiredStatus

} = this.props.state

Can I have these props and state in a more cleaner and efficien way?

A: Split it in two Components and use json objects:
    import React from 'react';

class customTextfield extends Component {

    render() {
        return (
            <TextField
                error={this.props.ErrorStatus}
                required={this.props.RequiredStatus}
                className={classes.textField}
                margin="normal"
                id={this.props.Name}
                name={this.props.Name}
                label={this.props.Label} />
        );
    }

}

class parentContainer extends Component {

    constructor(props) {
        super(props);

        this.state = {
            ErrorStatus = {
                Name: true,
                Email: false,
                Project: false,
                Family: false
            },
            RequiredStatus = {
                Name: true,
                Email: true,
                Project: true,
                Family: false
            },
            listOfTextFields =["Name", "Email", "Project", "Family"]
        }
    }

    render() {
        return this.state.listOfTextFields.map(field => <customTextfield Name={field} Label={field} ErrorStatus={this.state.ErrorStatus[field]} RequiredStatus={this.state.RequiredStatus[field]} />)
    };
}


text:
Q: How to write a document on cyrillic? I tried the instructions from the how to solve the problem reference link, but it doesn't work. I installed package as well and I really can't find a way to write my documents in Cyrillic.
What should I do/write in order to use this font_

A: Always compiling with pdfLaTeX:

\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T2A]{fontenc}
\usepackage[russian]{babel}
\begin{document}

Я не знаю, имеет ли этот перевод смысл на русском языке.

\end{document}

\documentclass{article}
\usepackage[T2A,OT1]{fontenc}
\usepackage[utf8]{inputenc}
\newcommand\cyrtext[1]{{\fontencoding{T2A}\selectfont #1}}
\begin{document}

\cyrtext{ДёжзКклЪЩЧщ}
\end{document}

or
\documentclass{article}
\usepackage[T2A]{fontenc}
\usepackage[utf8]{inputenc}
\begin{document}
ФЦцшыЭЮЯноОН
\end{document}

A: Serbian is no different from other languages except that it can be written with two scripts, Cyrillic and Latin.
The documentation for babel-serbianc (the c stands for Cyrillic) has a sample document in the report class, but the setup should work for any class.
\documentclass{report}
\usepackage[serbianc]{babel}

\title{Пример ћирилично-latiničnog документа}
\author{Филип Брчић <brcha@users.sourceforge.net>}

\begin{document}

\maketitle

\chapter{Азбука}

А Б В Г Д Ђ Е Ж З И Ј К Л Љ М Н Њ О П Р С Т Ћ У Ф Х Ц Ч Џ Ш

а б в г д ђ е ж з и ј к л љ м н њ о п р с т ћ у ф х ц ч џ ш

\chapter{Abeceda}

A B C Č Ć D Dž Đ E F G H I J K L Lj M N Nj O P R S Š T U V Z Ž

a b c č ć d dž đ e f g h i j k l lj m n nj o p r s š t u v z ž

\end{document}

Title page

First chapter


text:
Q: LINQ to SQL architecture. What is best? This question is sort of a pool. We are trying to identify the best archtecture while using a ORM like LINQ to SQL. The archture we are defining is for sort of framework that other applications will access either trough directly referencing the DLL or through a webservice. We have .NET apps and PHP apps.
The possibilities are:
Multiple data contexts: Separting the database into units of work and create separate contexts for each one.
Pros:

*

*Easy of use

*Classes will be broken into different namespaces

*Smaller domain to maintain

Cons:

*

*Objects have to be duplicated if
related, creating maintenance hell

*Objects cannot be passed between context, creating the need for another hit on the data base

Single data context: All tables, views, procedures, reside in the same huge context.
Pros:

*

*No duplication

*Relationships are easy to manage, basicaly the LINQ takes care of it.

*Better performance, less hits on the DB.

Cons:

*

*All tables are in the same namespace, code completion becomes nuts

*Not the best for the designer (at least on VS2008)

*Cannot be selective in what to save and what not. Save all, or delete all mode.

Well this are things that came up to my mind, so if have any other pros or cons, please tell me and I will include them in the post. Also pick your best one.
Thanks all

A: I understand your doubts. I had the same when I started to use LinqToSql. To help me find the better way I started to create a personal project where I could test all approaches without the worry and without preconception.
During this exercise I found that the only one context approach is the most useful. This solution appears to be easier to maintain and if you need to recreate the domain you will manage only one file in only one project.
Other aspect I realized during the exercise is that use the LinqToSql directly is not efficient in the terms of organization. If you have a project where a team will execute the development instead of only one person you should "shield" the LinqToSql from them. There should be a "sheriff" who will handle with the domain and you also should use some abstraction mechanism to protect the model from abusing (I implemented a Repository pattern and it worked well but you could find different approaches).
I also faced the problem of creating some logical groups inside the domain. Well in the true what I did was to use some DDD (Domain Driven Design) techniques to create what is called aggregates. Aggregates are a logical arrangement of entities inside a domain where you have a root entity (that works as an aggregator) and several other satellites entities related between them. You can do this creating some new entities in the LinqToSql domain. These new entities will be disconnected from the database and will work as aggregators. This approach will enable you to create "sub-domains" inside your domain and help you to have a better design.
In the end I realized that the best way to use LinqToSql is to take the context like a simple DAL. Reuse its domain, with some extensions (where we can use T4 to help us to create the code), where the entities are transformed into DTOs (Data Transfer Objects) to expose the data to the other layers.
I am publishing (it's not finished yet) the steps I took during the exercise in my blog: http://developmentnirvana.blogspot.com/

A: In my view, the data-context hides squarely behind a repository interface - allowing us to swap the implementation if we like (LINQ-to-SQL / EF / NHibernate / LLBLGen / etc). As such, the specifics of the data-context(s) are largely an implementation detail. As long as it passes the unit tests ;-p
Huge is rarely a good idea; tiny is rarely useful... I tend to break the sytem down into related chunks (normally related to different repository interfaces), and think of it at that level. I have some other thoughts here: Pragmatic LINQ - although I'd happily defer to any wisdom from Frans etc.

A: There are two more things to consider about using LINQ to SQL:

*

*While it's not obsolete, Microsoft have stated that the focus for future development will be Entity Framework, not LINQ to SQL

*LINQ to SQL ties you directly to the structure of your database. If you use Entity Framework, you'll be able to design your entities in a manner that is independent of your database implementation. For instance, if you decide to split one entity into two tables, your callers will not need to know.

A: So after about a year of development under multiple context, I learned that is not a good idea to use multiple contexts, the problem arrives when you have table that should really exist in 2 or more of the contexts, usually a many to many relationship.
What will happen is that the in the middle can only have a record inserted when the other 2 tables have their records inserted, so if you use L2S as you would use for other matters, that record will be created first with FKs equal to 0 (Zero), and that is invalid (Referential Integrity), which causes a error.
This is one of the inconvenient that I found but I could list a few more, if requested.
Now the solution I am using is to create a "Scheduler", this guys is responsible for waiting for certain conditions to be met (Both parents have a valid ID, different then 0 (Zero)), then it inserts, this is done very generically to allow as many specializations as I need (I have 6 Contexts), and it uses the PropertyChanged event to as a way to notify the changes to the scheduler.
So the most important thing in this post is, USE A SINGLE CONTEXT, that if you don't like having headaches ( I don't at all). Then after all that said someone might ask, why I went on with the multiple Contexts, well, lets say it was a decision that came from above me, and I had zero power to fight back. ( All though I really tried, hard )


text:
Q: SQLAlchemy Join on Temporary Literal Text Column I'm new to SQLAlchemy and having trouble figuring out how to get the type of result back that I want.
I have a list of values outside of SQL, e.g. ['A', 'B', 'C', 'D'] that I'm querying against.  I want to display a result that includes all of those list values even if nothing is returned from the SQL query for certain values.  So if SQL returns:
___________________________
A | 23423.32
---------------------------
D | 3523.0

I would want the result to look like:
___________________________
A | 23423.32
---------------------------
B | None
---------------------------
C | None
---------------------------
D | 3523.0

I've been trying to use something like this (although it hasn't been working):
subquery = select([list_vals]).as_scalar().subquery()
session.query(subquery.c.MY_COLUMN,query_results.MY_COLUMN).outerjoin(query_results, query_results.MY_COLUMN == subquery.c.MY_COLUMN)

to somehow create a literal column and join with the actual query results but have not been able to get it to work. It's an Oracle database if that is helpful.


text:
Q: Max in a list with two conditions I have a list in Python in which each element is a tuple like this:
(attr1, attr2, attr3)

I want to find the tuple that has the largest attr2, but that have attr3 >= 100.
What is the pythonic approach to this?

A: You have to both filter and use a key argument to max:
from operator import itemgetter

max(filter(lambda a: a[2] >= 100, yourlist), key=itemgetter(1))

The filter can also be expressed as a generator expression:
max((t for t in yourlist if t[2] >= 100), key=itemgetter(1))

Demo:
>>> yourlist = [(1, 2, 300), (2, 3, 400), (3, 6, 50)]
>>> max((t for t in yourlist if t[2] >= 100), key=itemgetter(1))
(2, 3, 400)
>>> max(filter(lambda a: a[2] >= 100, yourlist), key=itemgetter(1))
(2, 3, 400)

Note that because you filter, it's easy to end up with an empty list to pick the max from, so you may need to catch ValueErrors unless you need that exception to propagate up the call stack:
try:
    return max(filter(lambda a: a[2] >= 100, yourlist), key=itemgetter(1))
except ValueError:
    # Return a default
    return (0, 0, 0)

A: If you also want the index of the maximum value you could do:
 max(filter(lambda a: a[1][2] >= 100, enumerate(yourlist)), key=lambda x:x[1][1])`

although I have to admit that it gets a bit unreadable.


text:
Q: Creating a gallery within a screen window? I'm looking to create a simple UI to display the results of a project I've been working on. The simple display (upon which I'm hoping to build) is a splash screen which leads to gallery from which you can browse a number of .png files (graphs).
I'm looking to put this in my second screen (which at the moment is made up of two buttons.) I'm not looking for a complete solution from anybody, but some guidance would be appreciated. The idea would be that the second screen is linked to the directory containing the images, which can then be cycled through.
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen

# Create both screens. Please note the root.manager.current: this is how
# you can control the ScreenManager from kv. Each screen has by default a
# property manager that gives you the instance of the ScreenManager used.
Builder.load_string("""
<MenuScreen>:
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'collage.png'

    BoxLayout:
        padding: [100, 100, 100, 100]

        Button:
            text: 'Go to Gallery'
            on_press: root.manager.current = 'settings'
            size_hint: 0.1, 0.25
            pos_hint: {'center_x':.5, 'center_y':.2}

<GalleryScreen>:
    BoxLayout:
        Button:
            text: 'My settings button'
        Button:
            text: 'Back to menu'
            on_press: root.manager.current = 'menu'
""")

# Declare both screens
class MenuScreen(Screen):
    pass

class GalleryScreen(Screen):
    pass

# Create the screen manager
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(GalleryScreen(name='settings'))

class TestApp(App):

    def build(self):
         return sm

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

New to kivy, and under time constraints, which may explain the broad question, any help is appreciated.


text:
Q: Vuejs Component Not Rendering though registered I have a dropdown component called "MissionPlanner" in a single page component .vue file and I registered it in my App.vue file
App.vue
import MissionPlanner from "./MissionPlanner.vue";

export default {
  name: "app",
  components: {
      ...,
    "mission-planner": MissionPlanner
  }
...
<template>
   <mission-planner/>
</template

But when I tried to run the vue application, it is not showing my component at all. I do see the rest of my template html being rendered but not the dropdown component "mission-planner". I even tried changing the case for the "mission-planner" tag names to "MissionPlanner" but still nothing.
Also here is my main.js
new Vue({
  render: h => h(App),
  components: {
    "mission-planner": require("./MissionPlanner.vue")
  } //tried registering it globally but it is not working
}).$mount('#app')

Update:
ok looking closer at the console, i see several errors but not sure what they mean:
vue.runtime.esm.js?2b0e:619 [Vue warn]: Property or method "chosen" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

found in

---> <MissionPlanner> at src/MissionPlanner.vue
       <App> at src/App.vue
         <Root>
warn @ vue.runtime.esm.js?2b0e:619
warnNonPresent @ vue.runtime.esm.js?2b0e:2015
get @ vue.runtime.esm.js?2b0e:2070
eval @ MissionPlanner.vue?93e1:18
renderList @ vue.runtime.esm.js?2b0e:2630
render @ MissionPlanner.vue?93e1:16
Vue._render @ vue.runtime.esm.js?2b0e:3548
updateComponent @ vue.runtime.esm.js?2b0e:4066
get @ vue.runtime.esm.js?2b0e:4479
Watcher @ vue.runtime.esm.js?2b0e:4468
mountComponent @ vue.runtime.esm.js?2b0e:4073
Vue.$mount @ vue.runtime.esm.js?2b0e:8415
init @ vue.runtime.esm.js?2b0e:3118
createComponent @ vue.runtime.esm.js?2b0e:5978
createElm @ vue.runtime.esm.js?2b0e:5925
createChildren @ vue.runtime.esm.js?2b0e:6053
createElm @ vue.runtime.esm.js?2b0e:5954
patch @ vue.runtime.esm.js?2b0e:6477
Vue._update @ vue.runtime.esm.js?2b0e:3945
updateComponent @ vue.runtime.esm.js?2b0e:4066
get @ vue.runtime.esm.js?2b0e:4479
Watcher @ vue.runtime.esm.js?2b0e:4468
mountComponent @ vue.runtime.esm.js?2b0e:4073
Vue.$mount @ vue.runtime.esm.js?2b0e:8415
init @ vue.runtime.esm.js?2b0e:3118
createComponent @ vue.runtime.esm.js?2b0e:5978
createElm @ vue.runtime.esm.js?2b0e:5925
patch @ vue.runtime.esm.js?2b0e:6516
Vue._update @ vue.runtime.esm.js?2b0e:3945
updateComponent @ vue.runtime.esm.js?2b0e:4066
get @ vue.runtime.esm.js?2b0e:4479
Watcher @ vue.runtime.esm.js?2b0e:4468
mountComponent @ vue.runtime.esm.js?2b0e:4073
Vue.$mount @ vue.runtime.esm.js?2b0e:8415
eval @ main.js?56d7:8
./src/main.js @ app.js:1366
__webpack_require__ @ app.js:785
fn @ app.js:151
1 @ app.js:1379
__webpack_require__ @ app.js:785
checkDeferredModules @ app.js:46
(anonymous) @ app.js:861
(anonymous) @ app.js:864
Show 13 more frames
vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot use 'in' operator to search for '#<Object>' in NaN"

found in

---> <MissionPlanner> at src/MissionPlanner.vue
       <App> at src/App.vue
         <Root>
warn @ vue.runtime.esm.js?2b0e:619
logError @ vue.runtime.esm.js?2b0e:1884
globalHandleError @ vue.runtime.esm.js?2b0e:1879
handleError @ vue.runtime.esm.js?2b0e:1839
Vue._render @ vue.runtime.esm.js?2b0e:3550
updateComponent @ vue.runtime.esm.js?2b0e:4066
get @ vue.runtime.esm.js?2b0e:4479
Watcher @ vue.runtime.esm.js?2b0e:4468
mountComponent @ vue.runtime.esm.js?2b0e:4073
Vue.$mount @ vue.runtime.esm.js?2b0e:8415
init @ vue.runtime.esm.js?2b0e:3118
createComponent @ vue.runtime.esm.js?2b0e:5978
createElm @ vue.runtime.esm.js?2b0e:5925
createChildren @ vue.runtime.esm.js?2b0e:6053
createElm @ vue.runtime.esm.js?2b0e:5954
patch @ vue.runtime.esm.js?2b0e:6477
Vue._update @ vue.runtime.esm.js?2b0e:3945
updateComponent @ vue.runtime.esm.js?2b0e:4066
get @ vue.runtime.esm.js?2b0e:4479
Watcher @ vue.runtime.esm.js?2b0e:4468
mountComponent @ vue.runtime.esm.js?2b0e:4073
Vue.$mount @ vue.runtime.esm.js?2b0e:8415
init @ vue.runtime.esm.js?2b0e:3118
createComponent @ vue.runtime.esm.js?2b0e:5978
createElm @ vue.runtime.esm.js?2b0e:5925
patch @ vue.runtime.esm.js?2b0e:6516
Vue._update @ vue.runtime.esm.js?2b0e:3945
updateComponent @ vue.runtime.esm.js?2b0e:4066
get @ vue.runtime.esm.js?2b0e:4479
Watcher @ vue.runtime.esm.js?2b0e:4468
mountComponent @ vue.runtime.esm.js?2b0e:4073
Vue.$mount @ vue.runtime.esm.js?2b0e:8415
eval @ main.js?56d7:8
./src/main.js @ app.js:1366
__webpack_require__ @ app.js:785
fn @ app.js:151
1 @ app.js:1379
__webpack_require__ @ app.js:785
checkDeferredModules @ app.js:46
(anonymous) @ app.js:861
(anonymous) @ app.js:864
Show 11 more frames
vue.runtime.esm.js?2b0e:1888 TypeError: Cannot use 'in' operator to search for '#<Object>' in NaN
    at eval (eval at ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"aeb9565a-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/MissionPlanner.vue?vue&type=template&id=e2c8c042&scoped=true& (app.js:946), <anonymous>:21:20)
    at Proxy.renderList (vue.runtime.esm.js?2b0e:2630)
    at Proxy.render (eval at ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"aeb9565a-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/MissionPlanner.vue?vue&type=template&id=e2c8c042&scoped=true& (app.js:946), <anonymous>:19:15)
    at VueComponent.Vue._render (vue.runtime.esm.js?2b0e:3548)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:4066)
    at Watcher.get (vue.runtime.esm.js?2b0e:4479)
    at new Watcher (vue.runtime.esm.js?2b0e:4468)
    at mountComponent (vue.runtime.esm.js?2b0e:4073)
    at VueComponent.Vue.$mount (vue.runtime.esm.js?2b0e:8415)
    at init (vue.runtime.esm.js?2b0e:3118)

The first error says something about 'reactive properties'. I am not sure what these errors mean. Here is my MissionPlanner.vue template & script
<template>

Justice League Mission Planner

Roster:

        ✔

        {{ hero.name }}
        edit

      <input type="text"
             placeholder="new name"
             v-model="newName"
             v-if="isEdit"
             @keyup.enter="changeName"
             @blur="clear">

      enter to submit, click outside the box to cancel

    <chosen-heroes :heroes="heroes" />

</template>

A: ✔

Here is the chosen referenced during render but not defined on the instance.
I guess you want to check if this particular hero is part of this list
data() {
return {
  heroes: [
    { name: "Superman" },
    { name: "Batman" },
    { name: "Aquaman" },
    { name: "Wonder Woman" },
    { name: "Green Lantern" },
    { name: "Martian Manhunter" },
    { name: "Flash" }
  ],
  newName: "",
  isEdit: false,
  heroToModify: null
}

You can write any javascript expression in the v-if so you can try:
 heroObject.name).includes(hero.name)">✔

I used the Array.map() function here so you can keep your list with objects. You could remove it if you write directly the names in the array.
EDIT:
The best would probably be to use a computed property here to make it more reusable and take this long expression out of the v-if:
isInList(heroName) {
  return this.heroes.map(heroObject => heroObject.name).includes(heroName);
}

then
✔