text:
Q: Apply openCV Look Up Table (LUT) to an image I want to apply a custom color look up table (LUT) on an image.
I have looked over the openCV LUT Api but I can not seem to get it right.
#!/bin/bash
# -*- coding: utf-8 -*-

import os
import numpy as np
import cv2

b_max = 230
g_max = 220
r_max = 250

identity = np.arange(256, dtype = np.dtype('uint8'))

b_channel = np.arange(b_max, dtype = np.dtype('uint8'))
b_channel = np.append(b_channel, (256-b_max)*[b_max])
g_channel = np.arange(g_max, dtype = np.dtype('uint8'))
g_channel = np.append(g_channel, (256-g_max)*[g_max])
r_channel = np.arange(r_max, dtype = np.dtype('uint8'))
r_channel = np.append(r_channel, (256-r_max)*[r_max])

if 256 != b_channel.size or 256 != g_channel.size or 256 != r_channel.size:
    print "size of arrays don't match!"

lut = np.dstack((identity, identity, b_channel, g_channel, r_channel))

# Load the image
img = cv2.imread('input.jpg',cv2.IMREAD_COLOR)
dstImage = cv2.LUT(img, lut)
cv2.imwrite('output.jpg', dstImage)

I get the following error:
OpenCV Error: Assertion failed ((lutcn == cn || lutcn == 1) && _lut.total() == 256 && _lut.isContinuous() && (depth == CV_8U || depth == CV_8S)) in cv::LUT, file C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\core\src\convert.cpp, line 5690
Traceback (most recent call last):
  File "ApplyCLUT.py", line 33, in <module>
    dstImage = cv2.LUT(img, lut)
cv2.error: C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\core\src\convert.cpp:5690: error: (-215) (lutcn == cn || lutcn == 1) && _lut.total() == 256 && _lut.isContinuous() && (depth == CV_8U || depth == CV_8S) in function cv::LUT

EDIT:
change to this line:
lut = np.dstack( (b_channel, g_channel, r_channel) )

and it will work!

A: Below is an example of building LUT:
identity = np.arange(256, dtype = np.dtype('uint8'))
zeros = np.zeros(256, np.dtype('uint8'))
lut = np.dstack((identity, identity, zeros))

Note, there is much simpler and straightforward way zeroing the red channel:
img[:,:,2] = 0

Also calling LUT function should look like this:
dstImage = cv2.LUT(img, lut)

Set blue values greater than b_max to b_max:
b_max = 20
img[img[:,:,0] > b_max, 0] = b_max;


text:
Q: cat, grep & awk - both while read line & while read file in 1 loop?
Hi,
Thanks to alot of searching on stackoverflow (great resource!) last couple of days I succeeded in this, and even succeeded in the following issue, that was the output resulted in doubling of the lines everytime I ran the command. Thanks to an awk command which was able to remove double lines.
I'm pretty far in my search, but am missing 1 option.
Using both MacosX and linux by the way.
What I'm trying to do is parse through my notes (all plain text .md files), searching for words/tags in a text file (called greplist.txt), and parsing matched lines in separate text files with the same name as the searchword/tag (eg @computer.md).
Selection of contents of greplist.txt are:
@home
@computer
@Next
@Waiting

example contents of 2 .md files:
school.md:
* find lost schoolbooks @home
* do homework @computer

fun.md
* play videogame @computer

With this terminal command (that works great, but not perfect yet)
$ cat greplist.txt | while read line; do grep -h "$line" *.md >> $line.md.tmp; mv $line.md.tmp $line.md; awk '!x[$0]++' < $line.md > $line.md.tmp && mv $line.md.tmp $line.md ;done

Results
The result for @computer.md :
* do homework @computer
* play videogame @computer

And @home.md would look like this
* find lost schoolbooks @home

So far so great! Already really really happy with this. Especially since the added moving/renaming of the files, it is also for me possible to add extra tasks/lines to the @ tag .md files, and be included in the file without being overwritten the next time I run the command. Awesomecakes!
Now the only thing I miss is that I wish that in the output of the @ tag .md files behind the task also the output also list the filename (without extensions) in between brackets behind the search result (so that nvalt can use this as an internal link)
So the desired output of example @computer.md would become:
* do homework @computer [[school]]
* play videogame @computer [[fun]]

I tried playing around with this with the -l and -H in the grep command instead of -h, but the output it just gets messy somehow. (Not even tried adding the bracket yet!)
Another this I tried was this, but it doesn't do anything it seams. It does however illustrate probably what I'm trying to accomplish.
$ cat greplist.txt | while read line; do grep -h "$line" *.md | while read filename; do echo "$filename" >> $line.md.tmp; mv $line.md.tmp $line.md; awk '!x[$0]++' < $line.md > $line.md.tmp && mv $line.md.tmp $line.md ;done

So the million Zimbabwean dollar question is: How to do this. I tried and tried, but this is above my skill level atm. Very eager to find out the solution!
Thanks in advance.
Daniel Dennis de Wit

A: Try this one:
grep -f greplist.txt *.md | awk ' match($0, /(.*).md:(.*)(@.*)/, vars) { print vars[2], "[[" vars[1] "]]" >> vars[3]".md.out"} '

What it does:
grep will output matched patterns in greplist.txt in the .md files:
fun.md:* play videogame @computer
school.md:* find lost schoolbooks @home
school.md:* do homework @computer

finally awk will move the file name to the back in the format you want and append each line to the corressponding @.md.out* file:
* play videogame @computer [[fun]]
* find lost schoolbooks @home [[school]]
* do homework @computer [[school]]

I added the .out on the file name so that the next time you execute the command it will not include the @* files.
Note that I'm not sure if the awk script will work on the Mac OS X awk.

A: The outline solution seems like a fairly long-winded way to write the code.  This script uses sed to write an awk script and then runs awk so that it reads its program from standard input and applies it to all the '.md' files that don't start with an @.
sed 's!.*!/&/ { name=FILENAME; sub(/\\.md$/, "", name); printf "%s [[%s]]\\n", $0, name > "&.md" }!' greplist.txt |
awk -f - [!@]*.md

The version of awk on Mac OS X will read its program from standard input; so will GNU awk.  So, the technique it uses of writing the program on a pipe and reading the program from a pipe works with those versions.  If the worst comes to the worst, you'll have to save the output of sed into a temporary file, have awk read the program from the temporary file, and then remove the temporary file. It would be straight-forward to replace the sed with awk, so you'd have one awk process writing an awk program and a second awk process executing the program.
The generated awk code looks like:
/@home/ { name=FILENAME; sub(/\.md$/, "", name); printf "%s [[%s]]\n", $0, name > "@home.md" }
/@computer/ { name=FILENAME; sub(/\.md$/, "", name); printf "%s [[%s]]\n", $0, name > "@computer.md" }
/@Next/ { name=FILENAME; sub(/\.md$/, "", name); printf "%s [[%s]]\n", $0, name > "@Next.md" }
/@Waiting/ { name=FILENAME; sub(/\.md$/, "", name); printf "%s [[%s]]\n", $0, name > "@Waiting.md" }

The use of ! in the sed script is simply the choice of a character that doesn't appear in the generated script.  Determining the basename of the file on each line is not 'efficient'; if your files are big enough, you can add a line such as:
{ if (FILENAME != oldname) { name = FILENAME; sub(/\.md$/, "", name); oldname = FILENAME } }

to the start of the awk script (how many ways can you think of to do that?).  You can then drop the per-line setting of name.
Do not attempt to run the program on the @topic.md files; it leads to confusion.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java FX can't import InteliJ So l just started learning Java FX and l tried to create a file.

*

*I have Java SDK

*I downloaded the Java FX SDK and l imported it to global libraries. I even imported it to project libraries.

*I did the VM option --module-path
C:\Users\admin\Desktop\Coding\javafx-sdk-11.0.2\lib
--add-modules=javafx.controls,javafx.fxml

Here is how my project looks.
Nothing fixed my problem. I tried with the newest Java FX SDK but it too didn't fix it. I tried importing from the .rar, l tried importing from a folder, l tried different VM module options, watched multiple tutorials and read multiple stackoverflow posts but nothing helped...

A: Nevermind l fixed it! I tried again with the newest FX SDK and l needed to only import it in project library not in global library!


text:
Q: Python asyncio gather dictionary So I understand how to create a collection of async tasks via a list and use asyncio.gather() to execute them but I don't know how to do the same with a dict:
    from fastapi import FastAPI
    import asyncio
    import httpx

    app = FastAPI()

    urls = [
        "http://www.google.com",
        "https://www.example.org",
        "https://stackoverflow.com/",
        "https://www.wikipedio.org"
    ]

    async def async_request_return_dict(url: str):
        async with httpx.AsyncClient() as client:
            r = await client.get(url)
        return {url : r.status_code}

    # List of async coroutines
    @app.get("/async_list")
    async def async_list():

        tasks = []
        for url in urls:
            tasks.append(async_request_return_dict(url=url))
        response = await asyncio.gather(*tasks)

        # Convert list of dict -> dict
        dict_response = dict()
        for url in response:
            dict_response.update(url)

        return dict_response

    async def async_request_return_status(url: str):
        async with httpx.AsyncClient() as client:
            r = await client.get(url)
        return r.status_code

    # Dict of async coroutines
    @app.get("/async_dict")
    async def async_dict():

        tasks = dict()
        for url in urls:
            tasks[url] = async_request_return_status(url=url)

        ### How do you run async co-routines inside a dict??? ###
        await asyncio.gather(*tasks.values())

        print(tasks)

        return tasks

Output of /async_list:
    {
        "http://www.google.com":200,
        "https://www.example.org":200,
        "https://stackoverflow.com/":200,
        "https://www.wikipedio.org":200
    }

Traceback for /async_dict :
INFO:     Application startup complete.
{'http://www.google.com': <coroutine object async_request_return_status at 0x7fec83ded6c0>, 'https://www.example.org': <coroutine object async_request_return_status at 0x7fec83ded740>, 'https://stackoverflow.com/': <coroutine object async_request_return_status at 0x7fec83ded7c0>, 'https://www.wikipedio.org': <coroutine object async_request_return_status at 0x7fec83ded840>}
INFO:     127.0.0.1:58350 - "GET /async_dict HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 396, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/fastapi/routing.py", line 209, in app
    response_data = await serialize_response(
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/fastapi/routing.py", line 137, in serialize_response
    return jsonable_encoder(response_content)
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/fastapi/encoders.py", line 90, in jsonable_encoder
    encoded_value = jsonable_encoder(
  File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/fastapi/encoders.py", line 141, in jsonable_encoder
    raise ValueError(errors)
ValueError: [TypeError("'coroutine' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]

Basically how to execute asyncio.gather() with a dict.
Or is the first approach of executing the coroutines inside a list and re-constructing a dictionary once all await-ables are resolved.

A: This won't work as you expect because your dict values are coroutines but the actual result values are returned from asyncio.gather.
asyncio.gather:

The order of result values corresponds to the order of awaitables in
aws.

Based on this fact you can do something like this:
test.py:
import asyncio

import httpx

URLS = (
    "http://www.google.com",
    "https://www.example.org",
    "https://stackoverflow.com/",
    "https://www.wikipedio.org",
)

async def req(url):
    async with httpx.AsyncClient() as client:
        r = await client.get(url)

    return r.status_code

async def main():
    tasks = []

    for url in URLS:
        tasks.append(asyncio.create_task(req(url)))

    results = await asyncio.gather(*tasks)

    print(dict(zip(URLS, results)))

if __name__ == "__main__":
    asyncio.run(main())

Test:
$ python test.py
{'http://www.google.com': 200, 'https://www.example.org': 200, 'https://stackoverflow.com/': 200, 'https://www.wikipedio.org': 200}


text:
Q: How to extract the unique values from a separate ranges and concatenate to the adjacent column (offset (,-1) on the same range? I need to extract the unique values from a separate ranges and concatenate to the adjacent column (offset (,-1) on the same range.
As you see on the below picture, I sort my dataset by column_A ,so all duplicate values on column_A will be together.
I need to put the duplicate values on column_A with the respective cells on the same rows into a variable Range e.g rng1 = [A2:C4],
Then extract unique values found on rng1.columns(3) and concatenate to each cell on rng1.columns(2) ,range("B2:B4")
By the same rng2 will be = [A5:C7] and so on.
The problem is I do not know how when ID values is duplicates to put them and it's adjacent cells on the same rows into a variable range and process it !
At end column C will be be deleted.
In advance, great thanks for your learning support.

Sub Extract_unique_values_and_combine_in_adjacent_cells()

   Dim ws As Worksheet: Set ws = ActiveSheet
    Dim rng As Range
     Set rng = ws.Range("A2:C" & ws.Cells(Rows.Count, "A").End(xlUp).Row)

   Dim arr: arr = rng.Value2
    Dim i As Long
     For i = LBound(arr) To UBound(arr)

   On Error Resume Next 'skip error if i= 1
      If arr(i, 1) = arr(i + 1, 1) Or _
         arr(i, 1) = arr(i - 1, 1) Then
        arr(i, 2) = arr(i, 2) & vbLf & unique(ws.Range("C2:C4").Value2) 'I need (crg) to be dynamic
      End If
   On Error GoTo 0

    Next i

   rng.Value = arr

End Sub

Function unique(crg)

   Dim cel, a
     With CreateObject("scripting.dictionary")
       For Each cel In crg
         a = .Item(cel)
       Next
     unique = Join(.Keys, vbLf)
    End With

End Function

A: Please, try the next code. It uses a dictionary and arrays to keep, process and return the necessary strings. It will process all categories (unique in A:A) being in any order:
Sub CombineRanges()
   Dim sh As Worksheet, lastR As Long, arr, arrDict, dict As Object
   Dim arrDB, arrDC, mtch, arrFin, i As Long, j As Long, k As Long

   Set sh = ActiveSheet
   lastR = sh.Range("A" & sh.rows.count).End(xlUp).row

   arr = sh.Range("A2:C" & lastR).Value2
   Set dict = CreateObject("Scripting.Dictionary")

   For i = 1 To UBound(arr)
        If Not dict.Exists(arr(i, 1)) Then
            dict.Add arr(i, 1), Array(arr(i, 2), arr(i, 3)) 'place the strings from columns B and C
        Else
            arrDict = dict(arr(i, 1))                       'extract the array from dict items (it cnnot be modified inside the item)
            arrDict(0) = arrDict(0) & "|" & arr(i, 2)       'place in the array first element the strings collected from B:B
            arrDC = Split(arrDict(1), vbLf)                 'try splitting the second array element (string(s) from C:C)
            If UBound(arrDC) = 0 Then                       'if only one element:
                If arrDC(0) <> arr(i, 3) Then arrDict(1) = arrDict(1) & vbLf & arr(i, 3) 'add to it the value from C:C, separated by vbLf
            Else
                mtch = Application.match(arr(i, 3), arrDC, 0) 'check unicity of the string from C:C
                If IsError(mtch) Then                         'only if not existing:
                    arrDict(1) = arrDict(1) & vbLf & arr(i, 3)'add it to the string to be used in the next step
                End If
            End If
            dict(arr(i, 1)) = arrDict                         'put back the array in the dictionary item
        End If
   Next i

   ReDim arrFin(1 To UBound(arr), 1 To 2): k = 1              'redim the final array and initialize k (used to fill the array)
   For i = 0 To dict.count - 1                                'iterate between the dictionary keys/items:
        arrDict = dict.Items()(i)                             'place the item array in an array
        arrDB = Split(arrDict(0), "|")                        'obtain an array of B:B strins from the item first array element
        For j = 0 To UBound(arrDB)   'how many unique keys exists!
                arrFin(k, 1) = dict.Keys()(i)                 'place the dictionry key per each iteration
                arrFin(k, 2) = arrDB(j) & vbLf & arrDict(1)   'build the string of the second column
                k = k + 1
        Next j
   Next i
   'drop the processed result near the existing range (for easy visual comparison):
   sh.Range("D2").Resize(UBound(arrFin), 2).Value2 = arrFin
End Sub

The above code assumes what I wrote in my comment placed some time before and you din not confirm/infirm...
Edited:
Please, test the next version. It will return only a column keeping the concatenated B:C columns value and skips the empty values in C:C, if the case. It will return in D:D, too. After testing, if it does what you need, just change "D" with "B" in the last code line:
Sub CombineRangesOneColumn()
   Dim sh As Worksheet, lastR As Long, arr, arrDict, dict As Object
   Dim arrDB, arrDC, mtch, arrFin, i As Long, j As Long, k As Long

   Set sh = ActiveSheet
   lastR = sh.Range("A" & sh.rows.count).End(xlUp).row

   arr = sh.Range("A2:C" & lastR).Value2
   Set dict = CreateObject("Scripting.Dictionary")

   For i = 1 To UBound(arr)
        If Not dict.Exists(arr(i, 1)) Then
            dict.Add arr(i, 1), Array(arr(i, 2), arr(i, 3)) 'place the strings from columns B and C
        Else
            arrDict = dict(arr(i, 1))                                   'extract the array from dict items (it cnnot be modified inside the item)
            arrDict(0) = arrDict(0) & "|" & arr(i, 2)        'place in the array first element the strings collected from B:B
            arrDC = Split(arrDict(1), vbLf)                      'try splitting the second array element (string(s) from C:C)
            If UBound(arrDC) = 0 Then                           'if only one element:
                If arrDC(0) <> arr(i, 3) Then arrDict(1) = arrDict(1) & IIf(arr(i, 3) = "", "", vbLf & arr(i, 3)) 'add to it the value from C:C, separated by vbLf
            Else
                mtch = Application.match(arr(i, 3), arrDC, 0) 'check unicity of the string from C:C
                If IsError(mtch) Then                                          'only if not existing:
                    arrDict(1) = arrDict(1) & IIf(arr(i, 3) = "", "", vbLf & arr(i, 3))       'add it to the string to be used in the next step
                End If
            End If
            dict(arr(i, 1)) = arrDict                                             'put back the array in the dictionary item
        End If
   Next i

   ReDim arrFin(1 To UBound(arr), 1 To 1): k = 1            'redim the final array and initialize k (used to fill the array)
   For i = 0 To dict.count - 1                                                'iterate between the dictionary keys/items:
        arrDict = dict.Items()(i)                                               'place the item array in an array
        arrDB = Split(arrDict(0), "|")                                      'obtain an array of B:B strins from the item first array element
        For j = 0 To UBound(arrDB)   'how many unique keys exists!                     'place the dictionry key per each iteration
                arrFin(k, 1) = arrDB(j) & vbLf & arrDict(1)       'build the string of the second column
                k = k + 1
        Next j
   Next i
   'drop the processed result near the existing range (for easy visual comparison):
   sh.Range("D2").Resize(UBound(arrFin), 1).Value2 = arrFin
End Sub


text:
Q: null value in column "email" violates not-null constraint I got the following error(Error logs) and I found some solution and tried them but none of them is working. it would be great if you can help me with this.
index.js:
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser')
const cors = require('cors');
const adminGate = require('./admin')
const app = express();
const port = process.env.PORT;
const host = process.env.HOST;

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(cors())

app.get('/', (req, res)=>{
    res.send("NODE SERVER IS UP AND RUNNING");
});

// routing
app.post('/create_user', adminGate.createUser);

app.listen(port,()=>{
    console.table(`SERVER IS RUNNING ON PORT:${port}!`);
    console.table(`CHECK: http://${host}:${port}`)
});

admin.js:
const Pool = require('pg').Pool
const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: '##########',
  password: '##########',
  port: 5432,
});

const createUser = (request, response) => {
    const {email, username, password} =  request.params // || request.body none of them is working.

    pool.query('INSERT INTO users(email, username, password) VALUES($1,$2,$3)',[email, username, password], (error, results) => {
        if (error) {
            throw error
        }
        response.status(201).json({status: 'success', message: 'User added.'})
    })
}

module.exports ={createUser}

Error logs:
SERVER IS RUNNING ON PORT:3000!
CHECK: http://localhost:3000
/Users/pouya/src/admin.js:26
            throw error
            ^

error: null value in column "email" violates not-null constraint
    at Parser.parseErrorMessage (/Users/pouya/node_modules/pg-protocol/dist/parser.js:278:15)
    at Parser.handlePacket (/Users/pouya/node_modules/pg-protocol/dist/parser.js:126:29)
    at Parser.parse (/Users/pouya/node_modules/pg-protocol/dist/parser.js:39:38)
    at Socket.<anonymous> (/Users/pouya/pg-protocol/dist/index.js:8:42)
    at Socket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:302:12)
    at readableAddChunk (_stream_readable.js:278:9)
    at Socket.Readable.push (_stream_readable.js:217:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:186:23) {
  length: 184,
  severity: 'ERROR',
  code: '23502',
  detail: 'Failing row contains (null, null, null).',
  hint: undefined,
  position: undefined,
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: 'public',
  table: 'users',
  column: 'email',
  dataType: undefined,
  constraint: undefined,
  file: 'execMain.c',
  line: '1974',
  routine: 'ExecConstraints'
}

A: You have to pass the request and response as such because createUser expects these two parameters.
app.post('/create_user',(req, res) => {
  adminGate.createUser(req, res);
});

In createUser function
const {email, username, password} =  request.query


text:
Q: Getting a "for" loop to remove characters from list if they are equal In my program, the user inputs a secret word that another person is to guess (hangman). The letters are then put into a list. I am trying to make a loop that checks if there are several equal letters in the list, and remove them if there is.
This I have managed. The problem is that this loop also removes other characters that are not ment to be removed.
word = []

for i in range(int(len(secret_word)) - 1):
    if word[l] == word[q]:
        word.pop(l)
        q += 1
        if q > int(len(word)):
            break
    else:
        l +=1

Using the word "secret" and then printing the list, the output I get is
['s', 'c', 'e', 't']

It has removed the e, but unfortunately the r is also removed.
Also, this loop doesn't remove a third equal letter. Using "secretive" the output is
['s', 'c', 'e', 'i', 'e']

Here, removing one of the e's, but also r, t and v

A: word = 'secretblahblahset'
result = ''

for c in word:
  if not c in result:
    result += c

print(result)

A: Your example code is missing a number of features such as the initialization of q and l. And I suspect you must have an outer loop that you're not showing us, otherwise the example doesn't make a lot of sense (in the example as given word is just an empty list).
If you want all the unique letters in a string you can do so easily with set():
unique_letters = set(secret_word)

However, that will not preserve order. I don't know for your case if you even need to preserve order. But if you wanted to there are many ways to do so, often still involving set() but not necessarily. Here's one way:
unique_letters = []
seen = set()
for let in secret_word:
    if let in seen:
        continue

    unique_letters.append(let)
    seen.add(let)

Another way, as a one-liner, might be something like:
unique_letters = sorted(set(secret_word), key=secret_word.index)

Those are just a few examples. There are many ways to do this. I'm sorry I can't say exactly what's wrong with you code. The example is missing too much context. But you're probably overcomplicating the problem.


text:
Q: New Force.com IDE not auto-deploying? (NOT A DUPLICATE QUESTION) I am having the same issue as here New Force.com IDE (Eclipse) - not auto-deploying?, except the solution chosen isn't working.
I have Build Automatically checked and I've also already selected "Work Online" for the entire project.  These two actions are the only solutions made available under the above link. Nevertheless, every time I save the project, nothing saves to the production environment unless I manually go into each component and select "save to server" under the Force.com IDE menu item for that component.  I'm using Kepler 2 as well and the latest Force.com IDE Plugin.
I'm able to get the Sandbox Project I have to auto-deploy, just not in production.  I can also roll out new changes to the classes/vf pages via the changesets successfully (i.e., my test classes are working)
Please help, this is so annoying.

A: Is this something you encountered after latest summer '14 release ?
Please check the list of issues for force.com IDE to see if your issues is listed as known issue,
https://github.com/forcedotcom/idecore/issues


text:
Q: Custom Types passed as parameter I've created a custom type to allow me verify a country code, but I'm having trouble using this as a parameter for WebAPI call.
My custom Type which validates a string then assigns itself using the implicit operator;
public class CountryCode
{
    private readonly string _CountryCode;
    private CountryCode(string countryCode)
    {
        _CountryCode = countryCode;
    }
    public static implicit operator CountryCode(string countryCode)
    {
        return (countryCode.Length == 3) ? new CountryCode(countryCode) : null;
    }
    public override string ToString()
    {
        return _CountryCode.ToString();
    }
}

The WebAPI call;
[HttpGet]
public HttpResponseMessage Get(CountryCode countryCode)
{
    // countryCode is null
}

It's possible to work around this;
[HttpGet]
public HttpResponseMessage Get(string countryCode)
{
    CountryCode countrycode = countryCode;
    return Get(countrycode);
}

private HttpResponseMessage Get(CountryCode countryCode)
{
    // countryCode is valid
}

Is it possible to alter my custom type so it is instantiated by the WebAPI parameter call?

A: Use type converters
[TypeConverter(typeof(CountryCodeConverter))]
public class CountryCode
{
    ...
}

public class CountryCodeConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(string)) { return true; }
        return base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        if (value is string && value != null)
        {
            return (CountryCode)((string)value);
        }
        return base.ConvertFrom(context, culture, value);
    }
}

then
[HttpGet]
public HttpResponseMessage Get(CountryCode countryCode)

will work


text:
Q: Is it possible to have calculated columns in metrics resource I'm trying to divide one column from metrics by another to find percentage of used Azure files but can not figure out if it's possible to do. Example is below where I want to have a new calculated column which divides column called File capacity by column called File Share Capacity.

A: In the metrics directly no, as metrics itself doesn't have that (yet?)
In workbooks, yes, you can do this, using a "merge" data source, which allows addition of custom calculated columns.  (this is something we'd like to support directly on any metrics/query without using merge but hasn't worked its way up on to the todo list behind everything else)

*configure your metrics step (make sure the metric step is set to "grid" visualization)

*after your metrics step, add a new query step.

*choose data source "merge"

*click "add merge", and in the popup that appears choose "duplicate table" and choose the metric created in step 0

*

*you should now see a grid of all of the fields in the table with their original name and what they'll be named after the merge

*at this point, remove any columns you can remove any columns you don't need

*and i'd suggest naming the rest of them nice easy names to use in steps later

*click "add new item" in the toolbar

*you'll get a new window for adding a new column and how to populate its rows

*

*commonly this is used to if/then/else between values, but you'll just have one row here

*in the row for conditions, click "edit" in the default row

*a popup will appear, probably with a bunch of things disabled.

*but one of the options there is "value from" and you can choose "expression"

*after choosing "expression" you can type in the expression you want

for mine, i couldn't repro it on exactly your metrics, but i did this:

and got a grid (which i then set all the standard format options on to make it similar to the metrics grid (in group by settings group by sub, name by name, expand top level.  in column settings, set the group by column renderer to resource, hide sub, name columns, set the error rate column to percent and 5 decimals) and i get this:

you can then go to the original metrics step in your workbook, and use conditional visibility settings to hide the metrics step.


text:
Q: couchdb , procedure to add a CommonJS modules (show list function) What is the exact procudure to add a CommonJs module on couchdb ?
I've read tutorials like:
https://caolan.org/posts/commonjs_modules_in_couchdb.html
from official doc:
http://docs.couchdb.org/en/1.6.1/query-server/javascript.html#commonjs-modules
The CommonJS module can be added to a design document, like so:
{
   "views": {
      "lib": {
         "security": "function user_context(userctx, secobj) { ... }"
      }
   },
   "validate_doc_update": "function(newdoc, olddoc, userctx, secobj) {
      user = require('lib/security').user(userctx, secobj);
      return user.is_admin();
   }"
   "_id": "_design/test"
}

but where I copy or paste that code? must I save to the file and add it with  curl ?   On fauxton i don'see where.

A: Managing CouchDB design documents is usually best accomplished via a tool like couchapp. It allows you to package up a directory of files and outputs a CouchDB design document.
You can manually edit that JSON in the futon/fauxton editor, but it's a pain and there are other tools out there depending on your toolchain. An external tool like this also aids in deployment, particularly across different environments.


text:
Q: PHP echo select menu value but delete duplicate I'm working on a profile update page and i have a form field where users can select enabled or disabled. When i echo the value, it has a duplicate and can be confusing for the user. How can i get rid of the duplicate?

   Change Status

      <select class="form-control btn-danger" id="status" name="status">
         <option value="<?php echo $status ?>"><?php echo $status ?></option>
         <option value="Disabled">Disabled</option>
         <option value="Enabled">Enabled</option>
      </select>

As you can see, if the status is enabled and i hit the select menu its gonna say Enabled twice, same thing for disabled.
The only thing i thought of was to have another field labeled current status and have the select menu to change status.
I really dont want to do that.

   Current Status

      <input type="text" class="form-control" id="currentstatus" name="currentstatus" value="<?php echo $status ?>">

   Change Status

      <select class="form-control btn-danger" id="status" name="status">
         <option value="<?php echo $status ?>"><?php echo $status ?></option>
         <option value="Disabled">Disabled</option>
         <option value="Enabled">Enabled</option>
      </select>

This worked for me:
<option <?php if ($status=="Disabled") echo " selected"; ?>>Disabled</option>
<option <?php if ($status=="Enabled") echo " selected"; ?>>Enabled</option>

A: Instead of outputting the selected value as another option, output it as the selected attribute of an existing option.  Something like this:
<select class="form-control btn-danger" id="status" name="status">
    <option value="Disabled" <?php echo ($status == "Disabled") ? "selected" : ""; ?>>Disabled</option>
    <option value="Enabled" <?php echo ($status == "Enabled") ? "selected" : ""; ?>>Enabled</option>
</select>

There are likely a variety of ways to achieve the same end result, but the point is to not add options based on the data you have but instead use that data to determine which of the existing, finite, hard-coded options you already have should be selected.

A: Here is some jQuery that will let you change the value of the select box.

function setStatusSelect(val) {
  $("select#status").val(val);
}

setStatusSelect('Enabled');

  Change Status

    <select class="form-control btn-danger" id="status" name="status">
         <option value="Disabled">Disabled</option>
         <option value="Enabled">Enabled</option>
      </select>

If you include the Jquery function at the top of the page (so that it loads quickly) then you can do something like this:
<?php

print("");

?>

to set the value.
I haven't tested the PHP portion, but I know the jQuery portion works.


text:
Q: Fhir json - how to suppress attributtes (ex. @Value, @id) in java app I have a REST API that needs to produce both Fhir xml and Fhir json. I generated java classes using xsd.  XML works 100%. however, the json object looks funny as it includes attributes which I'd like to suppress.
I have specified on my REST API: @Produces({"application/json+fhir",MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
XML output:
    <Bundle xmlns="http://hl7.org/fhir" xmlns:ns2="http://www.w3.org/1999/xhtml">
<meta>
    <versionId value="urn:uuid:b6bfc48a-7b03-4bf3-ba94-d05a3b52979a"/>
    <lastUpdated value="2017-07-10T08:32:44.670+02:00"/>
</meta>
<type value="collection"/>
<entry>
    <resource>
        <Coverage>
            <id value="47000340200"/>
            <subscriber>
                <display value="AB SMITH"/>
            </subscriber>
            <period>
                <start value="2017-01-01"/>
            </period>
            <payor>
                <display value="XXX040TXX"/>
            </payor>
            <grouping>
                <extension url="some URL">
                    <valueUri value="Hyperlink goes here"/>
                </extension>
                <group value="XXX"/>
                <groupDisplay value="XXX MEDICAL FUND"/>
                <plan value="OPT1"/>
                <planDisplay value="OPTION1"/>
                <class value="Active"/>
            </grouping>
        </Coverage>
    </resource>
</entry>

JSON output:
    {"Bundle": {
"meta":    {
    "versionId": {"@value": "urn:uuid:b6bfc48a-7b03-4bf3-ba94-d05a3b52979a"},
    "lastUpdated": {"@value": "2017-07-10T08:32:44.670+02:00"}
},
"type": {"@value": "collection"},
"entry":    [
    {"resource": {"Coverage":       {
        "id": {"@value": "47000340200"},
        "subscriber": {"display": {"@value": "AB SMITH"}},
        "period": {"start": {"@value": "2017-01-01"}},
        "payor": {"display": {"@value": "XXX040TXX"}},
        "grouping":          {
            "extension":             {
                "@url": "some URL",
                "valueUri": {"@value": "Hyperlink goes here"}
            },
            "group": {"@value": "XXX"},
            "groupDisplay": {"@value": "XXX MEDICAL FUND"},
            "plan": {"@value": "OPT1"},
            "planDisplay": {"@value": "OPTION1"}
        }
    }}}
]

}}
How do I get rid of the "@Value" attribute?

A: The FHIR XML and JSON (and TTL) syntaxes are all tuned to their syntax and thus manifest a slightly different model.  If you try running an instance with extensions on a simple type (date, boolean, etc.), you'll find even more significant differences in your generated object model.  If you generate your object model from the XML schema, the JSON schema or the OWL, you'll find there's a decent chunk of hand-coding you'll have to add on afterwards to generate and parse the other syntaxes correctly.  The alternative is to use one of the existing reference implementations - those handle the conversion for you and provide a whole bunch of helper classes and methods that might also be helpful for you.  The reference implementations can be found on the downloads page.


text:
Q: spark using only one core on parallelism task So i have this code:
conf = SparkConf().setAll((
    ("spark.python.profile", "true" if args.profile else "false"),
    ("spark.task.maxFailures", "20"),
    ("spark.driver.cores", "4"),
    ("spark.executor.cores", "4"),
    ("spark.shuffle.service.enabled", "true"),
    ("spark.dynamicAllocation.enabled", "true"),
))

# TODO could this be set somewhere in cosr-ops instead?
executor_environment = {}
if config["ENV"] == "prod":
    executor_environment = {
        "PYTHONPATH": "/cosr/back",
        "PYSPARK_PYTHON": "/cosr/back/venv/bin/python",
        "LD_LIBRARY_PATH": "/usr/local/lib"
    }

sc = SparkContext(appName="Common Search Index", conf=conf, environment=executor_environment)

# First, generate a list of all WARC files
warc_filenames = list_warc_filenames()

# Then split their indexing in Spark workers
warc_records = sc.parallelize(warc_filenames, 4).flatMap(iter_records)

While it lounches all the spark stuff it uses all the cores.
But when it starts to do the task( indexing ), then it only uses 1 core on 100%.
How to make one spark task use all of the cores ?

A: Problem was in the python itself not using all cores. I implemented multi-threading.
Thanks for all who helped.


text:
Q: Vignette Table of Contents Missing When Package Published to CRAN I recently released a vignette with version 1.1 of my R package. The Rmd for the vignette can be found here. When I create the vignette locally, I see author information and the table of contents at the top of the vignette, as expected. However, when I submitted this package to CRAN and the vignette was created there, I no longer see the table of contents or author information. Does anyone know why this may be happening?
Thanks.

A: I glanced at your DESCRIPTION here and noticed that the VignetteBuilder field does not contain rmarkdown. Since you are using knitr::rmarkdown as an engine, I suspect that you need:
VignetteBuilder: knitr, rmarkdown

Here is a relevant paragraph from the R-exts manual:

The VignetteBuilder field names (in a comma-separated list) packages that provide an engine for building vignettes. These may include the current package, or ones listed in Depends, Suggests or Imports. The utils package is always implicitly appended. See Non-Sweave vignettes for details. Note that if, for example, a vignette has engine knitr::rmarkdown, then knitr provides the engine but both knitr and rmarkdown are needed for using it, so both these packages need to be in the VignetteBuilder field and at least suggested (as rmarkdown is only suggested by knitr, and hence not available automatically along with it). Many packages using knitr also need the package formatR which it suggests and so the user package needs to do so too and include this in VignetteBuilder.

This is not a guaranteed fix, but it is maybe a first step.


text:
Q: NodeJs express-validator. Case sensitive checking json I'm writing a NodeJS application.
I'm trying to validate the input json using 'express-validator':
var express = require('express');
const winston = require('../config/winston');
const { check, validationResult } = require('express-validator');
const myController= require('../controller/myController.js');
var router = express.Router();

router.use(       [
              check('COMMON.user','User incorrect').not().isEmpty(),
          ],
           (req, res, next) => {
      const resCheck = validationResult(req);
      if (!resCheck.isEmpty()) {
          obj= req.body;
          obj.COMMON= {codigoRespuesta:-1, textoRespuesta:"Error checking request"};

          winston.info(JSON.stringify(obj));
         return res.json(obj);
      }else{
          console.log("vacio");
      }
      return myController.procesaRequest(req, res);
});

+
Seems "check" method is case-sensitive. If json input contains "{common: {user:"Test"..." throws error, but "{COMMON: {user:"Test"..."  works ok.
How can i make 'check" case insensitive?
Thanks!

A: I'm not sure why You need case insensitive check, cause api-s have to be strict about validation.
But I recommend You to transform common to COMMON to achieve Your goal:
router.use(
  // transforming (adapting)
  (req, res, next) => {
    if (req.body && req.body['common']) {
      req.body['COMMON'] = Object.create(req.body['common']);
      delete req.body['common'];
    }
    next();
  },

  // validation
  [
    check('COMMON.user', 'User incorrect').not().isEmpty(),
  ],

  // post-validation
  (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      winston.info(JSON.stringify(req.body), errors.array());
      return res.status(400).json({
        codigoRespuesta: -1,
        textoRespuesta: "Error checking request",
        errors: errors.array()
      });
    }
    next();
  },

  // handler
  myController.procesaRequest
);


text:
Q: Integration test for spring jdbc Let's say we have a service layer :
@Service
public class MyServiceImpl implements MyService {

    @Autowired
    private MyDAO myDAO;

    @Transactional
    public void myMethod(SomeObject someObject) {
       myDAO.insertIntoMyDb(someObject);

    }
}

Let us say myDAO uses spring jdbc :
@Repository
public class MyDAOImpl implements MyDAO {

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    public void insertIntoMyDb(SomeObject object) {

        // some code before this where we get query and param

        int numberOfRowsUpdated = jdbcTemplate.update(query,param);

        if(numberOfRowsUpdated != 1)
            throw new Exception("Error while inserting a record in database. Actual records inserted : " + numberOfRowsUpdated);
    }

}

I want to write 2 tests.
The first test will check my dao layer only. I want to make a jdbc call here , get data and verify. I don't want to mock them.
The second test is integration test. I want my service layer to call Dao layer. Note that there is transaction. Now this will give me data from DAO. Again DAO has to connect to db to get data.
I am using spring boot. My database properties are present in applicationITest.properties file.
How to do these 2 testing ? What is the correct annotations I have to use ? Can some one provide an example ?

A: a) Rollback will happen by default as long as you annotate your Test class with @Transactional. Documentation about Test-managed transactions.
sample test class:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyTestConfig.class)
@Transactional
public class MyClassTest {
   //..

   @Test
   public void myTest() {
      //..
   }

   //..
}

b) Yes you can enforce the commit using the @Commit (added in Spring 4.2) test annotation. Here's the documentation.


text:
Q: 0.1 rem border-width renders differently on chrome and safari In my application I am setting:
html {
    font-family: 'Source Sans Pro',"Helvetica Neue",sans-serif;
}

I set border width to 0.1rem and now I noticed that in Chrome this sets the width to 1.6px and in Safari it sets it to 1px.
The text in Safari and Chrome appears the same size so why does the width of the lines render differently?
I saw on some web sites the setting font-size: 100%.  As a good practice should I be setting this?
One more question. Is it a bad practice for me to set my border widths with rem in this way? I was using rem as everything in the application uses rem and I wanted to keep things the same.

A: If you want rem measurements to be relative to a specific pixel size then you need to specify that size for the font-size property of your html tag. Without doing that, rem measurements will be relative to the default font size specified in each individual browser's settings.
html{
    font-size:16px;
}
p{
    border-width:.1rem; /* =1.6px */
}

Also, consider the fact that different browsers round numbers differently.

A: Usually what is noticed is that if the border width is <=1px, it is better to give it as 1px. As rem would make it a very small value. Some of the browsers don't render this value.


text:
Q: stringWithContentsOfFile:usedEncoding:error: does not work I'm trying to import a csv created by filemaker and copied onto my device using iTunes filesharing. I'm stuck on what should be a straightforward step. I just can't see where I'm going wrong. Tried the alternative method and setting UTF8 encoding. Also tried exporting from filemaker as xml UTF8, and also tried deleting the app from the phone and rerunning. It doesn't seem to read the encoding even if I specify it. The following code gives me this console output.
File exists
Import (null) Error Domain=NSCocoaErrorDomain Code=264 "The operation couldn't be completed. (Cocoa error 264.)"
-(void)importDatabase {
NSString *importString;
NSError *error;
NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
if ([[NSFileManager defaultManager] fileExistsAtPath:[documentsDirectoryPath stringByAppendingString:@"/iPhone.csv"]]) {
    NSLog(@" File exists");
    NSStringEncoding encoding;
    importString = [NSString stringWithContentsOfFile:[documentsDirectoryPath stringByAppendingString:@"/iPhone.csv"] usedEncoding:&encoding error:&error];
NSLog(@"Import %@ %@ ",importString, error);
} else {
    NSLog(@" File doesn't exist");
}

}

A: From the header:
NSFileReadUnknownStringEncodingError = 264,         // Read error (string encoding of file contents could not be determined)

Try telling Foundation what the encoding is, as you know what the encoding is.
importString = [NSString stringWithContentsOfFile: blah encoding: NSUTF8StringEncoding error: &error];

A: I had a similar problem, and it turned out that the file was encoded in some strange code page (with >128 characters), instead of UTF-8. In the end, i never did figure out how it was encoded originally...

A: I think you just forgot [NSString alloc] because this works for me:
NSString *fileComponents = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];


text:
Q: product of inputted numbers new here and in java world and I am a student. I just keep getting a wrong product for this question.
Write a Java application that asks the user to input an integer between 1 and 9
inclusive, 10 times, and then prints their product. Your program should use a for loop.
When an integer less than 1 or larger than 9 is input, your application should disregard
it.
You should NOT use logical AND or logical OR operators.
here is what I have done so far:
import java.util.Scanner;

public class newtest {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int counter;
        int product = 1;
        int number;

        System.out.print("Enter number 1-9: ");
        number = input.nextInt();
        for (counter=1; counter<=10; counter++){

        System.out.print("Enter number 1-9: ");
        number = input.nextInt();

        if (number<10){
            if (number>0) product*=number;
                else System.out.println ("number is disregarded");
        }
        else System.out.println ("number is disregarded");

        }

        product *= number;
        System.out.println (product);

    }

}

A: if (number<10){

    if (number>0) product*=number;
    else System.out.println ("number is disregarded");}
else System.out.println ("number is disregarded");

}   product *= number;
System.out.println (product);

Your problem is here, remove the product *= number; that follows the outer if block.


text:
Q: Is there a way to get direct_to_template to pass RequestContext in django? I have found myself writing the same view over and over.  It is basically this:
def home_index(request):
    return render_to_response('home/index.html', RequestContext(request))

To keep with the dry principal, I would like to utilize a generic view. I have seen direct_to_template, but it passes an empty context.  So how can I use a generic view and still get the power of RequestContext?

A: direct_to_template, like all generic views, already uses a RequestContext, so you don't need to do anything else to enable it.
However I'm not sure if what you're really asking is whether you can pass additional context items - and you can, by using the extra_context dictionary parameter, either in the URLconf or in a wrapper view.
Also you should ask yourself why you're creating multiple views that simply render templates. If that's what you are mostly doing, you may find that Django's built-in flatpages app is better than hard-coding your views.

A: I remember having the same problem, and writing something like this, but looking at the direct_to_template code it seems in new versions of django this problem doesn't exist anymore. direct_to_template passes the correct context.


text:
Q: Heatmaps for a matrix with ones and zeros using R Below is my sample data, basically its a matrix with row names as person names
and some columns for each of these rows. All I have in the data is just zeros and ones. I would like to visualize it using heatmaps. (reds for 0s and green for 1s or any other color coding). How do I accomplish this using R? you can show me using any example dataset with just ones and zeros (binary values).

A: Just another approach using ggplot
library(ggplot2)
library(reshape2)
library(plyr)
library(scales)

df <- structure(list(people = structure(c(2L, 1L), .Label = c("Dwayne", "LeBron"), class = "factor"),
                 G = c(1L, 0L),
                 MIN = c(1L, 0L),
                 PTS = c(0L, 1L),
                 FGM = c(0L,0L),
                 FGA = c(0L,0L),
                 FGP = c(1L,1L)),
            .Names = c("people", "G", "MIN", "PTS", "FGM", "FGA", "FGP"),
            class = "data.frame",
            row.names = c(NA, -2L))

df.m <- melt(df)
df1.m <- ddply(df.m, .(variable), transform, rescale = value)
p <- ggplot(df1.m, aes(variable, people)) +
geom_tile(aes(fill = rescale), colour = "black")
p + scale_fill_gradient(low = "green", high = "red")
show(p)

Adopted from this tutorial

A: With highcharter:
library(highcharter)
library(tidyr)
library(dplyr)
df<-data.frame(row=c("Dwayne","James"),G=c(1,0),MIN=c(1,0),PTS=c(0,1),FGM=c(0,0),FGA=c(0,0),FGP=c(1,1))
rownames(df)<-c("Dwayne","James")
df$row<-rownames(df)
data<-df%>%
     tidyr::gather(row,value)%>%
     setNames(c("name","variable","value"))

hchart(data, "heatmap", hcaes(x = variable, y = name, value = value)) %>%
  hc_colorAxis(stops = color_stops(2, c("red","green")))

UPDATE:
You can add hc_size(height = 800) for height=800 or make something like that
  x<-50
  hg<-length(unique(data$name))*x+100

  hchart(data, "heatmap", hcaes(x = variable, y = name, value = value)) %>%
    hc_colorAxis(stops = color_stops(2, c("red","green")))%>%
    hc_size(height = hg)

Where each row in dataset makes chart bigger by 50 points. You can change it  in x

A: This answer uses plotly and hence adding it as another answer. Using the same data as the following one.
library(plotly)
df1 <- as.matrix(df)
p <- plot_ly(x = colnames(df), y = df[,1], z = as.matrix(df[-1]), colors = colorRamp(c("green", "red")), type = "heatmap")

This is much simpler than the ggplot2 in terms of getting the output.
Hope this helps!


text:
Q: Do BoS Knights/Paladins/etc. stop dropping holotags? Under what circumstances would Brotherhood of Steel Knights, Paladins, etc. stop dropping holotags? I got on their bad side by killing the ones outside GnR Studio, but they were dropping them. However, the three Knights inside didn't drop holotags.
Is that normal for those three, did I encounter a bug, or do they stop dropping holotags once you've gotten on their bad side?

A: You probaly encountered a bug, as every member of the Brotherhood of Steel, just like soldiers of the US Army they are descended from, wears a set of two Holotags around their neck. They contain essential personal and medical information about the wearer and can be collected if the wearer is killed.


text:
Q: complex permission system for sails.js / angular I plan to build a few apps with sailsjs and angularjs
I need help to find a solution to set flexible permissions. It means that I can manage permissions on models (CRUD) and model-functions. It should also be possible to limit access to objects in models (e.g. User can modify only customer in USA but can also read customer in Europe / user has no right to see the address from customer). Does anyone know an existing solution for that?
Or can you give me a hint how to implement an own complex permission system?
Thank you for help, Nick.

A: Policies seem to be what you are looking for. http://sailsjs.org/#!documentation/policies
You can use them to protect resources, and fundamentally they are just middleware, so you can use Passport.js etc.
For the angular side, I would use a global Http Interceptor, to handle the non-200 responses returned by Sails

*

*https://docs.angularjs.org/api/ng/service/$http

*http://blog.thesparktree.com/post/75952317665/angularjs-interceptors-globally-handle-401-and-other


text:
Q: Issue rendering .NET form in Windows 7 vs XP I'm working an a form with a progressbar, which is meant to have certain colors (foreground and background). On my XP machine, the colors are correct. On my Windows 7 machine, the form looks all sexified (just like all the other windows 7 windows) and the color is not what I had set in the designer.
Is there some sort of style option that is overriding my form drawing?

A: Remove calls to Application.EnableVisualStyles();


text:
Q: Shell script to grep in a range of files I'm setting up a script which takes some user data with the read command. Using this data I need to search the file range and then do some filtering.
Here's how it is,
Enter fromtime

read fromtime

Enter totime

read totime

Enter the ID

read id

Initially I SSH into a server and then there I have a directory, Records with path cd home/report/records here, I have:

*

*REC_201901020345.gz (yyyymmddhhmm)

*REC_201901120405.gz

*REC_201903142543.gz
and so on.
These files have data along with the $id.
When the user inputs $fromtime and $totime it will be of format yyyymmddhh . Here, I need to go to that range of files and then grep for the $id and display. For example:
If $fromtime is 2019010103 and $totime is 2019031425. I need to go to only those specific range of files that is REC_201901020345.gz, REC_201901120405.gz, REC_201903142543.gz and perform the grep to find the id entered by the user.
I have tried this using an if condition but it doesn't seem to work. I am new to writing scripts like these. There might be mistakes when I have described everything here. Sorry for the same.
source config.sh

Enter fromtime

read fromtime

Enter totime

read totime

Enter the ID

read id

ssh $user@$ip

cd /home/report/records

# <-- need to know what to add here as described here, to navigate to the
# <-- specific range $fromtime-$totime. Then the command to find id will be

zfgrep $id *.gz

The result should be only the the data with the id's in the specified range of .gz files.

A: Try below command.
echo -e "$(ls -1 REC_????????????.gz 2>/dev/null)\nREC_${fromtime}##\nREC_${totime}##" | sort | sed -n "/##/,/##/p" | sed '1d;$d' | xargs zfgrep -a "$id"

Explanation:
'fromdate' and 'todate' along with a ## (say marker) is appended to the output of ls.
Sorted the input, resulting in desired file names enclosed with marker.
Both sed, prints only lines between marker.
Last one is the command, supposed to be executed for each file name.
You can omit pipes and all next commands, starting from end, and see how output is building.

A: To get the list of files within the given range (fromtime, totime), the following shell script may be used:
declare -i ta
for file in REC*.gz
do
    ta=$(echo "${file}" | grep -oP 'REC_\K(.*)(?=[[:digit:]]{2}.gz)')
    if [ "${ta}" ] ; then
       if [ ${ta} -le ${totime} -a ${ta} -ge ${fromtime} ] ; then
          echo -e "${file}"
       fi
    fi
done


text:
Q: Extract plain text excerpt from HTML I have @Html.Raw(Model.Content) in a razor page, I want to extract excerpt (plain text) truncated at word boundary near to 232-240 characters, followed by .... Is there any helper for all this?
Something equivalent to Ruby on Rail's truncate_html gem. Usage:
strip_tags(truncate_html(my_model.content, :length => 240, :omission => '...'))

A: Solved it with these extension methods:
public static string TruncateHtml(this string input, int length = 300,
                                   string ommission = "...")
{
    if (input == null || input.Length < length)
        return input;
    int iNextSpace = input.LastIndexOf(" ", length);
    return string.Format("{0}" + ommission, input.Substring(0, (iNextSpace > 0) ?
                                                          iNextSpace : length).Trim());
}

public static string StripTags(this string markup)
{
    try
    {
        StringReader sr = new StringReader(markup);
        XPathDocument doc;
        using (XmlReader xr = XmlReader.Create(sr,
                           new XmlReaderSettings()
                           {
                               ConformanceLevel = ConformanceLevel.Fragment
                               // for multiple roots
                           }))
        {
            doc = new XPathDocument(xr);
        }

        return doc.CreateNavigator().Value; // .Value is similar to .InnerText of
                                           //  XmlDocument or JavaScript's innerText
    }
    catch
    {
        return string.Empty;
    }
}

Usage:
@Html.Raw(Model.Content.StripTags().TruncateHtml(240, "..."))

A: You can create your own method, see this example where we create it as an extension.
You can then use it like this "String with a lot of text".TrimString(11);
Output will be "String with..."
You should be able to add logic to not break within a word.
public static string TrimString(this string text, int length = 300)
{
    if (text.Length > length)
    {
        return text.Substring(text.Length - (length - 3)) + "...";
    }

    return text;
}


text:
Q: React Native - Can not create new project via react-native-cli when react-native version is > 0.55 I am trying to create new project via react native project via react-native-cli react-native init ProjectName and get the following error

error Found incompatible module info
Visit https://yarnpkg.com/en/docs/cli/add for documentation about this
Error: Command failed: yarn add react-native --exact

Project can be created with the same command  when react native version is less then or equal to  0.54
react-native init ProjectName --version react-native@0.54

The following links also did not helped me.
https://github.com/facebook/react-native/issues/14861
https://github.com/yarnpkg/yarn/issues/3227

A: I solve the problem just moment.
the reason is node version problem.
you can install >10.0 node.
then, react-native init project succeed.

A: I came across similar issue. Following are the steps I took to solve it.

*

*Noticed the yarn error occurs due to incompatible node module version. It required node version >= 8.0. For this, I changed the node version using nvm:
nvm use 8.0.0
Note: Check first if you have a installed node version >= 8.0 using nvm list. If yes, just use the above command. Otherwise install it by nvm install v8.0.0.

*After this, you might come across similar error for npm. I did not have updated npm version. Install latest npm by npm install -g npm@latest
Try to create new react-native project, react-native init HelloWorld.


text:
Q: php unexpected end of file on closing html tag I have a PHP register form and every time I enter a name and password into the form it says "unexpected $end on line 52". The code is below for the index:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<form action="handler.php" method="post">

Register

<input type="text" name="username" />

<input type="password" name="password" />

<input type="submit" value="submit" />
</form>

handler:
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<?php

$username = $_POST['username'];
$password = $_POST['password'];
$counter = 0;

class MyDB extends SQLite3
   {
      function __construct()
      {
         $this->open('db/test.db');
      }
   }
   $db = new MyDB();

$sql =<<<EOF
    SELECT username from users WHERE username='$username';
EOF;

$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC)){
    $counter++;
}

if($counter >= 1){
    echo "user already exists. click here  to go back";
}

if($counter = 0){
    $_SESSION['username'] = $username;
    $_SESSION['password'] = $password;
    $sql2 =<<<EOF
    INSERT INTO users(ID, username, password) VALUES (null, '$username', '$password');
    EOF;
    header('Location: index.php');
}

?>

A: As the documentation mentions, heredoc closing tags cannot be indented, or in fact cannot contain any other characters.
So your second EOF should be like this:
if($counter == 0){ //Need to validate if the counter is 0
    $_SESSION['username'] = $username;
    $_SESSION['password'] = $password;
    $sql2 =<<<EOF
    INSERT INTO users(ID, username, password) VALUES (null, '$username', '$password');
EOF;
    header('Location: index.php');
}

(Also note the $counter == 0 change as suggested by jqheart)
(In fact, for this particular case I think it would be better to use a regular string as it would make the code cleaner)


text:
Q: C++ change base's member variable and print it from derived class The idea is:

I've 2 classes, one named Print with only one method called printName, and other class named Human with variable name. I want printName to print whatever the name variable in the Human class is.

Example:
class Print {
public:
    char name[255];  // name will be overridden from Human class.
    void print() { std::cout << name << std::endl; }  // `this.name` should be from Human class.
};

class Human : public Print {
public:
    char name[255];
};

int main() {
    Human h;
    h.name = "Somename";
    h.print(); // Should outputs: Somename
}

A: One of the solutions: Curiously Recurring Template Pattern 1, 2.
template <typename T>
class Print {
public:
    char name[255];
    void print() { std::cout << static_cast<T*>(this)->name << std::endl; }
};

class Human : public Print<Human> {
public:
    char name[255];
};

int main() {
    Human h;
    h.name = "Somename";
    h.print(); // Outputs: Somename
}

h.name = "Somename" will not compile.


text:
Q: SSH on mac 10.11.5 suddenly stopped working SSH was working nicely on mac 10.11.5 for a long time now.
Suddenly after installing Ansible it stopped working.
All I get when I try to connect to remote host is
this. Note: I gave replaced the server IP address with a dummy one.
iMac:~ mohamedsaleh$ ssh -v root@123.456.789.000
OpenSSH_7.3p1, OpenSSL 1.0.2h  3 May 2016
debug1: Reading configuration data /usr/local/etc/ssh/ssh_config
debug1: Connecting to 123.456.789.000 [138.68.60.62] port 22.
debug1: Connection established.
debug1: identity file /Users/mohamedsaleh/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/mohamedsaleh/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/mohamedsaleh/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/mohamedsaleh/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/mohamedsaleh/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/mohamedsaleh/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/mohamedsaleh/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/mohamedsaleh/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.3
ssh_exchange_identification: read: Operation timed out

Update: I have tried on several machines and all have the same issue.
Update2: I have tried using VPN and it works normally, after investigation it seems that my ISP have closed that port for random reason.

A: You might want to delete your locally stored ssh keys

Here is quick fix that worked for me

Go to the directory that stores your ssh keys
cd ~/.ssh/

Remove the known_hosts folder that has all your ssh keys that you previously used
rm known_hosts

Try to connect again to your remote server and provide your password once prompted.


text:
Q: Common styles for v10 and v11+? I'm using the v7 support library in order to have an ActionBar on API Level 10+ (that's Android 2.3.3+). Now, I want to customize the look a bit, so I added an application theme. Excerpt of my values/styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="actionBarStyle">@style/ActionBarStyle</item>
</style>

<style name="ActionBarStyle" parent="@style/Widget.AppCompat.ActionBar">
    <item name="background">@drawable/bg_actionbar</item>
</style>

This works fine on Android 2.3.3, where the compat stuff is used. However, on Android 4.3 on an N4 (or an emulator), the styles are not applied. If I change the styles.xml file to:
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="android:actionBarStyle">@style/ActionBarStyle</item>
</style>

<style name="ActionBarStyle" parent="@style/Widget.AppCompat.ActionBar">
    <item name="android:background">@drawable/bg_actionbar</item>
</style>

(notice the added android: prefix) it works on 4.3, but doesn't on 2.3 (styles not applied).
Is there any way I can get around this without specifying each <item> twice, once with the prefix and once without?

A: There is a perfect example on the google docs site:
http://developer.android.com/guide/topics/ui/actionbar.html#StyleExample
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.AppCompat.Light">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
        <item name="android:actionBarTabTextStyle">@style/TabTextStyle</item>
        <item name="android:actionMenuTextColor">@color/actionbar_text</item>

        <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/MyActionBar</item>
        <item name="actionBarTabTextStyle">@style/TabTextStyle</item>
        <item name="actionMenuTextColor">@color/actionbar_text</item>
    </style>

    <!-- general styles for the action bar -->
    <style name="MyActionBar"
           parent="@style/Widget.AppCompat.ActionBar">
        <item name="android:titleTextStyle">@style/TitleTextStyle</item>
        <item name="android:background">@drawable/actionbar_background</item>
        <item name="android:backgroundStacked">@drawable/actionbar_background</item>
        <item name="android:backgroundSplit">@drawable/actionbar_background</item>

        <!-- Support library compatibility -->
        <item name="titleTextStyle">@style/TitleTextStyle</item>
        <item name="background">@drawable/actionbar_background</item>
        <item name="backgroundStacked">@drawable/actionbar_background</item>
        <item name="backgroundSplit">@drawable/actionbar_background</item>
    </style>

    <!-- action bar title text -->
    <style name="TitleTextStyle"
           parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
        <item name="android:textColor">@color/actionbar_text</item>
    </style>

    <!-- action bar tab text -->
    <style name="TabTextStyle"
           parent="@style/Widget.AppCompat.ActionBar.TabText">
        <item name="android:textColor">@color/actionbar_text</item>
    </style>
</resources>

A:
Is there any way I can get around this without specifying each <item>
  twice, once with the prefix and once without?

Another way would be to create version specific res/values-XX folders.
Since the divide is version 10 and versions 10+, you can create res/values-v10/styles.xml containing:
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="actionBarStyle">@style/ActionBarStyle</item>
</style>

<style name="ActionBarStyle" parent="@style/Widget.AppCompat.ActionBar">
    <item name="background">@drawable/bg_actionbar</item>
</style>

Let versions 10+ deal with the default res/values/styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="android:actionBarStyle">@style/ActionBarStyle</item>
</style>

<style name="ActionBarStyle" parent="@style/Widget.AppCompat.ActionBar">
    <item name="android:background">@drawable/bg_actionbar</item>
</style>

Still, it isn't much different from specifying <item></item> twice.
For reference, you can look at the project structure of ActionBarSherlock. That should provide you some pointers.
You can also take a look at: Applying Styles and Themes to the UI. Scroll down to sub-section Select a theme based on platform version.

A: If I have not misunderstand your issue, you can collapse it together this way
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="android:actionBarStyle">@style/ActionBarStyle</item>
    <item name="actionBarStyle">@style/ActionBarStyle</item>
</style>

<style name="ActionBarStyle" parent="@style/Widget.AppCompat.ActionBar">
    <item name="android:background">@drawable/bg_actionbar</item>
    <item name="background">@drawable/bg_actionbar</item>
</style>

In my experience, this way eclipse gives compile time errors every time you change somethings inside styles.xml (due of lint if I remember good), but clean and rebuild make those errors go away.


text:
Q: Finite abelian subgroups of $\mathrm{SL_2}(\mathbb{C})$ This problem is from a Ph.D Qualifying Exam for algebra.

Question: Classify all finite abelian subgroups of $\mathrm{SL_2}(\mathbb{C})$ up to isomorphism.

My attempt: First, given a positive integer $n$, I tried to find an element of $\mathrm{SL_2}(\mathbb{C})$ of order $n$, and that was easy; a rotation by $2\pi/n$ radians. Therefore, for every $n\ge 1$, $\mathbb{Z}_n$ is a subgroup of $\mathrm{SL_2}(\mathbb{C})$.
My conjecture is that there are no other finite abelian subgroups than what I mentioned above, and I have to prove or disprove it, and here is where I stuck.
Does anyone have ideas?
Any hints or advice will help a lot!

A: In his "Vorlesungen über das Ikosaeder" [Klein, 1993],
published in 1884, Felix Klein gives the classification of all finite subgroups of
$SL(2,\Bbb{C})$ up to conjugacy. The abelian ones are just the cyclic groups $\Bbb{Z}/n\Bbb{Z}$ for all $n\in \Bbb{N}$. For a proof see here.

A: Well a finite abelian subgroup has finite exponent $n$, and so all its elements are roots of $X^n-1$ and so its elements are codiagonalizable.
Now a diagonal element of $SL_2(\mathbb{C})$ is essentially an element of $\mathbb{C}^\times$; but here it has finite order. Hence your subgroup is isomorphic to $\mathbb{Z}/n\mathbb{Z}$ (details left to the reader)
Conversely, of course any such group is a subgroup of $SL_2(\mathbb{C})$. Note that this actually yields a characterization up to conjugacy, so better than up to isomorphism


text:
Q: c++ use thread as timer I have my project with a different thread that make some stuff.
It's all ok, but I wish have some function called each 20ms (for example), but considering the time spent to the function... I try to explain better... I call the function, and the function spent 6ms to exit, so I wish that the thread sleeps 14ms (20 - 6), the next time that is called, the function spent 12ms, so the sleep will be only 8ms....
how can I do this?
here is my code:
// thread constructor
DWORD dwThreadId, dwThrdParam = 1;
HANDLE thread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)workerFunc, &dwThrdParam, 0, &dwThreadId );

// thread function
DWORD WINAPI workerFunc( LPDWORD lpdwParam )
{
    while( true )
    {
        myFunction( );
        Sleep( ??? );
    }
    return 0;
}

thanks!

A: What about this:
clock_t start, end;
while( true )
{
    start = clock();
    myFunction( );
    end = clock();
    Sleep(20-(end-start)*CLOCKS_PER_SEC/1000.0);
}

A: A simple approach would be to send the thread to sleep for a variable amount of time:
void periodic_function()
{
  /* function body */

  timestamp = get_time(); // pseudo-function
  remaining_sleep_time = std::min(0, 20 - (timestamp - last_timestamp));
  last_timestamp = timestamp;
  milli_sleep_callback(remaining_sleep_time, periodic_function);
}

You'll need a suitable steady clock function for get_time() and a sleep function - try the <chrono> or <tr1/chrono> header. In this example I've assumed that you have a timer callback (like in boost.ASIO), but you could also make an infinite loop or something like that.
This function will work if the function body never exceeds 20ms, though it'll do a quick catch-up if your function ever takes longer. If you want to synchronize to a global 20ms rhythm, you'd have to add another global step counter or something like that.

A: Use GetTickCount before calling myFunc and after calling myFunc. The difference gives you the time spent in myFunc. Note that this time includes the time spent by the process due to OS scheduling.

A: If you need precision, use NtSetTimerResolution when program starts up to set timer resolution. Yes, it is undocumented function, but works well. You may also use NtQueryTimerResolution to know timer-resolution (before setting and after setting new resolution to be sure).
You need to dynamically get the address of these functions using GetProcAddress from NTDLL.DLL, as it is not declared in header or any LIB file.
Setting timer resolution this way would affect Sleep, Windows timers, functions that return current time etc.


text:
Q: Table of points from a smooth function Given a function, say $\sin x$, can I cast this into a table of points with discretely divided values of $x$? Ideally, I would end up with a table of $xy$-values, where $x$ is the running variable and $y$ is the corresponding value of $\sin x$.

A: data = {#, Sin[#]} & /@ Subdivide[2 \[Pi], 20];
TableForm[data,
 TableHeadings -> {None, {"x", "sin(x)"}}]


text:
Q: Does tanz assumes all complex numbers? $f(z)=tanz$,$z$ $\in$ $C$
a)assumes all complex numbers
b)assumes none of complex numbers
c)assumes all complex numbers except $i$
d)assumes all complex numbers except $i$ and $-i$
I think answer is c, please help me!
I find that $tanz=-i$$\frac{e^{iz}-e^{-iz}}{e^{iz}+e^{-iz}}$. What is the next step?

A: (b) is obviously false, given that e.g. $\tan(i)$ is not purely real.
As pointed out in comments, if there is no number $z$ such that $\tan(z)=i$, there is also no number $z$ such that $\tan(z)=-i$. So (c) cannot be true.
This leaves (a) or (d), and if you already know that (a) is false, that leaves only (d).


text:
Q: Equation for reducing leave to zero I'm not a mathematician at all, but I'm looking for a formula that will help with the following problem:
It's coming up to Christmas and our employees want to take leave, but some employees will have accrued less leave than than the amount they wish to take in which case they are entitled to take all of their leave and the rest will be unpaid leave.
The problem is, that for every hour of leave paid to an employee, they are entitled to accrue an additional 0.038462 hours of leave, so as they take leave, they also accrue leave, which in turn they are entitled to take. The problem is, this makes it very hard to work out how much leave to give them so that their leave balance comes to 0
To give an example, I have an employee that currently has 10 hours leave but wants to take 20 hours all up.
Since he takes 10 hours leave, he will accrue 10 x 0.038462 in leave for that pay run. So he's actually is entitled to take 10.38462 hours leave.
So I change his leave taken to be 10.38462, but that means he accrues an additinal 0.0147932 hours of leave which you add on to the 10.38462 which then accrues another amount of leave and so on.
So what I'm wondering is, if there's a formula that I could use to work out how much leave an employee could be paid given that every time they take leave, an additional amount of leave is accrued?

A: Yes. Multiply the number of hours by 1.04.
For every one hour of leave, an employee gains an additional $x$ hours ($x$ being 0.038462 in this case). And for these $x$ hours of additional leave, the employee gains an additional $x \times x = x^2$ hours of leave, and so on.
So an employee entitled to $N$ hours of leave can actually take
$$N(1 + x + x^2 + x^3 + ...)$$
hours. This is called a Taylor series. As long as $-1 \le x \le +1$, it adds up to
$$\frac{N}{1 - x}$$
For $x$ = 0.038462, this comes out as very close to 1.04. So close, in fact, that I expect 1.04 is the exact figure, and the number you've been using is actually an approximation of $1 - \frac{1}{1.04}$.

A: Let $x$ be the amount of leave they end up taking and $a$ the amount they have already accrued.  Their total leave $x$ should be the leave they already have plus the leave they will accrue while on leave, so
$$x = a + 0.038462x$$
You can solve this for $x$ to get
$$x = \frac{a}{1 - 0.038462}$$


text:
Q: iOS App freezes at splash screen when user enables "Bold Text" on System Settings -> Display and Brightness My app freezes on the splash screen when "Bold Text" is enabled in System Settings -> Display and Brightness on iOS 13.
If the app is installed on an iPhone 11 there is no problem but when the app is installed in a previous iPhone (X, XS, 8, 8S...) it freezes on splash screen and the only way to fix it is to:

*

*Close the app from the application switcher if it is present

*Go to Settings -> Display and Brightness

*Turn off "Bold Text"

*Open the app again.

XCode doesn't show me any crash or any other information when I debug my iPhone 6S or iPhone XS.
Can someone help me?
Thank you so much

A: Solved.
When "Bold Text" was enabled in System Settings -> Display and Brightness on iOS 13, I was unable to set the frame of a view and this caused a loop in my app. I can't understand why this don't happen when bold text is disabled on the display and brightness system settings...


text:
Q: If analytic function F is real on the part of unit circle, then F is constant.
Let $F(z)$ be analytic function defined in the disk $|z|<2$. Assume
that $F( \zeta)$ is real for $\zeta$ belonging to an arc of $|\zeta |
 =1$. Prove that $F$ is constant.

I've encountered this problem, and my idea was using maximum modulus principle or reflection principle. But I'm not sure how to start proof.


text:
Q: How to export a dataframe which only contains date in another list in pandas? I have a list contains date
a = ['1997-01-01','1997-01-03','1997-01-18','1997-01-29']

and there is also a dataframe contains date and strings

date
strings

1997-01-01
nice to meet you

1997-01-01
hi

1997-01-02
who are you?

1997-01-02
Same question

1997-01-18
Again

1997-01-29
idk

1997-01-29
me too

1997-01-30
newstring

I want to export this dataframe where the date in list a. I tried for loop, but it did not give me any outputs.
for i in a:
    df[df['date'] == i]


text:
Q: regex to extract numbers starting from second symbol Sorry for one more to the tons of regexp questions but I can't find anything similar to my needs. I want to output the string which can contain number or letter 'A' as the first symbol and numbers only on other positions. Input is any string, for example:
---INPUT---    -OUTPUT-
A123asdf456 -> A123456
0qw#$56-398 -> 056398
B12376B6f90 -> 12376690
12A12345BCt -> 1212345

What I tried is replace(/[^A\d]/g, '') (I use JS), which almost does the job except the case when there's A in the middle of the string. I tried to use ^ anchor but then the pattern doesn't match other numbers in the string. Not sure what is easier - extract matching characters or remove unmatching.

A: I think you can do it like this using a negative lookahead and then replace with an empty string.
In an non capturing group (?:, use a negative lookahad (?! to assert that what follows is not the beginning of the string followed by ^A or a digit \d. If that is the case, match any character .
(?:(?!^A|\d).)+

var pattern = /(?:(?!^A|\d).)+/g;
var strings = [
  "A123asdf456",
  "0qw#$56-398",
  "B12376B6f90",
  "12A12345BCt"

];

for (var i = 0; i < strings.length; i++) {
  console.log(strings[i] + " ==> " + strings[i].replace(pattern, ""));
}

A: You can match and capture desired and undesired characters within two different sides of an alternation, then replace those undesired with nothing:
^(A)|\D

JS code:

var inputStrings = [
    "A-123asdf456",
    "A123asdf456",
    "0qw#$56-398",
    "B12376B6f90",
    "12A12345BCt"
];
console.log(
    inputStrings.map(v => v.replace(/^(A)|\D/g, "$1"))
);

A: You can use the following regex : /(^A)?\d+/g

var arr = ['A123asdf456','0qw#$56-398','B12376B6f90','12A12345BCt', 'A-123asdf456'],
    result = arr.map(s => s.match(/(^A|\d)/g).join(''));
console.log(result);


text:
Q: Unity,When I package an empty scene, the GPU usage reaches 100%!!! [[enter image description here](https://i.stack.imgur.com/orTud.png)](https://i.stack.imgur.com/C67tO.png)
I didn't do anything, just packed an empty scene, with this graphics card it reached 100%
I used Unity 2021, 2019, 2017 have the same problem, what is the problem?


text:
Q: Call to GetPrivateProfileString on kernel32 using Python C-types I try to use GetPrivateProfileString to edit ini files.It work on vb, so I try to put it in python.
from ctypes import *
def GetINIKey2(inipath,Content,itemname):
  kernel32 = windll.LoadLibrary("kernel32.dll")
  GetPrivateProfileString = kernel32.GetPrivateProfileStringA
  returnstring = c_wchar_p("")
  lpApplicationName = c_wchar_p(Content)
  lpKeyName = c_wchar_p(itemname)
  lpDefault = c_wchar_p('defalut')
  lpReturnedString = returnstring
  nSize = c_int(256)
  lpFileName = c_wchar_p(inipath)

  returnval = GetPrivateProfileString(byref(lpApplicationName),byref(lpKeyName),byref(lpDefault),byref(lpReturnedString),byref(nSize),byref(lpFileName))

  print(returnval)
  print(returnstring.value)

GetINIKey2("C:\test.ini","server","servername")
Follow is the ini file:
[server]
servername = 192.168.11.1
serverport = 8000

The returnstring.value should be "192.168.11.1", but it always be "default" which is lpDefault's value. What wrong with the code?


text:
Q: Flask wtform labels does not render after deleting flask-bootstrap I changed my mind about using flask-bootstrap and uploaded my CSS. But after that, all labels disappeared in my form. Only the fields themselves remained. What am I doing wrong?
These are HTML:

{% block content %} {% block prepare %}

<form action="" , method="post" , novalidate, class="Preparation_area">

Prepare Data

  {{ prepare_form.hidden_tag() }}

    {{ prepare_form.archive.label }} {{ prepare_form.archive }} {{ prepare_form.select_order.labe }} {{ prepare_form.select_order }} {{ prepare_form.h_back.labe }} {{ prepare_form.h_back(size=3) }} {{ prepare_form.min_deep.labe }} {{ prepare_form.min_deep
    }} {{ prepare_form.max_deep.labe }} {{ prepare_form.max_deep(size=4) }} {{ prepare_form.groupping.labe }} {{ prepare_form.groupping(size=3) }} {{ prepare_form.sort_levels.labe }} {{ prepare_form.sort_levels }} {{ prepare_form.submit_prepare() }}

</form>
{% endblock %} {% block content %}

These are FORMS:

class Prepare(FlaskForm):
    archive = FileField(label='Upload archive', validators=[FileRequired(), regexp('[\w-].xlsx$')])
    select_order = SelectField(label='Select order', choices=['5-1','5-2','5-3','5-4','5-5','2-1','2-2'], validate_choice=True)
    h_back = StringField(label='h-back', validators=[DataRequired()], render_kw={"placeholder": "10"})
    min_deep = StringField(label='minDeep', validators=[DataRequired()], render_kw={"placeholder": "1"})
    max_deep = StringField(label='maxDeep', validators=[DataRequired()], render_kw={"placeholder": "20"})
    groupping  = StringField(label='Groupping', validators=[DataRequired()], render_kw={"placeholder": "0"})
    sort_levels = SelectField(label='Sort.Lev.', choices=['No','sort_1','sort_2','sort_3'], validate_choice=True)
    submit_prepare = SubmitField(label='Preparate Data')

These are ROUTES:
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
@login_required
def index():
    prepare_form = Prepare()

    if prepare_form.validate_on_submit():
        if prepare_form.validate_on_submit():
            archive = prepare_form.archive.data#request.FILES[prepare_form.archive.name].read()
            select_order = prepare_form.select_order.data
            h_back = prepare_form.h_back.data
            min_deep = prepare_form.min_deep.data
            max_deep = prepare_form.max_deep.data
            groupping = prepare_form.groupping.data
            sort_levels = prepare_form.sort_levels.data
            flash(h_back, min_deep, max_deep)

    predict_form = Predict()

    return render_template('index.html', prepare_form=prepare_form, predict_form=predict_form)

And these ar CSS
html {
    background-color: #1f1e1e;
    font-size: 12px;
    font-family: 'Open Sans', sans-serif;
    color:aliceblue
  }

body {
  padding: 10px 0px 0px 0px;
  }

.Preparation_area {
  padding-left: 20px;
  margin: 10px 0px 10px 0px;
  border-radius: 10px;
  border: 1px solid black;
  background-color:#333232;
  display: flex;
  }

h3 {
  margin-top: -10px;
  width:fit-content;
  padding: 0px 2px 0px 2px;
  font-size: 14px;
  color: aliceblue;
  }

Thank you for your help!

A: Thanks to furas. He found my stupid mistake


text:
Q: How to destroy MockRestServiceServer? We are using RestTemplate to consume external rest services. There lot of different kinds of services in our project and all of them are tested using different strategies like mocking rest template and mocking our communication object.
We have used below code in our test case to test one service using MockRestServiceServer :
RestTemplate restTemplate = new RestTemplate();
mockServer = MockRestServiceServer.createServer(restTemplate);

So our question is :
Is there a way to destroy this server as soon as this test case completes so this doesn't affect other test cases?

A: First and foremost, the MockRestServiceServer is not a real server -- for example, it is not listening on a TCP port. The only thing the MockRestServiceServer does is modify your RestTemplate (see details below).
So to answer your question: there is no server to destroy.
However... if your RestTemplate is created in your ApplicationContext and injected into multiple components (e.g., in your service layer), you may want to reset the initial state of the RestTemplate. If that's the case, read on...
There is currently no "official" way to reset the RestTemplate passed to MockRestServiceServer.createServer(), but that doesn't mean you can't implement such a feature on your own.
The key to understanding this is knowing that the MockRestServiceServer.createServer() method replaces the ClientHttpRequestFactory in the provided RestTemplate with a mocked version (i.e., the private, internal MockRestServiceServer.RequestMatcherClientHttpRequestFactory).
So you should be able to reset the original state of the RestTemplate by tracking the original request factory and setting it in the template after your test. Something like the following should work:
RestTemplate restTemplate = // likely injected into the test
ClientHttpRequestFactory originalRequestFactory = restTemplate.getRequestFactory();
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);

try {
    // use mockServer as usual...

    mockServer.verify();
} finally {
    restTemplate.setRequestFactory(originalRequestFactory);
}

Let me know if that solves your problem!
Cheers,
Sam (author of the Spring TestContext Framework)


text:
Q: Multiplicities and ternary relations in UML and ER With entity–relationship diagrams, there are two conventions of denoting multiplicities, (I) and (II):
Say, a teacher T is giving ‹G› some lectures L. Then we can either write this as
        1       M
 (I)  T ———‹G›——— L,

reading

"Every teacher is giving multiple lectures and every lecture is given by exactly one teacher.",

or as
        M       1
(II)  T ———‹G›——— L,

reading

"Any teacher participates in multiple giving-relations and any lecture participates in exactly one giving-relation".

The picture becomes more complicated when we introduce ternary relations, say we want to express that a teacher is giving lectures in a certain room R:
       1       ?                  M       1
 (I) T ———‹G›——— L    and  (II) T ———‹G›——— L
           |                          |
           | ?                        | MC
           R                          R

Whereas I can interpret (II) by reading it as

"Any teacher participates in multiple giving-relations, any lecture participates in exactly one giving-relation, and any room participates in none or multiple giving-relations."

and everything makes perfect sense, I see no way to interpret or express the situation in the case of (I).
For example, we (still) want to say that

"Every lecture is being given by exactly one teacher in exactly one room."

So this seems to determine the multiplicity '1' at the teacher (as already put in). But then, from the perspective of the room, the relation would read as

"In every room, there are being given (multiple) lectures by exactly one teacher."

This is already false, as there might be many teachers giving lectures in a certain room.

As I understand is, interpretation (I) is used in UML class diagrams (and of course, sometimes for ER diagrams) – how is this resolved? What should I fill in for the question marks? Am I reading this stuff incorrectly?

A: I don't think UML prescribes the exact meaning. My impression is that UML limits itself to defining the possible number of things on each end.
For example, spinning up Sparx EA, I create a new basic UML model and a class diagram. I make a class "teacher" and a class "lecture"  I then draw an "aggregation" relationship from "lecture" to "teacher" such that the empty diamond is at the "teacher" end.
(This seems to be roughly what you have in mind above)
UML (Sparx) then happily allows me to assign multiplicities of "1-*" at each end. What EXACTLY aggregation means is not clarified by UML. I think this sort of lingering "exercise left to the reader" ambiguity is one reason that UML does not attempt to prescribe the behavior of code generators.
Hope this helps...


text:
Q: Batch files datetime I have written a batch file. It's my first one so I still suck at this.  What it does it copies a database backup file from a unc folder path and paste it to my local machine.  The file name changes every night with the datetime appended to it.
i.e file_backup_201306112210.bak
Below is what I have written in my batch file below
set datetimef=%date:~-4%%date:~3,2%%date:~0,2%
cmd /c echo F | xcopy "\\FileName\S$\DBs\file_backup_%datetimef%*.bak" "E:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Data\file_backup.bak"

The weird thing is that it does work every now and then but other days it fails.  I have tried to run it manually but still fails.
Can you please advise what is wrong?

A: Try this and look in the log file to see:
A) if the server is accessible and
B) if a file exists that matches the filespec
@echo off
set datetimef=%date:~-4%%date:~3,2%%date:~0,2%
echo copying "file_backup_%datetimef%*.bak" on %date% at %time% >>"%userprofile%\desktop\log.txt"
dir "\\FileName\S$\DBs\file_backup_%datetimef%*.bak" >>"%userprofile%\desktop\log.txt" 2>&1

echo f|xcopy "\\FileName\S$\DBs\file_backup_%datetimef%*.bak" "E:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Data\file_backup.bak"

A: A bit confusing what exactly doesn't work, but there are several things you can do, for the date in your backup file name with date time:
@ECHO OFF
:: http://blog.g-ball.com/2010/08/26/year-month-day-date-batch-script/
:: Formatting the date into a YYYYMMDD format and setting it to the variable,  varTodaysDate
SET varYYYY=%DATE:~10,4%
SET varMM=%DATE:~4,2%
SET varDD=%DATE:~7,2%
SET varTodaysDate=%varYYYY%%varMM%%varDD%

If you have issues launching the batch, you might check if you are logged in when the batch is launched. Are you launching the batch file from a server management? If yes, you might check its configuration(Edit: Check with which account you run it, Run whether user is logged on or not option, and run the task, use the following user account: Administrator). If you have rights issues, I would recommand you CPAU, from http://www.joeware.net/freetools/tools/cpau/ .
It will run the batch as administrator, download it and include it as following:
CPAU.exe -u 1 -p 1 -ex "cmd /c echo F | xcopy "\\FileName\S$\DBs\file_backup_%varTodaysDate%*.bak" "E:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Data\file_backup.bak"" -wait > log.txt 2> ./logerror.txt

If you are doing xcopy from shared drives, you have to replace CPAU.exe -u username -p password, but I wouldn't recommand it, its a security vulnerability if someone gets your batch file. What I could recommand as contra, would be WinSCP with scripts to run the same functionality and copy from one directory to another one.