text:
Q: wrong header in bibliography & list of figures / tables I am finalizing a thesis and encountered an issue regarding the page header. During the thesis, the header is defined as the name of the current sections. As far as I understand the provided class, this is obtained by
\RequirePackage[automark]{scrlayer-scrpage}
\automark{section}

which is the way it is supposed to work. However, the first issue appears when there is a chapter without any section, i.e. chapter 6 is the conclusion without a 6.1. Then, 5.4, which was the previous section, is displayed throughout chapter 6. I fixed this by adding
\automark{chapter}

at the beginning of the conclusion. This works as intended, although there might be a more sophisticated and general solution to this problem.
However #2, after the conclusions, there is the bibliography, the list of figures and the list of tables. Only the bibliography has the header of either chapter 6 or section 5.4 (depending on whether i include the automark{chapter} command or not), the other lists show as intended in the header. So, there should be "bibliography" in the header of the bibliography. Unfortunately, I don't know how. The lists are generated by the commands
\printbibliography % Print literature
\listoffigures % Show list of figures
\listoftables % Show list of tables

without any further information on them, even in the class file.
Any suggestions are appreciated! Thanks in advance!
Please let me know if any required information is missing.

A: Suggestion for a onesided document:
\documentclass{scrreprt}
\usepackage{blindtext}% only for dummy text

\usepackage{scrlayer-scrpage}
\automark{chapter}
\automark*{section}

\begin{document}
\blinddocument
\blinddocument
\chapter{Foo}
\Blindtext[20]
\blinddocument
\end{document}

And one possibility for a twosided document:
\documentclass[twoside]{scrreprt}
\usepackage{blindtext}% only for dummy text
\usepackage[automark]{scrlayer-scrpage}
\automark[chapter]{chapter}
\automark*[section]{section}
\begin{document}
\blinddocument
\blinddocument
\chapter{Foo}
\Blindtext[20]
\blinddocument
\end{document}


text:
Q: how to receive/send multiple iOS push notifications I have implemented push notifications in my application and receiving them without any issue. Problem occurs when my app is in offline, if I send more than one notification at that time (eg.5 notifications), when my device comes to online it is receiving only the latest notification.
Even when I checked with the apple documentation it is clearly mentioned that APNS will retain only the latest push notification received from 3rd party server.
But how all the other apps like(social networking and chat apps) could able to send multiple notifications when device goes to online from offline.
Do we have to implement specifically or we have any 3rd party providers or frameworks which gives the service.
If any 3rd party providers are giving the service, how they are doing? does apple gives any feedback server whether the notification is delivered to the device or not so that our 3rd party server can send the undelivered message again?

A: You can resolve this by external services which gives you several advantages:
1) send push notifications asynchronouslly
2) send multiple push notifications
3) easilly subscribe unsubscribe
I have used Urban Airship and have been sutisfied.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ConvertFrom-StringData clear hash-table I am attempting to parse multiple mails in a specific mail folder, to eventually create a csv file with the information.
If I run the script on one user, the output I get is perfect;
Name                           Value
----                           -----
Kontor.                        HR
Prøvetid                       Ja
Blomster på dagen              Nej
Telefonnr.                     85789845
Adresse                        Hovedgade 13
Ansættes i stedet for          Ninette Kock
Navn                           Marianne Pedersen
Etage                          1. sal
Fri telefon                    Ja
Benyttet navn                  Marianne Pedersen
Medarbejdertype                Fastansat
Overtagelse af mobilnr.        Ja
Placering                      Sydøst
Ansættelsesdato                01-01-2020
Stilling                       Fuldmægtig
Lokalnr.                       +45 3370 0000
Besked til IT-centret
Antal timer                    37
Journalistpraktikant           Nej
Tidl. ansat                    Nej
Initialer                      MAPE
Blomster anden dag             02-01-2020
Postnr/By                      2630 Taastrup
Cpr. nr.                       XXXX

The problem is when I try to parse a second mail, the first mail will still get parsed correctly, but the second one will throw an error;
ConvertFrom-StringData : Data item 'Medarbejdertype' in line 'Medarbejdertype=Fastansat' is
already defined.

If I try to parse the second mail as the first mail, it will parse perfectly.
Problem happens when I try to parse more then one.
I have tried to clear the hash-table like so;
$data.clear()
clear-variable -name data
$data = @{}

But it somehow seems that the hash-table is not emptied?
The code I am using:
Clear-Host
$navne = "MAJE", "ASHO"

# create an instance of Outlook
Add-Type -AssemblyName "Microsoft.Office.Interop.Outlook"
$outlook = New-Object -ComObject Outlook.Application
$nameSpace = $outlook.GetNameSpace("MAPI")
$html = New-Object -ComObject "HTMlFile"

# Opens and save all mails in Nye Til Oprettelse in $mails.
$mails = $nameSpace.Folders.Item('hotline').Folders.Item('Indbakke').Folders.Item('@HOVSA''er').Folders.Item('@01Nye til oprettelse').Items | Select-Object -Property subject, htmlbody

# Loop over $mails, check if $navn = subject
foreach ($navn in $navne) {
    foreach ($mail in $mails) {
        if($mail | Where-Object {$_.subject -match "$Navn"}) {
            #$mail.HTMLBody
            # write data to $html, then find all <table> tags and parse that text.
            $html.IHTMLDOCUMENT2_write($mail.HTMLBody)
            $data = $html.all.tags("table") | % innertext
            $data = $data -split '\r?\n' -match '^[^:]+:[^:]+$' -replace ':\s*', '=' -join "`n" | ConvertFrom-StringData
            $navn
            $data
            $data = @[]
           }
    }
}

A: You're appending each email to the $html document using $html.IHTMLDOCUMENT2_write($mail.HTMLBody), but you only initialise it once at the top of your script, so each time your foreach ($mail in $mails) loops you add another email to the document.
That means the second time the loop iterates there are two emails in the $html document and you're getting an error about duplicate data items as a result.
Try moving $html = New-Object -ComObject "HTMlFile" inside your foreach loop so it reads:
foreach ($mail in $mails) {
    ...
    $html = New-Object -ComObject "HTMlFile"
    $html.IHTMLDOCUMENT2_write($mail.HTMLBody)
    ...
}

P.S.: You might also want to look at using a non-COM library like the HTML Agility Pack to do your html processing - it'll potentially be a bit faster and more reliable (and portable) in an automation script than COM is.


text:
Q: Is there any hope of recovering this installation? I have a laptop that gets very hot and when it overheats it shuts down abruptly. By Sod's law this happened while I was updating to 11.04 (during the install phase, somewhere in the lib* section, so probably the worst time).
When I try to boot into Ubuntu now it cannot find the root filesystem, (I get the option to wait, skip mounting or enter a root terminal).  My laptop's keyboard has also decided not to work (this has happened before and it eventually came back, although I do think it's time for a new laptop) - luckily USB continues to work. I am able to boot into my Windows partition so I can assume the hard drive isn't smashed.
My question is how screwed is my Ubuntu install? I have quite a lot of data on the Ubuntu partition - is this lost or will I be able to access it via a live CD? How would I go about manually locating the filesystem in the root terminal? I don't mind reinstalling, but getting the data first is very important (yes, backup is quickly going to be sorted out, damned hindsight).

A: Your data is safe as long as you do not format the disc and the hard disc is healthy.
You can use your LiveCD without touching your current install so you are always safe using the LiveCD (that is the whole concept of the LiveCD ;-) ).
I have used the LiveCD before to save a couple of files to a USB drive (drag and drop from the desktop) and I did it with the tools we all use with normal gnome.
Yes, I can imagine you are panicking but rest assured: the LiveCD will come to your rescue. Your system will be fine! Except you do need to sort out that heating problem... it could bite you again when you (again) least expect it.
Good luck!!

A: You can backup your files booting into Windows or with a live CD. Please do it first.
Then I think you can boot a live CD and try to update your installation from it.


text:
Q: Golang Postgres connection string not opening return null I am sure that there is something with the connectionString as the values I am giving are the same values that I use in Java to log into the same database. This is my code
package main

import(
    "fmt"
    "database/sql"
    _ "github.com/lib/pq"

    "log"
)

func main() {

    db, err := sql.Open("postgres", "user=postgres password=password dbname=name sslmode=disable")

    if err != nil {
        log.Fatal(err)
    }

     defer db.Close()
    age := 21
    rows, err := db.Query("SELECT city FROM streams WHERE id=69", age)

    fmt.Println(rows)

}

I am using what I found here https://godoc.org/github.com/lib/pq my postgres version is 9.4 and my Go Version is 1.6 . I have no idea why it is happening.

A: Could you add the ping code and see what error is returned?
package main

import (
    "fmt"
    "database/sql"
    _ "github.com/lib/pq"

    "log"
)

func main() {

    db, err := sql.Open("postgres", "user=postgres password=password dbname=name sslmode=disable")

    if err != nil {
        log.Fatal(err)
    }

    err = db.Ping()
    if err != nil {
        log.Fatal(err)
    }

    defer db.Close()
    age := 21
    rows, err := db.Query("SELECT city FROM streams WHERE id=$1", age)

    fmt.Println(rows)

}

A: Your
 rows, err := db.Query("SELECT city FROM streams WHERE id=69", age)

has to be:
 rows, err := db.Query("SELECT city FROM streams WHERE id = ?", age)

also
 defer db.Close()

goes after you execute the query.


text:
Q: Combining arrays with React and Redux I have a chat widget that works like the facebook chat widget. I am now implementing an infinite loading of messages when i scroll up. The problem I am having now is how to combine the next range of messages to previous one, because currently it replaces the previous range when I call the next range. I have cut my code example for brevity:
constructor(props) {
  super(props);
  this.props.getMessages(1) // axios call, returns first range
}

handleScroll(event) {
  //some scroll logic
  this.props.getMessages(2)
  //axios call, returns 2nd range
  //for simplicity i just call 2 ranges for now
}

function mapStateToProps(state) {
  return {
    messages: state.messages
  };
}

export default function (state = {fetched: false}, action) {
  switch (action.type) {
      case 'FETCH_MESSAGES_FULFILLED':
          return {...state,
            data: action.payload
          }
      break;
   }
   return state;
}

data model:
[
        {
            msg_id: 1,
            to_id: 1,
            from_id: 2,
            message: "Marzipan jelly-o croissant sweet gummies chocolate croissant marzipan. Jujubes soufflé tiramisu halvah chocolate oat cake jelly1"
        },
        {
            msg_id: 2,
            to_id: 1,
            from_id: 2,
            message: "Jelly sw2"
        }
]

A: You wish to append messages to the data rather than replace it. You can simple do it with the spread operator syntax like
var initialState = {
    fetched: false,
    data: []
}
export default function (state = initialState, action) {
  switch (action.type) {
      case 'FETCH_MESSAGES_FULFILLED':
          return {...state,
            data: [...state.data, action.payload]
          }
      break;
   }
   return state;
}

This is assuming data to be an array.


text:
Q: Remove duplicate tuple pairs from PySpark RDD I am given a rdd.  Example:
test = sc.parallelize([(1,0), (2,0), (3,0)])
I need to get the Cartesian product and remove resulting tuple pairs that have duplicate entries.
In this toy example these would be ((1, 0), (1, 0)), ((2, 0), (2, 0)), ((3, 0), (3, 0)).
I can get the Cartesian product as follows: NOTE The collect and print statements are there ONLY for
troubleshooting.
def compute_cartesian(rdd):
    result1 = sc.parallelize(sorted(rdd.cartesian(rdd).collect()))
    print(type(result1))
    print(result1.collect())

My type and output at this stage are correct:
<class 'pyspark.rdd.RDD'>
[((1, 0), (1, 0)), ((1, 0), (2, 0)), ((1, 0), (3, 0)), ((2, 0), (1, 0)), ((2, 0), (2, 0)), ((2, 0), (3, 0)), ((3, 0), (1, 0)), ((3, 0), (2, 0)), ((3, 0), (3, 0))]

But now I need to remove the three pairs of tuples with duplicate entries.
Tried so far:

*

*.distinct()  This runs but does not produce a correct resulting rdd.

*.dropDuplicates()  Will not run. I assume this is an incorrect usage of .dropDuplicates().

*Manual function:

Without an RDD this task is easy.
# Remove duplicates
for elem in result:
    if elem[0] == elem[1]:
        result.remove(elem)
print(result)
print("After: ", len(result))

This was a function I wrote that removes duplicate tuple pairs and then spits out the resulting len so I could do a sanity check.
I am just not sure how to directly perform actions on the RDD, in this case remove any duplicate tuple pairs resulting from the Cartesian product, and return an RDD.
Yes, I can .collect() it, perform the operation, and then re-type it as an RDD, but that defeats the purpose.  Suppose this was billions of pairs.  I need to perform the operations on the rdd and return an rdd.

A: You can use filter to remove the pairs that you don't want:
dd.cartesian(rdd).filter(lambda x: x[0] != x[1])

Note that I would not call those pairs "duplicate pairs", but rather "pairs of duplicates" or even better, "diagonal pairs": they correspond to the diagonal if you visualize the Cartesian product geometrically.
This is why distinct and dropDuplicates are not appropriate here: they remove duplicates, which is not what you want. For instance, [1,1,2].distinct() is [1,2].


text:
Q: reloading vimrc causes different syntax highlighting When I open up a file in macvim it is like this http://imgur.com/a/3cLqB#0.
I have set ,V to :source ~/.vimrc<CR>.
After I have this file open, I press ,V, and the syntax highlighting changes to this http://imgur.com/a/3cLqB#1.
The difference is that (,),;,, become from blue, white, and ->,.,? become from blue, darker blue.
Why does that happen? This is my vimrc file https://gist.github.com/pvinis/4979592
--
Update: I found out that Valloric/vim-operator-highlight is the plugin that changes the colors. so the first picture is the correct picture.
I also found out, that as soon as i do :syntax on, the colors reset. Is there a way to check if syntax is already on?

A: Problem:
When reloading .vimrc, some highlight groups are messed up.
It depends on what plugins you have and what colorschemes you are using.
I've noticed that some highlight links were broken, and some highlight groups were cleared.
Affected highlight groups
In my particular setup I've noticed broken hi links or  cleared groups on:

*

*SignColumn

*GitGutter (which uses SignColumn)

*powerline-status (which uses status line)

Notice the affected areas after reloading:
(reloading means saving the modified file. Using :wa in this example)

Solution
Unfortunately the listed answers or any combination of options that I've tried does not preserve or reinstate the hi groups after reloading.
Running manually colorscheme <your-coloscheme> after reloading fixes everything, but when doing it with Vimscript it does not.
Hopefully someone will share a proper solution to this annoying small issue.
Ugly hack
Reloading vimrc:
On any change to my vim config files, I execute reload.vim:
.vimrc:
" .....
augroup reload_vimrc " {
    autocmd!
    autocmd BufWritePost ~/.vim/*.vim,~/.vim/vimrc source ~/.vim/reload.vim
augroup END " }

reload.vim: restores broken links and cleared groups
What we have to do is to reinstate the hi groups after sourcing vimrc.
To find the correct values for an affected area, e.g. for SignColumn, type:
:hi SignColumn, BEFORE any reloading has occurred.

The outcome is (where xxx is a preview):

You have to do this for every affected hi.
In the following snippet I initially fix SignColumn to match my solarized colorscheme.
Then I fix some GitGutter color issues:
e.g., GitGutterAdd is linked to GitGutterAddDefault which is preserved, but from GitGutterAddDefault to DiffAdd is broken, so I reinstall that one. And so on so forth.
reload.vim:
source ~/.vim/vimrc

hi SignColumn ctermfg=12 ctermbg=0 guifg=Cyan guibg=Grey

" GitGutterAdd -> GitGutterAddDefault (preserved)
hi link GitGutterAddDefault DiffAdd

" GitGutterChange -> GitGutterChangeDefault (preserved)
hi GitGutterChangeDefault ctermfg=3 ctermbg=0 guifg=#bbbb00

" GitGutterDelete -> GitGutterDeleteDefault (preserved)
hi GitGutterDeleteDefault ctermfg=1 ctermbg=0 guifg=#ff2222

" GitGutterChangeDelete -> GitGutterChangeDefault (preserved)
" (which we already fixed above)

" Powerline highlight groups
" (see this attached Gist for solution)

Everything works as it should:

Fixing powerline-status colors:
This one is a bit more tricky, but the principle is the same. All highlight groups of powerline start with Pl_. But some of them might not exist yet. For example, if you haven't entered visual mode yet, then the respective groups for visual mode won't be populated yet. So, enter insert, visual, and normal modes to populate the groups and then copy them. You can find them at the bottom of the output of the hl command. Then, paste them in your reload.vim and adapt them to be legit hl commands.
It may sound like a lot of work but it isn't.
Here's a gist with the full reload.vim, and some gifs to guide you through.

A: I had something very similar to this happening. I was able to solve it by making sure these were in the correct order:
syntax on
let g:solarized_termtrans=1
let g:solarized_termcolors=256
set background=dark
colorscheme solarized

I also used this for reloading
augroup reload_vimrc
autocmd!
autocmd BufWritePost $MYVIMRC source $MYVIMRC
augroup END

With those two I could do live updating of my vimrc without having to reload. I am using iTerm2 with Terminal vim. Hopefully this helps someone else out as I have spent quite a bit of time trying to get this live reloading working. Also make sure you have the newest versions of the solarized theme. I know it seems mundane to mention but it might make a difference.

A: I guess that the highlightings are defined / changed by some plugin. The re-execution of :colorscheme resets those definitions. The plugins would have to hook into the ColorScheme event with an :autocmd, but most don't.
To work around this, try wrapping the :colorscheme in a guard:
if ! exists('g:colors_name') || g:colors_name !=# 'Tomorrow-Night-Eighties'
    colorscheme Tomorrow-Night-Eighties
endif

A: This works for me
"auto reload vimrc once changed
if has("autocmd")
  autocmd! BufWritePost .vimrc source $MYVIMRC

  " This fixes the color changes and things not working :D
  autocmd! BufWritePost .vimrc filetype plugin indent on
endif

A: I have absolutely no idea why, (probably for the same reason that doing :source ~/.vimrc manually works) but for me replacing
autocmd BufWritePost *vimrc,*exrc :source %

with
autocmd BufWritePost *vimrc,*exrc :call feedkeys(":source %\<cr>")

fixed the problem.

A: autocmd BufWritePost *vimrc,*exrc :call feedkeys(":source %\<cr>")
Fixed it right away for me.  Must be some weird issue with the ordering.  I also have a keystroke to resource the file and this always works even when the autocmd was failing.

A: Most likely unrelated to your particular case, but I had a similar problem so I thought I'd share since it's the first StackOverflow result on Google.
My issue with reloading was in two phases: using the dark Solarized theme, reloading .vimrc would first change the colors slightly, then, reloading a second time, it would switch to the light Solarized theme.
The lines about colors in my .vimrc were:
set background="dark"
let g:solarize_termcolors=256
colorscheme solarized

The problem? The first line shouldn't have quotes:
set background=dark

I can now reload .vimrc without changing the colors. I'm not sure why it would work one time and work a different way after though. I realized that after commenting out everything but these lines as others have suggested.

A: set syntax enable after colorscheme


text:
Q: Screen capturing excluding some window in linux I'm trying to get screenshots every N milliseconds and I want not to show my own program widgets in this screenshot. User mustn't know any information from this program.
There is exist Magnification API for Windows to do such thing and this API works.
Is there any C++/C library for Linux?


text:
Q: UISearchBar clears when tapping on result table I have a TableViewController and UISearchController that I attached in viewDidLoad to it.
- (void)viewDidLoad
{
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    _searchController.searchResultsUpdater = self;
    _searchController.searchBar.delegate = self;
    [self.tableView.tableHeaderView addSubview:_searchController.searchBar];

}

While entering something into the search text field everything works, but if I tap on the results table, then the text field gets cleared and the Cancel button disappears. If I use the "Search" button from the keyboard instead, everything seems to be perfectly fine, until I tap on on the Table. Why is it that my SearchBar gets cleared when I tap on my TableView?
I'm using XCode 7.3 and iOS 9.

A: Adding _searchController.dimsBackgroundDuringPresentation = NO; fixed the problem, if someone will ever run into this problem.


text:
Q: MongoDB needs to get total counts from all objects my aggregate query looks like this. I need to get the total count from the value.
db.getCollection('mydesk').aggregate([
{
    $match: {
        "accountId": ObjectId("616ea615edc5fa4278ccb7f6"),
                "val" : { $ne : null},
        "deskId": { "$in": [
                ObjectId("61934f7efdb9dc5a7c1c3a01"),
                ObjectId("61713730857c3243ec1d257c"),
                ObjectId("629d9548e0c93e34e435e7b9"),
                ObjectId("616eaf613bcd9655b8035a25"),
            ]}
    }
},
{
      $project: {
         item: 1,
         value:  { $size: "$val.shapes" },
      }
}

])

I got result like this. But need to get the total counts of my value.
/* 1 */
{
    "_id" : ObjectId("616fab4f12b90d59d03f380e"),
    "value" : 11
}

/* 2 */
{
    "_id" : ObjectId("616fbad35700980a041cd190"),
    "value" : 4
}

/* 3 */
{
    "_id" : ObjectId("61713752857c3243ec1d257e"),
    "value" : 12
}

Needed result :
{
    "totalValueCount" : 27
}

Thanks in advance

A: One option is to use $group to $sum up the values:
db.getCollection('mydesk').aggregate([
  {
    $match: {
        "accountId": ObjectId("616ea615edc5fa4278ccb7f6"),
        "val" : { $ne : null},
        "deskId": { "$in": [
                ObjectId("61934f7efdb9dc5a7c1c3a01"),
                ObjectId("61713730857c3243ec1d257c"),
                ObjectId("629d9548e0c93e34e435e7b9"),
                ObjectId("616eaf613bcd9655b8035a25"),
            ]}
    }
  },
  {
      $group: {
         _id: null,
         total:  {$sum: { $size: "$val.shapes"}},
      }
  },
  {$project: {_id: 0, total: 1}}

])


text:
Q: Prove that $\mathbb{R}$ with this metric is complete Prove that $\mathbb{R}$ endowed with the metric $d(x,\ y)=|x^3-y^3|$ is complete.
My attempt:
Let $\{x_n\}$ be a Cauchy sequence in $(\mathbb{R},\ d)$. We must prove that $x_n\to x$ where $x\in\mathbb{R}$.
The main problem I face is that I don't know what $x$ is. If I did, I could try proving that $d(x_n,\ x)\to 0$.

A: Let $(x_n)_{n \in \mathbb{N}}$ be a Cauchy sequence for the metric $d$, and let's consider the sequence $(y_n)_{n \in \mathbb{N}}$ defined by $y_n = x_n^3$.
$(x_n)_{n \in \mathbb{N}}$ is a Cauchy sequence, so you have
$$\forall \varepsilon > 0, \exists N \in \mathbb{N}, \forall p,q \geq N, |x_p^3 - x_q^3| \leq \varepsilon$$
i.e.
$$\forall \varepsilon > 0, \exists N \in \mathbb{N}, \forall p,q \geq N, |y_p - y_q| \leq \varepsilon$$
So $(y_n)_{n \in \mathbb{N}}$ is a Cauchy sequence for the usual metric on $\mathbb{R}$, therefore it converges. Let $y$ be its limit.
We have then that
$$\forall \varepsilon > 0, \exists N \in \mathbb{N}, \forall n \geq N, |y_n-y| \leq \varepsilon$$
so
$$\forall \varepsilon > 0, \exists N \in \mathbb{N}, \forall n \geq N, |x_n^3-\left(y^{\frac{1}{3}}\right)^3| \leq \varepsilon$$
So you get the definition of the convergence, for the metric $d$, of the sequence $(x_n)_{n \in \mathbb{N}}$ to its limit $y^{\frac{1}{3}}$.
So your topological space is complete, as this proof.

A: Suppose that $(x_n)_n$ is a Cauchy sequence.  It's bounded in the usual metric, so you may find some closed and bounded interval (in usual sense) $[-M,M]$ so that $(x_n)_n \subseteq [-M,M]$, from which you may find a convergent subsequence (still in the usual Euclidean metric) $(x_{n_k})_k$ so that $x_{n_k} \to x$.  Check that $x_{n_k} \overset{d}{\to} x$.
Fix $M' = \max_{(x,y) \in [-M,M]^2} |x^2+xy+y^2|$.  (Well defined since $(x,y) \mapsto |x^2+xy+y^2|$ is continuous.)  Then
$$d(x_{n_k},x) = |x_{n_k}^3-x^3| = |x_{n_k}-x||x_{n_k}^2+x_{n_k}x+x^2| \le M'|x_{n_k}-x|\xrightarrow[k \to \infty]{} 0.$$
Since $(x_n)_n$ is Cauchy, the fluctuation of the tail of $(x_n)_n$ can be made arbitrarily small.  This forbids $(x_n)_n$ from having two limit points.  Therefore, $x_n \overset{d}{\to} x$.


text:
Q: g++: error: unrecognized command line option '-stdlib=libstdc++' Hi I'm running a makefile that has the line
ADDLIBS = -stdlib=libstdc++ -L${BOOST_DIR}/lib -lboost_program_options

but I get the exception
g++: error: unrecognized command line option '-stdlib=libstdc++'

Could someone tell me how I modify the makefile?

A: That flag is for clang.  It's not a valid flag for GCC.  So just remove it:
ADDLIBS = -L${BOOST_DIR}/lib -lboost_program_options


text:
Q: Special characters in folder names cause delete by batch-file to fail I'm trying to delete empty folders via a batch file, in Windows.

for /f "usebackq delims=" %%d in ("dir V:\Temp /ad/b/s | sort /R") do rd "%%d"

fails on folders with special characters - specifically parentheses and Alt+(numpad)7 bullets.
How can I process folders with these special characters in their name?

A: In the end I side-stepped this issue by using DirClean. It seems to be no longer developed, and its page has gone dead, but it works just fine.


text:
Q: Как распарсить строку на переменные? Дан текстовик: random.txt
В нëм строки: 123123:123123:123123, такого вида.
Как можно эти строки распарсить на 3 переменные?

A: Ну например как-то так:
var filepath = Path.Combine(
    Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
    "random.txt");

foreach (var line in File.ReadLines(filepath))
{
    int[] numbers = line.Split(':').Select(int.Parse).ToArray();
    int first = numbers[0];
    ...
}


text:
Q: Typescript Comments in bundled js-file is there a way to add an important comment to the top of the bundled js-file in typescript.
i would like to add automaitcally a comment with the Version-information to the top of the js-file everytime it gets "compiled".
like:
/*!
v 1.0.1.0
Git:...
License: MIT
...
*/

A: Yes, there are a set of "header" and "footer" tools. I'm using gulp-header and gulp-footer. I beleive similar tools are existing for other build tools.


text:
Q: combine Fragment and Activity class in Base class I have 2 classes:
public class MyFragment extends Fragment implements MyListener
public void myFun1()
public void myFun2()
public void myFun23()

public class MyActivity extends AppCompatActivity implements MyListener
public void myFun1()
public void myFun2()
public void myFun34()

I am trying to combine my two classes in an base class so I need to write myFun1() and myFun2() only once but the problem is that one class extends Fragment and one class extends Activity. How can I bring the functions together in one base class?
EDIT: The methods do not come from the listener and can be ignored. myFun1() and myFun2() have the same functionality while myFun23() and myFun34() have both a special function only necessary in its class

A: You can do it only with Java8 that introduced the default methods in interfaces.
You can define something like:
public interface MyInterface {

    default void myFun1() {
         // default method implementation
    }

    default void myFun2() {
         // default method implementation
    }

}

Then:
   public class MyActivity extends AppCompatActivity implements MyListener, MyInterface {

     // Just define
     public void myFun23(){}
   }

   public class MyFragment extends Fragment implements MyListener, MyInterface {

     // Just define
     public void myFun34(){}
   }

You can do the same with kotlin.
interface MyInterface {
    fun myFun1() {
      // implementation
    }
    //...
}

Then:
class MainActivity : AppCompatActivity(), MyInterface {

    fun func23() {
       //...
    }
}

....

A: There is a rule of thumb in Object Oriented Programming called "Favor Composition over Inheritance". Your question is a classic example of the benefits of composition over inheritance. All you need to do is move the functions into another class and then create an instance of that class wherever you want.
For example:
public class MyFunctions {

    public void myFun1() {
        // do cool things here
    }

    public void myFun2() {
        // do cool things here
    }

}

public class MyFragment extends Fragment implements MyListener {
    MyFunctions myFunctions = new MyFunctions();
}

To learn more about this rule of thumb and many many more, you should read Effective Java.

A: In this specific situation probably your myFun1() and myFun2() access some member variables in MyFragment and MyActivity. If you want to common out (like strategy pattern) the implementation of the myFun1() and myFun2() you should supply those variables to the common implementation either directly, or indirectly by introducing another interface.
The second solution of introducing another interface is mostly not preferable. In the first solution we end up with a strategy like the following.
class DataFetchingStrategy(val repo: Repository) : MyListener {
    fun myFun1() {
      repo.fetchData1()
    }

    fun myFun2() {
      repo.fetchData2()
    }
}

A strategy is not a listener. Even though we name it differently like DataFetcher or RepoManager, they are also not listeners.
Then how can we eliminate the duplicate code from the listener methods? Listener methods should be as lean as possible and the listener implementations should be ad hoc. The listener methods will forward the call to a strategy or delegate or composite etc. Not the strategy or delegate or composite will implement the listener.
class DataFetcher(val repo: Repository) {
  fun fetchData1() {
    // implementation
  }

  fun fetchData2() {
    // implementation
  }
}

class MyFragment : Fragment, MyListener {
  val dataFetcher = DataFetcher(Repository())

  fun myFun1() = dataFetcher.fetchData1()

  fun myFun2() = dataFetcher.fetchData2()

  fun myFun23() {}
}

class MyActivity : AppCompatActivity, MyListener {
  val dataFetcher = DataFetcher(Repository())

  fun myFun1() = dataFetcher.fetchData1()

  fun myFun2() = dataFetcher.fetchData2()

  fun myFun34() {}
}

A: You could think about Composition over Inheritance or Strategy Patterns.
e.g. your Classes don't implement MyListener but include a MyListener instance
public class MyFragment extends Fragment
public MyListener myListener;

public class MyActivity extends BaseActivity
public MyListener myListener;

public class MyListenerImpl implements MyListener
public myFun1();
public myFun2();

you can now use your functions in all classes, that have an instance of it.
(with Kotlin you could simply create the Functions without the need of classes)


text:
Q: Searching byte encoded integers, is it faster to convert to int or match the bytes? I have a binary file containing integers at known positions. I want to seek a specific integer, or byte sequence. I got the idea converting to integer would be more efficient given the byte version's resemblance to a string.
Should I convert each byte sequence to an integer for comparisons or use bytes?
How does the size of the byte sequence comprising each int effect this, eg would using 3 bytes incur an overhead of masking off the odd byte?

A: To answer I devised a small script. The slowest part is generating the randoms.
import random
import time

endianness = "big"
bytes_given_to_int = 3

def some_nums(top_end: int):
    return [x + random.randint(0, 42) for x in range(top_end)]

top_end = 9_999_999

bs = [x.to_bytes(bytes_given_to_int, endianness) for x in some_nums(top_end)]
bs2 = [x.to_bytes(bytes_given_to_int, endianness) for x in some_nums(top_end)]
cs = some_nums(top_end)
cs2 = some_nums(top_end)

iicmps=[]
bbcmps=[]
bicmps=[]
ibcmps=[]

for i in range(10):
    t0 = time.time()
    rs1 = [1 for i in range(top_end) if bs[i] == bs2[i]]
    # Each sum should be roughly equal. Using it here helps instruct the interpreter/compiler
    # not to optimise away the arbitrary task we give it.
    print(sum(rs1))
    bbcmps.append((time.time() - t0))
    t0 = time.time()
    rs2 = [1 for i in range(top_end) if cs[i] == cs2[i]]
    print(sum(rs2))
    iicmps.append((time.time() - t0))
    t0 = time.time()
    rs3 = [1 for i in range(top_end) if int.from_bytes(bs[i], endianness) == cs[i]]
    print(sum(rs3))
    bicmps.append((time.time() - t0))
    t0 = time.time()
    rs4 = [1 for i in range(top_end) if cs[i].to_bytes(bytes_given_to_int, endianness) == bs[i]]
    print(sum(rs4))
    ibcmps.append((time.time() - t0))

print("Comparing byte sequences took {:.2f}s".format(sum(bbcmps) / len(bbcmps)))
print("Comparing ints took {:.2f}s".format(sum(iicmps) / len(iicmps)))
print("Comparing byte sequences (converted to ints) to ints took {:.2f}s".format(sum(bicmps) / len(bicmps)))
print("Comparing ints (converted to byte sequences) to byte sequences took {:.2f}s".format(sum(ibcmps) / len(ibcmps)))

Comparing byte sequences took 1.54s
Comparing ints took 1.50s
Comparing byte sequences (converted to ints) to ints took 3.53s
Comparing ints (converted to byte sequences) to byte sequences took 3.52s

Ok, this shows byte sequences to be first class objects, as we might deduce from even strings being a thin veneer on lists.
What happens with other word lengths? Let's try 4.

Comparing byte sequences took 1.31s
Comparing ints took 5.89s
Comparing byte sequences (converted to ints) to ints took 3.29s
Comparing ints (converted to byte sequences) to byte sequences took 3.20s

I guess the variables in this script are useful! byte sequences FTW!


text:
Q: Programming external QSPI flash Raspberry Pi Pico I want to reprogram the external flash of a raspberry Pico via SWD line.
This feature must be implemented in a different microcontroller, not from a Linux computer so the OpenOCD library cannot be used.
I already wrote a C library that is able to read and write in RAM and in core registers via SWD and I'm able to put the Cortex-M0+ into halt state.
I read many tutorials and documentation and those that are useful are:

*

*http://markding.github.io/swd_programing_sram/

*https://www.silabs.com/documents/public/application-notes/an0062.pdf

*https://community.silabs.com/s/article/how-to-program-internal-sram-over-swd?language=en_US
but unfortunately they aren't clear enough.
Can you explain the sequence of commands that I should send to RP2040 to correctly upload the new firmware?
Thanks for your help!


text:
Q: Back to main view controller from modal View controller I want to make a back button from a modal view to the Main view.
The View Controller is embedded in the navigation controller. The menu button take me to the Second View Controller. There I have a back button who works fine using this:
[self.navigationController popViewControllerAnimated:YES];

I want to go back to the Main View Controller from the Page Two VC.
I have tried:
- (IBAction)goToRootView:(id)sender {

[self.presentingViewController dismissViewControllerAnimated:(NO) completion:nil];
[self.navigationController popViewControllerAnimated:YES];
}

and:
- (IBAction)goToRootView:(id)sender {

[self dismissViewControllerAnimated:(NO) completion:nil];
[self.navigationController popViewControllerAnimated:YES];
}

The first just goes back to the Second VC, the last sends and lldb error.
How can I go from Mantras Page Two VC to Main VC?
Thank you for your help!

A: In the first snippet, instead of
[self.navigationController popViewControllerAnimated:YES];

try
[self.navigationController popToRootViewControllerAnimated:YES];

A: You can tray this...
CHS_View_Controller *oldView = [self.storyboard instantiateViewControllerWithIdentifier:@"CHS_View"];
UINavigationController *yourNavigationController = [[UINavigationController alloc]  initWithRootViewController:oldView];

yourNavigationController.modalTransitionStyle= UIModalTransitionStyleCrossDissolve;

[self presentViewController:yourNavigationController animated:YES completion:nil];

for that you must:
1) import you dest controller
#import "CHS_View_Controller.h" // your controller name

and
2)
set an Identifier for your CHS_Controller, "CHS_View" in the bellow example (into the Storyboard Editor and in the Attributes Inspector)


text:
Q: serverless deploy threw error when trying to associate aws waf to aws api gateway When serverless deploy tried to associate an aws waf to my aws api gateway, it threw this error:
Other than downgrading my node, serverless, plugin and SDK to older versions, anyone found a fix?
Thanks!
Karl
Environment: darwin, node 18.6.0, framework 3.22.0, plugin 6.2.2, SDK 4.3.2
Credentials: Local, "default" profile
Docs:        docs.serverless.com
Support:     forum.serverless.com
Bugs:        github.com/serverless/serverless/issues

Error:
TypeError: this.config.name.trim is not a function
    at AssociateWafPlugin.updateWafAssociation (/Users/kninh/node_modules/serverless-associate-waf/lib/index.js:58:66)
    at PluginManager.runHooks (/usr/local/lib/node_modules/serverless/lib/classes/plugin-manager.js:530:15)
    at async PluginManager.invoke (/usr/local/lib/node_modules/serverless/lib/classes/plugin-manager.js:565:9)
    at async PluginManager.run (/usr/local/lib/node_modules/serverless/lib/classes/plugin-manager.js:604:7)
    at async Serverless.run (/usr/local/lib/node_modules/serverless/lib/serverless.js:174:5)
    at async /usr/local/lib/node_modules/serverless/scripts/serverless.js:771:9

Serverless.yml
resources:
  Resources:
    WafAcl:
      Type: 'AWS::WAFv2::WebACL'
      Properties:
         Scope: REGIONAL

custom:
   associateWaf:
    name: !Ref WafAcl
    version: Regional


text:
Q: List activity with header, footer and empty all visible I would like to have the listview in a ListActivity be displayed with the header and footer visible all the time even if the list data is empty.
An empty list causes the empty view to appear and the header and footer to disappear. However my header has filtering UI and should therefore always be visible.
The only way I can make it happen at the moment is if I take the header and footer out of the listview and implement them as static views outside in the activity layout. However then these are always visible and only the data scrolls.
I would prefer for both to just be on top and bottom of the scrolling list. Wrapping it all in a scroll view does not work since then there are two nested scroll views( the list view outside and the wrapping one).
Is there a way to do this nicely apart from a hack like adding a fake record?

A: You could use my MergeAdapter for this. Add the header view, add the data adapter, and add the footer view. They will all scroll in unison, and the header and footer will persist even if the adapter in the middle has no rows.

A: Ok, this workaround is a hack. But, without having to create a fake item.
For an ArrayAdapter you can add a null item... i.e.
myAdapter.add(null);

And, in the MyAdapter getView(..) you do something like:
myItem = getItem(position);
if (myItem == null) {
   return getLayoutInflater().inflate(R.layout.my_empty_row, null);
} else {
...
}

A: Make your empty view include your header.
i.e.
 <ListView />
 <RelativeLayout
    android:id="@android:id/empty"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
       // Add whatever you want here including your header
 </RelativeLayout>

A: This answer is a bit late, but you can simply override BaseAdapter.isEmpty() to return false.
public boolean isEmpty() {
    return false;
}

A: I found that header/footer will always be visible if you don't call ListView.setEmptyView.
Instead, manually show/hide your empty view:
emptyView.setVisibility(list.size() == 0 ? View.VISIBLE : View.GONE);

A: I meet the same issue, if ListView has no item, you could ListView.setAdapter(new SomeAdapter(new ArrayList())); and the header is also visible.

A: In my case I had both header and footer views.
I placed my mEmptyView in footer view.
First, as user1034295 mentioned, I overrided adapter's isEmpty() method:
@Override
public boolean isEmpty() {
// If not overridden, then this will return `true` if your list is empty
// Thus, you won't see header/footer views
   return false;
}

ExpandableListView adapter's getGroupCount(). Override appropriate method for your adapter.
@Override
public int getGroupCount() {
    int size = null != mData ? mData.size() : 0;
    if (0 == size) mHostFragment.toggleEmptyView(true);
    else mHostFragment.toggleEmptyView(false);
    return size;
}

In you activity/fragment
public void toggleEmptyView(boolean show) {
    if(show && mEmptyView.getVisibility() != View.VISIBLE)
        mEmptyView.setVisibility(View.VISIBLE);
    else if (!show && mEmptyView.getVisibility() != View.GONE)
        mEmptyView.setVisibility(View.GONE);
}

mEmptyView is a child in ListView's footer view.
So, when your list becomes 0 sized you'll get your header/footer views remained + mEmptyView will become visible.

A: You can put the listView and the empty layout together in a FrameLayout, and put
the empty layout margin in the size of the header, then, you can change the visibility of the empty view when an item is added to listview.
layout will be as similar to this:
<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1">

    <ListView
        android:id="@+id/myListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:listheader="@layout/myHeader"/>

    <LinearLayout
        android:layout_marginTop="@dimen/headerHeight"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:id="@+id/emptyLayout">

       //insert your layout here

    </LinearLayout>

</FrameLayout>


text:
Q: Is there a way to "trickle down" implicits from top level applications to other imported modules? I am trying to refactor some code for a program which uses an ActorSystem as the backbone for Http calls.
My specific goal is to make my code more modular so I can write libraries of functions which make http calls using an ActorSystem where the ActorSystem is later expected to be provided by the application.
This is a general question though as I tend to run into this problem a reasonable amount.
I have two goals:

*

*Minimize the number of ActorSystems I create to simplify tracking of them  (one per top level application is the goal)

*Avoid explicitly passing around the ActorSystem and context everywhere it's needed.

Conceptually - the code below illustrates how I'm thinking about it (of course this code would not compile).
import akka.actor.ActorSystem
import intermediateModule._

import scala.concurrent.ExecutionContextExecutor

object MyApp extends App {
  // Create the actorsystem and place into scope
  implicit val system = ActorSystem()
  implicit val context = system.dispatcher

  intermediateFunc1(300)

}

// Elsewhere in the intermediate module
object intermediateModule {
  import expectsActorSystemModule._

  def intermediateFunc1(x: Int) = {

    // Relies on ActorSystem and Execution context,
    // but won't compile because, of course the application ActorSystem and
    // ec is not in scope
    usesActorSystem(x)
  }

}

// In this modiule, usesActorSystem needs an ActorSystem
object expectsActorSystemModule {

  def usesActorSystem(x: Int)
                     (implicit system: ActorSystem, context: ExecutionContextExecutor) = ???
  //... does some stuff like sending http requests with ActorSystem
}

Is there a way to "trickle down" implicits through the sub-modules to achieve the goal of the top level application providing the needed implicits?
Can this be done in a way such that the "depth" of module imports doesn't matter (e.g. if I added a few more intermediate libraries in between the top level app and the module which requires the ActorSystem)?

A: The answer here is dependency injection. Every object that has dependencies on other objects should receive them as constructor parameters. The important thing here is that higher layers only get their own dependencies, and not their dependencies' dependencies.
In your example, IntermediateModule doesn't use the ActorSystem itself; it only needs it to pass it on to ExpectsActorSystemModule. This is bad, because if the latter  changes and requires another dependency, you will need to change the former as well – that is too much coupling. You can refactor it like so:
import akka.actor.ActorSystem
import scala.concurrent.ExecutionContextExecutor

object MyApp extends App {
  // Create the actorsystem and place into scope
  // wire everything together
  implicit val system = ActorSystem()
  implicit val context = system.dispatcher
  val expectsActorSystemModule = new ExpectsActorSystemModule
  val intermediateModule = new IntermediateModule(expectsActorSystemModule)

  // run stuff
  intermediateModule.intermediateFunc1(300)

}

// Elsewhere in the intermediate module
class IntermediateModule(expectsActorSystemModule: ExpectsActorSystemModule) {
  def intermediateFunc1(x: Int) = {
    // Note: no ActorSystem or ExecutionContext is needed, because they were
    // injected into expectsActorSystemModule
    expectsActorSystemModule.usesActorSystem(x)
  }
}

// In this module, usesActorSystem needs an ActorSystem
class ExpectsActorSystemModule(
  implicit system: ActorSystem,
  context: ExecutionContextExecutor) {

  def usesActorSystem(x: Int) = ???
  //... does some stuff like sending http requests with ActorSystem
}

Note that IntermediateModule no longer needs an ActorSystem or an ExecutionContext, because those were provided directly to ExpectsActorSystemModule.
The slightly annoying part is that at some point you have to instantiate all these objects in your application and wire them all together. In the above example it's only 4 lines in MyApp, but it will get significantly longer for more substantial programs.
There are libraries like MacWire or Guice to help with this, but I would recommend against using them. They make it much less transparent what is going on, and they don't save all that much code either – in my opinion, it's a bad tradeoff. And these two specifically have more downsides. Guice comes from the Java world and gives you basically no compile-time guarantees, meaning that your code might compile just fine and then fail to start because Guice. MacWire is better in that regard (everything is done at compile time), but it's not future-proof because it's implemented as a Scala 2 macro – it will not work on Scala 3 in its current form.
Another approach that is popular among the purely functional programming community is to use ZIO's ZLayer. But since you're working on an existing codebase that is based on the Lightbend tech stack, this is unlikely to be the means of choice in this particular case.


text:
Q: wxListCtrl does not show images I make use of a wxListCtrl which has one column (so a really simple list). Based on the listctrl-sample I tried to have the list-items with a icon in front. Unfortunately only the text is shown but not the image.
That's my code (relevant parts only):
m_toolImages=new wxImageList(25,25);

m_hideList=new wxListCtrl(toolPanel,wxID_ANY,wxDefaultPosition,wxSize(180,-1),wxLC_REPORT|wxLC_NO_HEADER|wxLC_SINGLE_SEL);
m_hideList->AppendColumn(wxEmptyString);
m_hideList->SetColumnWidth(0,250);
m_hideList->SetImageList(m_toolImages,wxIMAGE_LIST_NORMAL);

imageID=m_toolImages->Add(bm); // bm is a wxBitmap wit a size of 25x25 pixels

m_hideList->InsertItem(i,"ItemName",imageID);

So...what could be missing here?

A: The report mode uses "small" image list and not the normal one, which is only used in the "icon" mode, so you need to set that one.


text:
Q: Is there any way to validate that a request to .NET Framework Web API is from our hosted portal? I am using .NET Framework Web API, and I need to verify the API calls are from my hosted portal end.
Is there any method to validate request and block requests?
I used CORS to validate, and I don't know if that is the best practice to verify.

A: Your question is not clear. if you want to verify the API calls from your hosted portal and block other domain the best way is to use the Cross Origin Resource Sharing (CORS):
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(name: AllowPortalDomain,
                          policy =>
                          {
                              policy.WithOrigins("http://PortalDomain.com");
                          });
    });

    ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseCors(AllowPortalDomain);
...
}

You can enable Cross-Origin Requests per controller or action:
[EnableCors("AllowPortalDomain")]
[HttpPost]
public IActionResult yourAPI(){...}

for more information see this link CORS
hope this helps!


text:
Q: Two methods of performing cohort analysis in MySQL using joins I make a cohort analysis processor. Input parameters: time range and step, condition (initial event) to exctract cohorts, additional condition (retention event) to check after each N hours/days/months. Output parameters: cohort analysis grid, like this:
               0h |   16h |   32h |   48h |   64h |   80h |   96h |
cohort #00     15 |     6 |     4 |     1 |     1 |     2 |     2 |
cohort #01      1 |    35 |     8 |     0 |     2 |     0 |     1 |
cohort #02      0 |     3 |    31 |    11 |     5 |     3 |     0 |
cohort #03      0 |     0 |     4 |    27 |     7 |     6 |     2 |
cohort #04      0 |     1 |     1 |     4 |    29 |     4 |     3 |

Basically:

*

*fetch cohorts: unique users who did something 1 in every period from time_begin every time_step.

*find how many of them (in each cohort) did something 2 after N seconds, N*2 seconds, N*3, and so on until now.

In short - I have 2 solutions. One works too slow and includes a heavy select with joins for each data step: 1 day, 2 day, 3 day, etc. I want to optimize it by joining result for every data step to cohorts - and it's the second solution. It looks like it works but I'm not sure it's the best way and that it will give the same result even if cohorts will intersect. Please check it out.

Here's the whole story.
I have a table of > 100,000 events, something like this:
#user-id, timestamp, event_name
events_view (uid varchar(64), tm int(11), e varchar(64))

example input row:
"user_sampleid1", 1423836540, "level_end:001:win"

To make a cohort analisys first I extract cohorts: for example, users, who send special event '1st_launch' in 10 hour periods starting from 2015-02-13 and ending with 2015-02-16. All code in this post is simplified and shortened to see the idea.
DROP TABLE IF EXISTS tmp_c;
create temporary table tmp_c (uid varchar(64),  tm int(11), c int(11) );

set beg = UNIX_TIMESTAMP('2015-02-13 00:00:00');
set en = UNIX_TIMESTAMP('2015-02-16 00:00:00');
select min(tm) into t_start from events_view ;
select max(tm) into t_end from events_view ;
if  beg <  t_start then
    set beg = t_start;
end if;
if  en >  t_end then
    set en = t_end;
end if;

set period =   3600 * 10;
set cnt_c = ceil((en - beg) / period) ;

/*works quick enough*/
WHILE i < cnt_c DO
    insert into tmp_c (
    select uid, min(tm), i from events_view where
            locate("1st_launch", e) > 0 and tm > (beg + period * i)
            AND tm <= (beg + period * (i+1)) group by uid );
    SET i = i+1;
END WHILE;

Cohorts may consist the same user ids, though usually one user is exist only in one cohort. And in each cohort users are unique.
Now I have temp table like this:
user_id  |  1st timestamp |  cohort_no
uid1        1423836540          0
uid2        1423839540          0
uid3        1423841160          1
uid4        1423841460          2
...
uidN        1423843080          M

Then I need to again divide time range on periods and calculate for each period how many users from each cohort have sent event "level_end:001:win".
For each small period I select all unique users who have sent "level_end:001:win" event and left join them to tmp_c cohorts table. So I have something like this:
user_id  |  1st timestamp |  cohort_no  |   user_id    | other fields...
uid1        1423836540          0           uid1
uid2        1423839540          0           null
uid3        1423841160          1           null
uid4        1423841460          2           uid4
...
uidN        1423843080          M           null

This way I see how many users from my cohorts are in those who have sent "level_end:001:win", exclude not found by where clause: where t2.uid is not null.
Finally I perform grouping and have counts of users in each cohort, who have sent "level_end:001:win" in this particluar period.
Here's the code:
DROP TABLE IF EXISTS tmp_res;
create temporary table tmp_res (uid varchar(64) CHARACTER SET cp1251 NOT NULL,  c int(11), cnt int(11) );
set i = 0;
set cnt_c = ceil((t_end - beg) / period) ;
WHILE i < cnt_c DO
    insert into tmp_res
    select concat(beg + period * i, "_", beg + period * (i+1)), c, count(distinct(uid)) from
    (select t1.uid, t1.c  from tmp_c t1 left join
        (select uid, min(tm) from events_view where
            locate("level_end:001:win", e) > 0 and
            tm > (beg + period * i) AND tm <= (beg + period * (i+1)) group by uid ) t2
        on t1.uid = t2.uid where t2.uid is not null) t3
    group by c;
    SET i = i+1;
END WHILE;

/*getting result of the first method: tooo slooooow!*/
select * from  tmp_res;

The result I've got (it's ok that some cohorts are not appear on some periods):
"1423832400_1423890000","1","35"
"1423832400_1423890000","2","3"
"1423832400_1423890000","3","1"
"1423832400_1423890000","4","1"
"1423890000_1423947600","1","21"
"1423890000_1423947600","2","50"
"1423890000_1423947600","3","2"
"1423947600_1424005200","1","9"
"1423947600_1424005200","2","24"
"1423947600_1424005200","3","70"
"1423947600_1424005200","4","6"
"1424005200_1424062800","1","7"
"1424005200_1424062800","2","15"
"1424005200_1424062800","3","21"
"1424005200_1424062800","4","32"
"1424062800_1424120400","1","7"
"1424062800_1424120400","2","13"
"1424062800_1424120400","3","24"
"1424062800_1424120400","4","18"
"1424120400_1424178000","1","10"
"1424120400_1424178000","2","12"
"1424120400_1424178000","3","18"
"1424120400_1424178000","4","14"
"1424178000_1424235600","1","6"
"1424178000_1424235600","2","7"
"1424178000_1424235600","3","9"
"1424178000_1424235600","4","12"
"1424235600_1424293200","1","6"
"1424235600_1424293200","2","8"
"1424235600_1424293200","3","9"
"1424235600_1424293200","4","5"
"1424293200_1424350800","1","5"
"1424293200_1424350800","2","3"
"1424293200_1424350800","3","11"
"1424293200_1424350800","4","10"
"1424350800_1424408400","1","8"
"1424350800_1424408400","2","5"
"1424350800_1424408400","3","7"
"1424350800_1424408400","4","7"
"1424408400_1424466000","2","6"
"1424408400_1424466000","3","7"
"1424408400_1424466000","4","3"
"1424466000_1424523600","1","3"
"1424466000_1424523600","2","4"
"1424466000_1424523600","3","8"
"1424466000_1424523600","4","2"
"1424523600_1424581200","2","3"
"1424523600_1424581200","3","3"

It works but it takes too much time to process because there are many queries here instead of one, so I need to rewrite it.
I think it can be rewritten with joins, but I'm still not sure how.
I decided to make a temporary table and write period boundaries in it:
DROP TABLE IF EXISTS tmp_times;
create temporary table tmp_times (tm_start int(11), tm_end int(11));

set cnt_c = ceil((t_end - beg) / period) ;
set i = 0;
WHILE i < cnt_c DO
 insert into  tmp_times values( beg + period * i, beg + period * (i+1));
SET i = i+1;
END WHILE;

Then I get periods-to-events mapping  (user_id + timestamp represent particular event) to temp table and left join it to cohorts table and group the result:
SELECT Concat(tm_start, "_", tm_end) per,
       t1.c                          coh,
       Count(DISTINCT( t2.uid ))
FROM   tmp_c t1
       LEFT JOIN (SELECT *
                  FROM   tmp_times t3
                         LEFT JOIN (SELECT uid,
                                           tm
                                    FROM   events_view
                                    WHERE  Locate("level_end:101:win", e) > 0)
                                   t4
                                ON ( t4.tm > t3.tm_start
                                     AND t4.tm <= t3.tm_end )
                  WHERE  t4.uid IS NOT NULL
                  ORDER  BY t3.tm_start) t2
              ON t1.uid = t2.uid
WHERE  t2.uid IS NOT NULL
GROUP  BY per,
          coh
ORDER  BY per,
          coh;

In my tests this returns the same result as method #1. I can't check the result manually, but I understand how method #1 work more and as far I can see it gives what I want. Method #2 is faster, but I'm not sure it's the best way and it will give the same result even if cohorts will intersect.
Maybe there are well-known common methods to perform a cohort analysis in SQL? Is method #1 I use more reliable than method #2? I work with joins not that often, that's why still do not fully understand joins magic yet.
Method #2 looks like pure magic, and I used to not believe in what I don't understand :)
Thanks for answers!


text:
Q: Combine 2 internet lines
Possible Duplicate:
Internet connection using 2 modem at a time

I moved into an apartment where the internet is provided. Each internet connection is limited to 10mbps/10mbps. There are two ethernet outlets in the apartment. It appears that these two outlets do not share bandwidth. They each have separate IP's and usage when connected to one outlet does not seem to affect the speed of the other. I currently have a wireless router setup on one of the ethernet connections and my desktop is connected through LAN on the other.
I was wondering if it would be possible to merge the two connections into one. What would be the required hardware? Also, could I still use my wireless router with that setup?

A: You can do DSL link bonding aka link aggregation but rest assured that your speed boost won't be really as u expect. i.e not the sum of the speeds of both lines. Additionally, some ISPs restrict that by default or, some mechanisms has to be supported from their side first before you can make use of such technology.
Moreover, DSL link bonding might be not "out there" and offered in the firmware of most home consumer-grade routers. Therefore, you would typically need to make use of other opensource firmware such as DD-WRT and OpenWRT in order to unlock and configure such feature (documentation and howto do link aggregation on their website).
The link below is a comprehensive overview of setting DSL bonding up and has some benchmarks in the end as well:
http://www.youtube.com/watch?v=BBoJ12ByutY
If you know what you are doing and geeky enough, it's worth giving it a try indeed ;)


text:
Q: How do I modify a ReadOnly Linq property I have a LINQ to SQL generated class with a readonly property:
<Column(Name:="totalLogins", Storage:="_TotalLogins", DbType:="Int", UpdateCheck:=UpdateCheck.Never)>  _
Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer)
    Get
        Return Me._TotalLogins
    End Get
End Property

This prevents it from being changed externally, but I would like to update the property from within my class like below:
Partial Public Class User

...

    Public Shared Sub Login(Username, Password)
        ValidateCredentials(UserName, Password)

        Dim dc As New MyDataContext()
        Dim user As User = (from u in dc.Users select u where u.UserName = Username)).FirstOrDefault()
        user._TotalLogins += 1
        dc.SubmitChanges()
    End Sub

...

End Class

But the call to user._TotalLogins += 1 is not being written to the database? Any thoughts on how to get LINQ to see my changes?

A: Set the existing TotalLogins property as either private or protected and remove the readonly attribute. You may also want to rename it e.g. InternalTotalLogins.
Then create a new property by hand in the partial class that exposes it publically as a read-only property:
Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer)
    Get
        Return Me.InternalTotalLogins
    End Get
End Property

A: Make a second property that is protected or internal(?)

<Column(Name:="totalLogins", Storage:="_TotalLogins", DbType:="Int", UpdateCheck:=UpdateCheck.Never)>  _
protected Property TotalLogins2() As System.Nullable(Of Integer)
    Get
        Return Me._TotalLogins
    End Get
    Set(byval value as System.Nullable(Of Integer))
        Return Me._TotalLogins
    End Get
End Property

and then update that . I think it won't save readonly properties by default. And why should it anyway. I now it's a hack but hey that's life.

A: Before you change the field call SendPropertyChanging() and then after call SendPropertyChanged("").
This will make the Table entity tracking know something changed.


text:
Q: How to solve the multiple integral $\int\sin^{p-2}(\theta_1)\sin^{p-3}(\theta_2) \cdots \sin(\theta_{p-2})\ d\theta_1d\theta_2\cdots d\theta_{p-1}$? I am wondering how to solve the multiple integrals of this form:
$$
\int_{\theta_1 \in [0,\pi]}\ldots\int_{\theta_{p-2} \in [0,\pi]}\int_{\theta_{p-1} \in [0,2\pi]} \sin^{p-2}(\theta_1)\sin^{p-3}(\theta_2) \cdots \sin^{2}(\theta_{p-3}) \sin(\theta_{p-2})\ \ \  d\theta_1d\theta_2\cdots d\theta_{p-1}
$$
Here, the first $p-2$ integrals go from $[0,\pi]$ while the last goes from $[0,2\pi]$. I was wondering if there was a simple way to solve the integral. Thanks.
How to solve the multiple integral $\int\sin^{p-2}(\theta_1)\sin^{p-3}(\theta_2) \cdots \sin(\theta_{p-2})\ \ \  d\theta_1d\theta_2\cdots d\theta_{p-1}$

A: Hint
This is the area element of $n$ sphere. It is not hard to prove by induction that the integral is
$$
S_{n-1} = \frac{2 \pi^{\frac{n}{2}}}{\Gamma(\frac{n}{2})}
$$
Source: Wikipedia


text:
Q: Entity Relationship Diagram: Composition of primary and foreign keys I have defined the following tables with their attributes:
Table A)    Table B)    Table C)
- ID        - ID        - ID1
- Name      - xxx       - ID2
- Address   - yyy       - zzz
                        - ...
                        - ...

I have two questions:
1) In Table A), ID is my primary key. The ID attribute in Table A) and Table B) are the same and I am not sure if in Table B) ID can be used as a primary and foreign key? Apparently, ID is also a primary key in Table B) but at the same time a foreign key for Table A). Is that allowed?
2) In Table C) I need both attributes ID1 and ID2. None of the two by itself is a primary but they ned the attribute zzz to be. However, the two attributes ID1 and ID2 are more or less interchangeable so that I have the possibility to create two different primary keys: 1) ID1 + zzz OR 2) ID2 + zzz. I am not sure if it matters which key to choose or if this scenario is allowed at all. Or is the primary key in this particular case the combination of all 3 attributes ID1, ID2 and zzz?

A: *

*If ID in A and B is the same then you can merge the two tables and put same ID:
Table AB)
-ID
-name
-address
-xxx
-yyy

so ID should not be the same...

*You can use the primary key as combination of ID1 and ID2


text:
Q: How to simulate postback in nested usercontrols? I'm doing an asp.net application with one page. In this page, I have one usercontrol defined. This usercontrol has a menu (three buttons) and 3 usercontrols defined too. Depending on the clicked button one of the three usercontrols turn to visible true or false.
In these three usercontrols I have a button and a message, and I want to show the message "It's NOT postback" when the button of the menu is clicked, and when the button of the usercontrol is clicked the message will be "YES, it's postback!!!".
The question is that using property "IsPostBack" of the usercontrol or the page the message will never be "It's NOT postback" because of the clicked button of the menu to show the nested usercontrol.
This is the structure of the page:
page
  parent usercontrol
    menu
    nested usercontrol 1
      message
      button
    nested usercontrol 2
    nested usercontrol 3

I know it can be done using ViewState but, there is a way to simulate IsPostBack property or know when is the true usercontrol postback?
Thanks.

A: I have the solution for this problem. When an element fires an event is sent to the server in the Request.Form collection, so I created a property in nested usercontrols that checks if there is a child control (defined in the usercontrol itself) in Request.Form collection:
public bool IsUserControlPostBack
    {
        get
        {
            foreach (Control c in Controls)
                foreach(string key in Page.Request.Form.AllKeys)
                    if( c.ClientID == key.Replace('$','_'))
                        return true;

            return false;
        }
    }

This code can be a property of the usercontrol or, if it's called a lot of times, a variable that it's set on the OnInit event of the usercontrol.


text:
Q: How to start GWT from web service REST Is it possible to run GWT application from web service REST?
@Path("/main")
public class RestService {
  @GET
  @Path("{name}")
  public Response getUserByName(@PathParam("name") String name){

   // return Response.status(200).entity("My name is " + name).build();
  }
}

What is important for me, the URL which calls REST, must not be changed after GWT will run. So when the browser go to localhost:8080/application/main/adam, the REST runs and calls the GWT application which shows message box with My name is adam. After that, I can sill see the same URL in the browser.
Maybe I should explain the reason of my requirements.
I want to create application where the end-user will use only the URLs, example:
localhost:8080/application/somecommand/somedata
localhost:8080/application/anothercommand/anotherdata
No windows, no forms, only URLs.

A: Yes, it is possible. Just serve the HTML page with your GWT app.

A: If you can deal with Urls Like this:
localhost:8080/application#somecommand/somedata
localhost:8080/application#anothercommand/anotherdata
It is just the GWT History-API


text:
Q: How to start an internationalized WPF-Project in SharpDevelop 4.2? I want to create a Software, where the User can choose between several Languages.
As a start i want to learn how to handle Internationalization, since i have never done that before.
As IDE i use SharpDevelop or #develop, however you would spell it.
I want to use C# and WPF, since i'm also learning XAML/WPF at the moment.
So i create a new WPF-Project in ShardDevelop.
On the Main Window i create a ComboBox and a TextBlock.
The ComboBox get's two Entries: "German" and "English".
The textBlock should show "Hallo Welt!" or "Hello World!", depending on the Language which is selected.
Now comes the part where i get stuck.
I guess each language get's a separate file in XML/XAML-Style (Makes sense).
Where are these files and how are they and their Content loaded so that the Text of the selected Language is loaded?
I found several examples but all are something about creating Resource-DLL and using some weird program to decompile them back into a csv-file... i don't get it, isn't there an easier way?

I took the next Step.
The Text of the TextBlock is now loaded via "{StaticResource Strings.MainForm.hwText}". It looks like this now:
<TextBlock Text="{StaticResource Strings.MainForm.hwText}" />

Also I created one ResourceDictionary for German and one for English which both define the key i used in the TextBlock.
In the Application.Resources Part i load one of the ResourceDictionary's per default.
The Problem now is: How can i "unload" this Dictionary during Runtime and Replace it with the other?
Of course i use the SelectionChange-Event of the ComboBox, but what do i do there?

Problem solved!! Thanks to kmatyaszek
Although i changed the Code of the Event-Handler a bit to my needs:
Uri baseUri = new Uri(AppDomain.CurrentDomain.BaseDirectory);
Uri uri = new Uri(baseUri,"Languages\\lang."+((sender as ComboBox).SelectedItem as ComboBoxItem).Tag.ToString()+".xaml");
if(File.Exists(uri.LocalPath) || File.Exists((uri = new Uri(baseUri,"Languages\\lang.de-DE.xaml")).LocalPath)){
    ResourceDictionary dict = new ResourceDictionary();
    dict.Source = uri;
    this.Resources.MergedDictionaries.Add(dict);
}

A: If you created two ResourceDictionary files you can binding by DynamicResource.
Example:
First resource file (Lang.en-US.xaml):
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:system="clr-namespace:System;assembly=mscorlib">

    <system:String x:Key="Username">Username:</system:String>
    <system:String x:Key="Password">Password:</system:String>
    <system:String x:Key="close">Close</system:String>
    <system:String x:Key="login">Login</system:String>
</ResourceDictionary>

Second resource file (Lang.pl-PL.xaml):
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:system="clr-namespace:System;assembly=mscorlib">

    <system:String x:Key="Username">Login:</system:String>
    <system:String x:Key="Password">Hasło:</system:String>
    <system:String x:Key="close">Zamknij</system:String>
    <system:String x:Key="login">Zaloguj</system:String>
</ResourceDictionary>

Set default language in Application resources:
 <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Lang.en-US.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
 </Application.Resources>

Let's say that we have ComboBox like below:
<ComboBox Name="cbLang" Margin="2" SelectionChanged="cbLang_SelectionChanged" >
                <ComboBoxItem Content="English" Tag="en-US" />
                <ComboBoxItem Content="Polish" Tag="pl-PL" />
  </ComboBox>

Code-behind SelectionChanged:
 private void cbLang_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            ResourceDictionary dict = new ResourceDictionary();

            switch (((sender as ComboBox).SelectedItem as ComboBoxItem).Tag.ToString())
            {
                case "en-US":
                    dict.Source = new Uri("Lang.en-US.xaml", UriKind.Relative);
                    break;
                case "pl-PL":
                    dict.Source = new Uri("Lang.pl-PL.xaml", UriKind.Relative);
                    break;
                default:
                    break;
            }
            this.Resources.MergedDictionaries.Add(dict);
        }

And you can binding like this:
 <TextBlock Text="{DynamicResource Username}" VerticalAlignment="Center" />


text:
Q: Question about number of nonnegative integer solutions of linear equation/inequality with positive integer coefficients Given $0<a_1 < a_2 <\cdots < a_n$ all integers and $b > 0$ also a integer,
$$a_1 x_1 + \cdots a_n x_n \le b \tag{1}$$
Question: how many nonnegative integer solutions $\{x_1, \cdots, x_n\}$ are there for $(1)$?
$$a_1 x_1 + \cdots a_n x_n = b \tag{2}$$
Question: how many nonnegative integer solutions $\{x_1, \cdots, x_n\}$ are there for $(2)$?
My question:

*

*I want to know what's the terminology of above problems such that I can search it. Is there some literatures which systematically tackle the above problems and give some analytic solutions? If there is no analytic solution, except the naive brute force algorithm, is there some more efficient way to determine this number?

A: Knapsack Problems may be related to what you are looking for.
I encountered a special case of equation $(2)$ where all $x_i$'s could be either $0$ or $1$.
Refer the section 'The Knapsack Cryptosystem' in the chapter 'Introduction to Cryptography' in the book 'Elementary Number Theory by David M. Burton'.
If $a_1, a_2, ... , a_n$ forms a superincreasing sequence, it also provides a method for finding a solution.


text:
Q: Is there a way to run an svg on click? <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"width="450px" height="450px" viewBox="0 0 450 450" style="enable-background:new 0 0 450 450;" xml:space="preserve">
            <style type="text/css">
                .st0{fill:#FFFFFF;}
                .st1{fill:none;stroke:#000000;stroke-miterlimit:10;}
            </style>
            <rect id="1" x="299.8" y="300.5" class="st0" width="149.5" height="150.5"/>
            <rect id="2" x="150.2" y="300.5" class="st0" width="149.5" height="150.5"/>
            <rect id="3" y="300.5" class="st0" width="149.5" height="150.5"/>
            <rect id="4" x="299.8" y="150.5" class="st0" width="149.5" height="150.5"/>
            <rect id="5" x="150.2" y="150.5" class="st0" width="149.5" height="150.5"/>
            <rect id="6" y="150.5" class="st0" width="149.5" height="150.5"/>
            <rect id="7" x="299.8" class="st0" width="149.5" height="150.5"/>
            <rect id="8" x="150.2" class="st0" width="149.5" height="150.5"/>
            <rect id="9" class="st0" width="149.5" height="150.5"/>
            <line class="path" fill="none" stroke="#000000" x1="149.5" y1="0" x2="149.5" y2="450"/>
            <line class="path" fill="none" stroke="#000000" x1="299.5" y1="450" x2="299.5" y2="0"/>
            <line class="path" fill="none" stroke="#000000" x1="0" y1="150.5" x2="450" y2="150.5"/>
            <line class="path" fill="none" stroke="#000000" x1="450" y1="300.5" x2="0" y2="300.5"/>
        </svg>

I have this svg which is a tic tac toe board. I want it to load(run the animation of the line tags) AFTER the user enters the number of players and player names. Is there a way to do that? the rect elements are what I will use to target areas while playing the game.
.path {
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
  animation: dash 5s linear forwards;
}

@keyframes dash {
  to {
    stroke-dashoffset: 0;
  }
}

A: Like so perhaps i.e. set the class on click?

function run() {
  var lines = document.getElementsByTagName("line");
  for (var i = 0; i < lines.length; i++) {
    lines[i].setAttribute("class", "path");
  }
}
line {
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
}

.path {
  animation: dash 5s linear forwards;
}

@keyframes dash {
  to {
    stroke-dashoffset: 0;
  }
}
<button onclick="run()">click me</button>
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"width="450px" height="450px" viewBox="0 0 450 450" style="enable-background:new 0 0 450 450;" xml:space="preserve">
            <style type="text/css">
                .st0{fill:#FFFFFF;}
                .st1{fill:none;stroke:#000000;stroke-miterlimit:10;}
            </style>
            <rect id="1" x="299.8" y="300.5" class="st0" width="149.5" height="150.5"/>
            <rect id="2" x="150.2" y="300.5" class="st0" width="149.5" height="150.5"/>
            <rect id="3" y="300.5" class="st0" width="149.5" height="150.5"/>
            <rect id="4" x="299.8" y="150.5" class="st0" width="149.5" height="150.5"/>
            <rect id="5" x="150.2" y="150.5" class="st0" width="149.5" height="150.5"/>
            <rect id="6" y="150.5" class="st0" width="149.5" height="150.5"/>
            <rect id="7" x="299.8" class="st0" width="149.5" height="150.5"/>
            <rect id="8" x="150.2" class="st0" width="149.5" height="150.5"/>
            <rect id="9" class="st0" width="149.5" height="150.5"/>
            <line fill="none" stroke="#000000" x1="149.5" y1="0" x2="149.5" y2="450"/>
            <line fill="none" stroke="#000000" x1="299.5" y1="450" x2="299.5" y2="0"/>
            <line fill="none" stroke="#000000" x1="0" y1="150.5" x2="450" y2="150.5"/>
            <line fill="none" stroke="#000000" x1="450" y1="300.5" x2="0" y2="300.5"/>
        </svg>


text:
Q: Small questions regarding residue of $\frac{e^z}{\sin^2 z}$ at $z=k\pi$ Could someone check the correctness following and answer the small questions?

Calculate the residue of $$f(z) = \frac{e^z}{\sin^2 z}$$ at $z=k\pi \;(k \in \mathbb{Z})$

I classify $z=k\pi$ as a pole of order 2.
I find it difficult to use the limit calculation so I try to calculate the Laurent-expansion around $z=k\pi$.
Let $t=z-k\pi$ then $z=t+k\pi$ and $$f(t) = \frac{e^{t+k\pi}}{\sin^2 (t+k\pi)} = \frac{e^{k\pi}e^t}{\sin^2 t}$$
Question 1: can I write $f(t)$ or should I write $f(t+k\pi)$?
Laurent-expansion around $t=0$.
$$\begin{align}
\frac{e^{k\pi}e^t}{\sin^2 t} & = a_{-2}t^{-2}+a_{-1}t^{-1}+\ldots\\
e^{k\pi}\left(1+t+\frac{t^2}{2!}+\ldots\right) &= \left( t-\frac{t^3}{3!}+\ldots\right)^2 \cdot (a_{-2}t^{-2}+a_{-1}t^{-1}+\ldots)\\
e^{k\pi}\left(1+t+\frac{t^2}{2!}+\ldots\right) &= \left( t^2 -\frac{2t^4}{3!}+\ldots\right) \cdot  (a_{-2}t^{-2}+a_{-1}t^{-1}+\ldots)
\end{align}$$
Meaning $$e^{k\pi} = a_{-2}\qquad e^{k\pi}  = a_{-1}$$
Concludes $$e^{k\pi}  = \operatorname*{res}_{t=0} f(t) = \operatorname*{res}_{z=k\pi} f(z)$$
Question 2: if I would want to calculate $a_0$, is the following right?
$$\frac{e^{k\pi}}{2!} = a_0 -\frac{2}{3!}a_{-2}$$

A: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\dsc}[1]{\displaystyle{\color{red}{#1}}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,{\rm Li}_{#1}}
 \newcommand{\norm}[1]{\left\vert\left\vert\, #1\,\right\vert\right\vert}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
There are, at least, two ways to find the residue:

*
*
\begin{align}
{\expo{z} \over \sin^{2}\pars{z}}&=
{\expo{k\pi} \over \sin^{2}\pars{z}}
+\dsc{\expo{k\pi}\pars{z - k\pi} \over \sin^{2}\pars{z}}
+{\expo{k\pi}\pars{z - k\pi}^{2} \over 2\sin^{2}\pars{z}} + \cdots
\\[5mm]&=
{\expo{k\pi} \over \sin^{2}\pars{z}}
+\dsc{\color{#00f}{\expo{k\pi}}
\bracks{{z - k\pi \over \sin\pars{z - k\pi}}}^{2}\,\color{magenta}{1 \over z - k\pi}}
+{\expo{k\pi}\pars{z - k\pi}^{2} \over 2\sin^{2}\pars{z}} + \cdots
\end{align}

*

*
\begin{align}
&\lim_{z\ \to\ k\pi}\totald{}{z}
\bracks{\pars{z - k\pi}^{2}\,{\expo{z} \over \sin^{2}\pars{z}}}
=\color{#00f}{\expo{k\pi}}\ \underbrace{\lim_{z\ \to\ 0}\totald{}{z}
\bracks{z^{2}\expo{z} \over \sin^{2}\pars{z}}}_{\dsc{1}}
\end{align}

$$
\color{#66f}{\large\,{\rm Res}_{\bracks{z\ =\ k\pi}}\bracks{%
{\expo{z} \over \sin^{2}\pars{z}}}} = \color{#66f}{\large\expo{k\pi}}
$$

A: Your approach is correct. Perhaps more direct is
$$
\begin{align}
\frac{e^{k\pi}(1+z+z^2/2+O(z^3))}{z^2(1-z^2/3+O(z^4))}
&=\frac{e^{k\pi}(1+z+5z^2/6+O(z^3))}{z^2}\\
&=\color{#C00000}{e^{k\pi}}\left(\frac1{z^2}+\color{#C00000}{\frac1z}+\frac56+O(z)\right)
\end{align}
$$
Thus, the residue at $z=k\in\mathbb{Z}$ is $e^{k\pi}$.
In the end, everything is about computing the coefficient of $z^{-1}$, which is what you've done.

A: You are making everything a bit too lenghty. Since $e^z$ is an entire function and $\sin^2(z)$ is a periodic function with period $\pi$, the residue is just $e^{k\pi}$ times the residue of $\frac{e^z}{\sin^2 z}$ at $z=0$, that is:
$$\frac{d}{dz}\left.\frac{z^2 e^z}{\sin^2 z}\right|_{z=0}=[z](1+z)=1$$
since both $\frac{z}{\sin z}$ and $\frac{z^2}{\sin^2 z}$ are $1+O(z^2)$ in a neighbourhood of the origin.


text:
Q: Slack API - input box with type password to hide the information Is there anyway to hide the text entered in input box field (similar to HTML password type)?

A: Although all user data is handled with security controls, Slack API currently doesn't support data masking or hiding sensitive data from the screen. I doubt this is a feature that will be added soon. You can find more on this discussion here


text:
Q: Crystal Reports- Change a parameter value for every details view I am working on a Crystal Reports document which I require changing a parameter that will be produced from the code-behind. I already know how to set the parameter's value through the code, however I need it to work dynamically in the details view.
Because the details view can occur many times, I would like to know if it is possible to programmatically set a different value to the parameter every time the details view runs? I know it would be better to get the value from a dataset, which is what I am already doing, but for this value it needs to be entered through a parameter simply because it does not exist in our sql databases.
Any help would be greatly appreciated.

A: /* Set datasource first
         myDataReport.SetDataSource(...)

         myDataReport.SetParameterValue("MyParameter", "Hello");
         */


text:
Q: Not quite adjoint functors What are standard and/or natural examples of pairs of functors $F:C\leftrightarrows D:G$ and unnatural bijections $\hom_D(Fx,y)\to\hom_C(x,Gy)$ for all $x$ and $y$? Can one do this so that the bijections are natural in $x$ and not in $y$?

A: Let $C$ and $D$ both be the category of finite-dimensional (say real) vector spaces and invertible linear maps between them, let $F$ be the identity, and let $G$ take a vector space to its dual.  ($G$ is not functorial on all linear maps, but it is on the invertible ones.)  Then $G y \cong y$ unnaturally, so $\hom(F x, y) = \hom(x, y) \cong \hom(x, G y)$ naturally in $x$ but unnaturally in $y$.


text:
Q: Are Files On Ubuntu One Secure? are my files stored in Ubuntu One secure from the American intelligence agency (NSA)?
In which country are they stored?
Is it better than using Dropbox or any other popular cloud?
Thanks in advance for your answers!

A: This link says they are.

If you need to use cloud storage, you can do away with Google Drive and Dropbox, and instead use a service like Kim Dotcom's Mega, Ubuntu One, or Sparkleshare.


text:
Q: creating Vanilla JS equivalent css method of jQuery I am trying to create a function like the function of jQuery which changes the style of an HTMLElement, probably you have seen it somewhere:
$("button").css("color", "red");

which is pretty handy, so here is what I've tried:
function $(selector, parent=document){
return parent.querySelector(selector);
}

so the above code is the code of the function $ which grabs an HTMLElement from the DOM,this seems to work perfectly.
Now, the next step for me is to define the $ function methods and properties, so the method I want to create is the css method as seen in the previous example:
$.css = function(style, value){
this[style] = value;
}

now after testing the css method it's not working (and of course it will never work, but I'm just trying to deliver my question idea for you).
I know a lot about object-oriented programming in JavaScript, I am comfortable with it, so I have no problem if you posted any answer, I will try my best to understand it.
I've tried a lot to understand what's the magic that the jQuery developers made to create this method.
What do you think the best approach to make it? what about mixins, what if I wanted other functions and not just "$" to inherit this "css" method?

A: To modify styles, you need to set a CSS property of the style declaration object of an element. For example:
elm.style.color = 'red';

You need to modify your $.css to access the current element(s) in the collection, and access their .style[propertyName] property.
You can put the collection onto a property of the instance, and make sure to put the css method as a prototype of the class:

function collection (selector, parent = document) {
  this.elms = parent.querySelectorAll(selector);
}
collection.prototype.css = function(prop, value) {
  for (const elm of this.elms) {
    elm.style[prop] = value;
  }
}
const $ = (...args) => new collection(...args);

$("button").css("color", "red");
<button>a button</button>
<button>a button</button>

Because your $ doesn't use new, you'll either need it to return an instance of a different class (as in the code above), or always use new when calling it, or have $ return its instance created via Object.create, or something like that. There are various methods.

A: Not sure if this is what you're after, but you could just apply the style inline?
var elem = document.querySelector('#some-element');

//set color to red
elem.style.color = 'red';

//set the background color to a light gray
elem.style.backgroundColor = '#e5e5e5';

//set the height to 225px
elem.style.height = '225px';


text:
Q: Verilog testbench for inout Can anybody please help me out with how to write test benches for inout ports in Verilog? I can't instantiate them as reg type variables in the test bench.

A: You can't drive an inout directly as a reg. inout types need to be wire. So, you need a workaround.
The workaround is creating a driver pin that shares the same wire as the module signal. To do this, define a reg variable for your 3-state test signal, then assign it to the inout pin to connect it.
As follows:
module my_testbench;

wire inout_pin;   // bidirectional signal from DUT
reg inout_drive;  // locally driven value
wire inout_recv;  // locally received value (optional, but models typical pad)

assign inout_pin = inout_drive;
assign inout_recv = inout_pin;

then later in your testbench, you can manipulate the drive state of the tristate pin:
initial begin

inout_drive = 1'bz;    // default high-Z

later....
inout_drive = 1'b0;    // drive a value, propagates onto inout_pin

As you expect, the inout_pin will assume the value you drive it with inout_drive as long as the DUT signal is in high-Z state. Likewise, inout_recv will follow the value driven onto inout_pin.
Strictly speaking, you don't need inout_recv to use the value present on inout_pin in your test bench, but it reflects modeling a tristate I/O pin connected to the DUT.

A: You can test them the same way as you assign them from within the module:
reg dir;
reg gen;
wire bidir;

assign bidir = dir ? gen : 1'bz;

MyAmazingModule DUT (
    .myInOut(bidir)
);

initial begin
   dir = 0;
   gen = 0;
   ...
end


text:
Q: How to convert an EXE file for Windows CE without Active Sync I'm able to compile and use Active Sync 4.5 to copy and then run application files in a Windows CE based device. Whenever I copy a file to the device Active Sync will say it will convert the file.
This process of manually uploading the files using Active Sync is slow so I'm now sending the files directly using my application and a TCP sort of file receiver. File is being transferred fine (crc checked).
The problem is that the file does not run complaining with a generic message that the file cannot be opened. My first and only guess is related to this "conversion" process that Active Sync is doing.
I could not find any documentation related to what is is this process and how does it work. Is there any place I can find more information about this conversion? Or is there any tool that can pre-convert so I can transfer it?
The first idea about pre-convert was to copy the file to the device and the copy it back using Active Sync but when copying files out of Windows CE it will convert back to PC format.


text:
Q: Magento 2 : why module-checkout overrides country order? I just wasted 3 hours trying to figure out why I couldn't seem to manipulate the order of the country_id field in the checkout shipping address only to find out that any value I insert in the customer_eav_attribute table is overridden by the magento CE code in the vendor/magento/module-checkout package. Why?!?!
What's the point of having sort order if the core code is going to override the value in the source code?
vendor/magento/module-checkout/view/frontend/layout/checkout_index_index.xml
 <item name="country_id" xsi:type="array">
       <item name="sortOrder" xsi:type="string">115</item>
   </item>


text:
Q: Special connection between 3 tables I created 3 mysql tables:
table 'city': contains cities
i.e   |  name  |
      +========+
      | Athens |
      +--------+
      | Rome   |
      +--------+
      | Paris  |
      +--------+

table 'category': contains categories
i.e   |    name    |
      +============+
      | category_1 |
      +------------+
      | category_2 |
      +------------+

table 'shops': contains shops
i.e   |  name  |  category_name  |  city_name  |
      +========+=================+=============+
      | shop_1 |   category_2    |    Rome     |
      +--------+-----------------+-------------|
      | shop_2 |   category_2    |    Rome     |
      +--------+-----------------+-------------+
      | shop_3 |   category_1    |    Paris    |
      +--------+-----------------+-------------+

I'm trying to create a single query that will allow me to create the following html array(that shows how many shops there are in each city grouped by category):
|        ||   category_1   |  category_2 |
+========++================+=============+
| Athens ||        0       |      0      |
+--------++----------------+-------------|
| Rome   ||        0       |      2      |
+--------++----------------+-------------+
| Paris  ||        1       |      0      |
+--------++----------------+-------------+

Thank you in advance,
Giannis

A: Try this
select c.name,
sum(case when s.category_name='category_1' then 1 else 0 end) as categoty_1,
sum(case when s.category_name='category_2' then 1 else 0 end) as categoty_2
from city as c left join shops as s on c.name=s,city_name
group by c.name

A: Look into this
    SQL select data from multiple tables  tables/32249225?noredirect=1#comment52417831_32249225

A: Try:
select Name, isnull([category_1],0), isnull([category_2],0) from
(
    select city.name as Name, category.name as Category, count(category.name) as   [Count]
    from city left join shops on shops.city_name = city.name
    left join category on category.name =  shops.category_name
    group by  city.name, category.name
) as PivotSource
pivot
(
    sum([Count]) for Category in ([category_1], [category_2])
) as PivotTable


text:
Q: Ormlite + PredicateBuilder "variable referenced from scope '', but it is not defined" When I attempt the following:
   public List<MatterViewModel> ReturnMatchingMatters(IEnumerable<string> matterNames)
    {
        var filter = PredicateBuilder.True<tblMatter>();
        filter = x => matterNames.Any(mattername => mattername.ToLowerInvariant() == x.Matter.ToLowerInvariant());

        return this.dal.DB.GetList<MatterViewModel>(OrmLiteConfig.DialectProvider.ExpressionVisitor<tblMatter>().Where(filter).ToSelectStatement());
    }

I receive the error:
variable 'x' of type '[...]tblMatter' referenced from scope '', but it is not defined
([...] mine)
Essentially, what I'm trying to accomplish is to have the predicate return true if the matter string is contained within any of the matters.
What am I missing? Do I need to do some sort of foreach with a temp variable?

A: The following code accomplishes what I need to do, though might not be the prettiest.
    public List<string> ReturnMatchingMatters(IEnumerable<string> matterNames)
    {

        var filter = PredicateBuilder.True<tblMatter>();
        filter = x => Sql.In(x.Matter, matterNames);

        SqlExpressionVisitor<tblMatter> ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<tblMatter>();

        ev.Select("select Matter from tblmatter");
        ev.Where(filter);

        return this.dal.DB.GetList<string>(ev.ToSelectStatement());
    }