text:
Q: match duplicate string before a specified delimiter cat test.txt
serverabc.test.net
serverabc.qa.net
serverabc01.test.net
serverstag.staging.net
serverstag.test.net

here i need to match the duplicate strings just before the delimiter '.'
So the expected output would be like below. because string "serverabc" and "serverstag" found to be duplicates. Please help.
serverabc.test.net
serverabc.qa.net
serverstag.staging.net
serverstag.test.net

A: awk to the rescue!
$ awk -F\. '{c[$1]++; a[$1]=a[$1]?a[$1]RS$0:$0}
         END{for(k in c) if(c[k]>1) print a[k]}' file

serverabc.test.net
serverabc.qa.net
serverstag.staging.net
serverstag.test.net

A: If it is not going to be used allot I would probably just do something like this:
cut -f1 -d\. foo.txt | sort |uniq -c | grep -v "      1 " | cut -c 9-|sed 's/\(.*\)/^\1\\./' > dup.host
grep -f dup.host foo.txt
serverabc.test.net
serverabc.qa.net
serverstag.staging.net
serverstag.test.net


text:
Q: Cannot find module Estou seguindo esse tutorial para criar um chatbot do link abaixo, e ta dando esse erro, alguem pode me ajudar com o erro? o erro e no arquivo server.js ou no dialogflow.js?
dialogflow.js
const axios = require('axios')
const accessToken = process.env.DIALOGFLOW_ACCESS_TOKEN
const baseURL = 'https://api.dialogflow.com/v1/query?v=20150910'

module.exports = {

send (message) {

    const data = {
      query: message,
      lang: 'pt-BR',
      sessionId: '123456789!@#$%'
    }
    return axios.post(baseURL, data, {
      headers: { Authorization: `Bearer ${accessToken}` }
    })
  }
}

server.js
const express = require('express')
const bodyParser = require('body-parser')
const Pusher = require('pusher')
const cors = require('cors')
require('dotenv').config()
const shortId = require('shortid')
const dialogFlow = require('./dialogFlow')
const app = express()

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

const pusher = new Pusher({
  appId: process.env.PUSHER_APP_ID,
  key: process.env.PUSHER_APP_KEY,
  secret: process.env.PUSHER_APP_SECRET,
  cluster: 'eu',
  encrypted: true
})

app.post('/message', async (req, res) => {
  // simulate actual db save with id and createdAt added
  console.log(req.body);

  const chat = {
    ...req.body,
    id: shortId.generate(),
    createdAt: new Date().toISOString()
  }

  //update pusher listeners

  pusher.trigger('chat-bot', 'chat', chat)

  const message = chat.message;
  const response = await dialogFlow.send(message);

  // trigger this update to our pushers listeners

  pusher.trigger('chat-bot', 'chat', {
    message: `${response.data.result.fulfillment.speech}`,
    type : 'bot',
    createdAt : new Date().toISOString(),
    id: shortId.generate()
  })

  res.send(chat)
})

app.listen(process.env.PORT || 5000, () => console.log('Listening at 5000'))

erro

module.js:549
     throw err;
     ^

Error: Cannot find module './dialogFlow'
     at Function.Module._resolveFilename (module.js:547:15)
     at Function.Module._load (module.js:474:25)
     at Module.require (module.js:596:17)
     at require (internal/module.js:11:18)
     at Object.<anonymous> (/home/marco/Documentos/trabalho/chatbot/chatbotapp/server.js:7:20)
     at Module._compile (module.js:652:30)
     at Object.Module._extensions..js (module.js:663:10)
     at Module.load (module.js:565:32)
     at tryModuleLoad (module.js:505:12)
     at Function.Module._load (module.js:497:3)

A: Pelo que foi relatado o nome do arquivo é dialogflow.js e você está importando dialogFlow. Utilize o require da forma a seguir, caso os arquivos estejam na mesma pasta:
const dialogFlow = require('./dialogflow');

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I update an electron BrowserWindow icon after the window is already opened? With the electron api, I can set the window's icon when calling the BrowserWindow constructor, like this:
  mainWindow = new BrowserWindow({
    icon: __dirname + '/electric-glowing-bear.png');

Unfortunately, I haven't been able to figure out how to update the icon after the fact. There seems to be a way to update the dock icon on Mac OS X, however, I am running Linux.
The purpose of this is so that I can 'badge' the icon with a number to indicate unread messages are waiting.
The only workaround I have found so far is to use a Tray icon, however, I would prefer to show the unread count in the dock / taskbar.

A: You can set BrowserWindow icon when creating windows at like this.
const {BrowserWindow} = require('electron')
let mainWindow = new BrowserWindow({icon: icon})

You can change BrowserWindow icon anytime like this.
mainWindow.setIcon(changeicon);

You can Taskbar icon overlay numbering anytime like this.
mainWindow.setOverlayIcon(overlayicon, description)

Windows overlay NativeImage - the icon to display on the bottom right corner of the taskbar icon. If this parameter is null, the overlay is cleared
description String - a description that will be provided to Accessibility screen readers
Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some sort of application status or to passively notify the user.

A: this should work as long as you have the appropriate files in place
const os = require('os'); // top of file
switch (os.platform()) {
    case 'darwin':
        mainWindow.setIcon('src/app/assets/icons/icon.icns');
        break;
    case 'win32':
        mainWindow.setIcon('src/app/assets/icons/icon.ico');
        break;
    default:
        mainWindow.setIcon('src/app/assets/icons/icon.png');
        break;
}

A: Unfortunately this does not seem to be possible currently, at least not on Linux.


text:
Q: Selecting output from two DB Tables to one output I have two tables, operators (who operates an aircraft) and history (history is the movements of an aircraft). What I need to do is only show the operators which have an "active" flag on the history table as the last entry.
For instance, I have in the history table 10 entries for an aircraft in the history table. the last entry for this is for British Airways and the aircraft is active. this should, therefore, should allow British Airways to be listed on the output.
I then have 10 entries for an aircraft which was with Fly Uk, then has been sold to British Airways. Both had or have the aircraft as active, but as British Airways is the current active operator for the aircraft it shouldn't show FLY UK in this list.
Both Operators may have multiple aircraft in the list, some as active and some as on order, stored, etc.
tables -
History
has a field for operator and status (where this can be active, stored, scrapped, written off)
Aircraft
Has a field for the OperatorName
so it should be something like
select *
from operators
where max history.status = 'active' or 'stored' or 'grounded';

however it's not working?
I have tried various things with the code, changed php version and no better in the situation
select *
from operators
where max history.status = 'active' or 'stored' or 'grounded';

I don't get any output with this

A: You can use a correlated subquery:
select o.*
from operators o
where (
    select h.status
    from history h
    where h.operatorName = o.operatorName
    order by h.operationDate desc
    limit 1
) in ('active', 'stored', 'grounded')

In MySQL 8.0, window functions come handy:
select *
from (
    select
        o.*,
        h.status,
        rank() over(partition by h.operatorName order by h.operationDate desc) rn
    from operators
    inner join history h on h.operatorName = o.operatorName
) t
where
    rn = 1
    and status in ('active', 'stored', 'grounded')

history.status = 'active' or 'stored' or 'grounded' won't work as you expect. This will always be true.
There is in fact 3 conditional statements :
history.status = 'active'
'stored'
'grounded'
'stored' and 'grounded' will never be false, because a non empty string is not considered false
Your condition can be rewritten this way, and the logic is kept : (history.status = 'active') or (TRUE) or (TRUE) that evaluates to TRUE no matter the value of history.status


text:
Q: When i can access to SDL_Rendrerer after maximizing window? I try to redraw window only when is need, but when window is resize in a hop (for example maximize), SDL_Renderer is not usable in new size some time after action.
Here is my simple example code:
#include <SDL2/SDL.h>

bool redraw = true;

void draw(SDL_Renderer* renderer, SDL_Rect& rect)
{
    SDL_SetRenderDrawColor(renderer, 0, 0, 50, 0xFF);
    SDL_RenderClear(renderer);

    SDL_SetRenderDrawColor(renderer, 90, 90, 90, 0xFF);
    SDL_RenderDrawLine(renderer, 0, 0, rect.w, rect.h);

    SDL_RenderPresent(renderer);
    redraw = false;
}

SDL_Rect resize(const SDL_Event& event)
{
    int win_w = (int) event.window.data1;
    int win_h = (int) event.window.data2;

    SDL_Rect rect = {0, 0, win_w, win_h};
    redraw = true;
    return rect;
}

int main(int argc, char** argv)
{
    SDL_Init(SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO);
    SDL_Window* window = SDL_CreateWindow("Maximize test",
                              SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED,
                              800, 450, 0);
    SDL_SetWindowResizable(window, SDL_TRUE);

    SDL_Renderer* renderer = SDL_CreateRenderer(
            window, -1,
            SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

    bool running = true;
    SDL_Event event;
    SDL_Rect rect = {0, 0, 800, 450};

    while (running) {
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
                case SDL_QUIT:
                    running = false;
                    break;
                case SDL_WINDOWEVENT:
                    switch (event.window.event) {
                        case SDL_WINDOWEVENT_RESIZED:
                            rect = resize(event);
                            break;
                    }
                    break;
            }

            if (redraw) {
                draw(renderer, rect);
            }
        }
    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    return 0;
}

At first, I try to get new renderer size SDL_GetRendererOutputSize in same result like getting size from event.
When I try to resize window with typical mouse motion actions, it works fine. But maximize or window manager resizing to one screen side does not work.
I try to use different event like SDL_WINDOWEVENT_SIZE_CHANGED, but with same result.
And yes, normally, I checks all SDL calls, with SDL_RenderDrawLine but without any errors.


text:
Q: Demonstrate compiler's optimization effects when volatile keyword is not used during signal handling? In the following code, I have not made the variable quit has volatile sig_atomic_t. I have left it as a plain int.
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

#define UNUSED(x) (void) (x)

int quit;

void sigusr1_handler(int sig)
{
    UNUSED(sig);
    write(1, "handler\n", 8);
    quit = 1;
}

int main()
{
    struct sigaction sa;

    sa.sa_handler = sigusr1_handler;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);

    if (sigaction(SIGUSR1, &sa, NULL) == -1) {
        perror("sigaction");
        return 1;
    }

    quit = 0;
    while (!quit) {
        printf("Working ...\n");
        sleep(1);
    }

    printf("Exiting ...\n");
    return 0;
}

Since the quit variable is not specified as volatile, I was expecting that the compiler's optimizer would optimize the while-loop in the code to:
    while (1) {
        printf("Working ...\n");
        sleep(1);
    }

But I don't see this happening. On one terminal, I run the following.
$ gcc -O3 foo.c && ./a.out
Working ...
Working ...

On another terminal, I send SIGUSR1 to my program.
$ pkill -USR1 a.out

On the first terminal, the output shows that the program's signal handler is invoked and the while-loop quits.
Working ...
Working ...
handler
Exiting ...
$

How can I demonstrate the optimization of the loop due to quit not being volatile?

A: It can be difficult to force the compiler to optimize the load of quit out from the while conditional. I was able to do it by removing the body of the while loop:
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

#define UNUSED(x) (void) (x)

int quit;

void sigusr1_handler(int sig)
{
    UNUSED(sig);
    write(1, "handler\n", 8);
    quit = 1;
}

int main()
{
    struct sigaction sa;

    sa.sa_handler = sigusr1_handler;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);

    if (sigaction(SIGUSR1, &sa, NULL) == -1) {
        perror("sigaction");
        return 1;
    }

    quit = 0;
    while (!quit) {
        //printf("Working ...\n");
        //sleep(1);
    }

    printf("Exiting ...\n");
    return 0;
}

When compiling for x86-64 with -O3 on gcc version 5.4 this results in an infinite loop which doesn't check the quit variable. Notice the jump-to-self at .L5:
.LC0:
        .string "handler\n"
sigusr1_handler(int):
        sub     rsp, 8
        mov     edx, 8
        mov     esi, OFFSET FLAT:.LC0
        mov     edi, 1
        call    write
        mov     DWORD PTR quit[rip], 1
        add     rsp, 8
        ret
.LC2:
        .string "sigaction"
main:
        sub     rsp, 168
        lea     rdi, [rsp+8]
        mov     QWORD PTR [rsp], OFFSET FLAT:sigusr1_handler(int)
        mov     DWORD PTR [rsp+136], 0
        call    sigemptyset
        xor     edx, edx
        mov     rsi, rsp
        mov     edi, 10
        call    sigaction
        cmp     eax, -1
        je      .L7
        mov     DWORD PTR quit[rip], 0
.L5:
        jmp     .L5
.L7:
        mov     edi, OFFSET FLAT:.LC2
        call    perror
        mov     eax, 1
        add     rsp, 168
        ret
quit:
        .zero   4

Changing the definition to volatile int quit; causes the correct behavior. See the mov, test, and je instructions at .L6:
.LC0:
        .string "handler\n"
sigusr1_handler(int):
        sub     rsp, 8
        mov     edx, 8
        mov     esi, OFFSET FLAT:.LC0
        mov     edi, 1
        call    write
        mov     DWORD PTR quit[rip], 1
        add     rsp, 8
        ret
.LC2:
        .string "sigaction"
.LC3:
        .string "Exiting ..."
main:
        sub     rsp, 168
        lea     rdi, [rsp+8]
        mov     QWORD PTR [rsp], OFFSET FLAT:sigusr1_handler(int)
        mov     DWORD PTR [rsp+136], 0
        call    sigemptyset
        xor     edx, edx
        mov     rsi, rsp
        mov     edi, 10
        call    sigaction
        cmp     eax, -1
        je      .L11
        mov     DWORD PTR quit[rip], 0
.L6:
        mov     eax, DWORD PTR quit[rip]
        test    eax, eax
        je      .L6
        mov     edi, OFFSET FLAT:.LC3
        call    puts
        xor     eax, eax
.L5:
        add     rsp, 168
        ret
.L11:
        mov     edi, OFFSET FLAT:.LC2
        call    perror
        mov     eax, 1
        jmp     .L5
quit:
        .zero   4

You can play with both examples here: without volatile and with volatile.


text:
Q: outer folds errors in nested cross-validation I have a time series data that I wish to be able to obtain the general performance of it. For that, I use nested cross-validation with time series flavor as described in this amazing blog.
As you have to start with an initial window size, I choose my window size to be 52.  The outer fold is mainly done at each time step left, from timestep 53 onwards.
For each outer fold, I compute the average error, in this case, RMSE in order to be able to see the error's fluctuation/trend as we move through the time steps. I wish by the end of the day to be able to see that the error decreases as I move forward with timesteps and to reach a point were it stabilizes.
I know that the error in each outer fold might be affected with the choice of the hyperparameters from the inner fold. However, I do have model stability (i.e. the chosen set of hyper parameters from the inner fold is the same). However, I plot the change in the outer fold's RMSE over the time steps and this is what I got:
The so-called 'testing errors' is the RMSE of each outer fold, and the so-called 'validation errors' is the average RMSE of each inner fold.
I am surprised from the harsh fluctauations in the outer fold RMSE. Can someone explain:

*

*Is that normal ?

*If not, what might be the reason?

*Also if not, what shall I do to make this better and more stable ?

*The validation error is stable, which is a good sign, isn't it ?

Note: My dataset is small in size (154 samples). I am unable to collect more data.Also, the

A: If I understand correctly what you are doing,

*

*each of the red dots is the estimated performance by the inner crossmoving window validation. I.e., it is an RMSE based on 5 cases,

*each of the blue dots is the estimated performance by the outer crossmoving window validation, i.e. the "RMSE" based on 1 case (the next one after the 52 training cases).  In this case, this RMSE over 1 case is also the absolute error for that case, which is why I put the RMSE in quotes, and

*this is done 102 times, testing cases 53 - 154:

t t t ... t t t r r r r r b x x x ... x x x
x t t t ... t t t r r r r r b x x x ... x x
x x t t t ... t t t r r r r r b x x x ... x
.
:
x x x ... x x x t t t ... t t t r r r r r b

with x = unused, t = inner training, r = red = inner testing = hyperparameter tuning, b = outer testing
Then:

*

*The random uncertainty of the RMSE depends on the number of cases that enter the calculation of the RMSE: the more cases, the lower the variance on the RMSE estimate, thus the less noisy we expect the estimate to look.
So the blue estimates being based on 1 case each are expected to be more noisy than the red estimates which are based on 5 cases each.

*Unless you retrain after fixing hyperparameters on t t t ... t t t r r r r r (do you?), the blue predictions have more lag, i.e. are further into future. This may lead to higher variance error in the predictions, thus also of the blue error.

*Also, if the inner RMSE estimate is based on 5 consecutive time points and shifted one at a time, it must have considerable auto-correlation (which it does). Autocorrelation will make it look ness noisy.

*Due to the complex interaction (the inner RMSE estimte being actually part of the training) I find it difficult to say whether the outer RMSE estimate is surprisingly noisy. A simulation of the behaviour of the two RMSEs may be helpful.

As RMSE is the square root of the average squared error (as opposed to averaging RMSEs) the variance uncertainty of our RMSE estimate does not quite follow the simple variance of the mean $s^2_\bar x = \frac{1}{n} s^2_x$ dependency. See variance of variance estimate for more information.

As a side note, I had only a very quick glance at the blog post you linked, so I cannot quite comment on its total virtue. However, already the first glance did raise some red flags:

*

*RMSE over 1 case is just absolute error of that one case.
Of course, one can use this - but a reminder of this property to the unsuspecting reader would have been good. I wouldn't have mentioned this, though, if there weren't the nex concern:

*Taking the average of $i$ 1-case-"RMSE"s is not the same as calculating the RMSE over $i$ cases, it's the MAE of those $i$ cases.
Again, it is not forbidden to do this - but it should IMHO be clearly labeled as "mean RMSE as opposed to RMSE of the pooled predictions", and again the unsuspecting reader should be made aware of what is done. Also a justification would be in place, IMHO.
Together, these two points make me suspicious whether the author actually calculates what they think they are calculating (to me  this has a distinct "smell" of possible error with operator precedence).

*Looking at RMSE of models with a varying length of the training window makes a lot of sense. But pooling these results across widely varying training window sizes IMHO does require at the very least a justification.
I don't have access to the papers the blog references, but I'd have expected methods with rolling origin in their name to actually have a moving origin, i.e. a moving training window of fixed size. But the day-chaining described as being the same does use expanding windows with fixed origin (and moving end).

*"cross validation" seems to me a rather unlucky choice of name as it's explicitly about not doing cross validation due to the time dependency - though to be fair that may be the result of the blog post author trading off unlucky choice of name vs. term established by the Bergmeir & Benítez paper.
I'd have used expanding window validation (or rolling window valiation in your case) instead.

A: @cbeleites
Thank you so much!!! Indeed I realize what you are saying is very very true. The reason why I did not using rolling forecasts directly is because I have suite of models: Lasso, Ridge.., etc. from which I want to pick among them the best performing model, and then do rolling forecast using THAT picked model afterwards. However I want to tune their hyper parameters. That is why I am resorting to nested cross validation. Now after your comment, I am doing the following: n the outer loop, I divide the data now into 70 training and 20 testing, and the 70 training I divide them in the inner loop into 50 training and 10 validation. As I will use expanding window as you have suggested, the training sizes in both the inner and the outer loop increase one time step at a time, with the testing and validation sizes being fixed to 20 and 10 respectively in each of the folds (inner and outer)
This is what I got so far:

Now it is very clear, thanks to you, that doing "RMSE" on 1 sample was a very big, let me call it, mistake (since as you said it is just the absolute error).


text:
Q: Symfony 2, Twig: how not to escape field value (used with backbonejs & symfony 2) I'm rendering a prototype using below code:
{{form_widget(form.get('prototype').myField, {'attr': {'value': '<%= myModelProperty %>'} }) }}

BackboneJS is supposed to read the code generated by this twig block, and replace the <%= myModelProperty %> by some model property value.
And this doesn't happen because the value is escaped in twig and thus replaced by:
<%= viewport %>

I've tried to force the value to RAW in the *form_div_layout.html* file:
> {% block field_widget %} {% spaceless %}
>     {% set type = type|default('text') %}
>     <input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value|raw }}" {% endif %}/> {%
> endspaceless %} {% endblock field_widget %}

but without success.
So my question is how not to escape the field value in twig.
Thanks!
EDIT
Solution:
So in fact the method was right, I have to use the "raw" filter to get my variable not escaped.
I've an autoescape block set that englobe this particular output which is why the reason it has to be "un-escaped".
Twig bundle of Symfony 2 provided several block to render form data, and those uses a specific block for attribute rendering called "{% block widget_attributes %}".
What I did is edit this block (I've a separated template file with all my customized blocks) so I can add a layer of "should this value be escaped or not":
{% block widget_attributes %}
{% spaceless %}
    id="{{ id }}" name="{{ full_name }}"{% if read_only %} disabled="disabled"{% endif %}{% if required %} required="required"{% endif %}{% if max_length %} maxlength="{{ max_length }}"{% endif %}{% if pattern %} pattern="{{ pattern }}"{% endif %}

    {% for attrname,attrvalue in attr %}
        {# Attribute value can be defined as an array. ['data']: contains the actual value, ['escape']: boolean (true if the value HAS to be escaped)#}
        {% if attrvalue.data is defined %}
            {% if not attrvalue.escape %}
                {{attrname}}="{{ attrvalue.data|raw }}"
            {% else %}
                {{attrname}}="{{ attrvalue.data|e }}"
            {% endif %}
        {% else %}
            {{attrname}}="{{attrvalue}}"
        {% endif %}
    {% endfor %}

{% endspaceless %}
{% endblock widget_attributes %}

Called from my twig file:
{{ form_widget(form.displays.get('prototype').myField, {'attr': {'value': { 'data': myvalue, 'escape': false } } }) }}

The escape is done when printing the value so in the {{ }} twig tag, so what I was doing earlier was sending an unescaped value to a block where the print is actually called and where the value was thus escaped.
This works for me!
thanks!

A: Solution: So in fact the method was right, I have to use the raw filter to get my variable not escaped. I've an autoescape block set that englobe this particular output which is why the reason it has to be "un-escaped".
Twig bundle of Symfony 2 provided several block to render form data, and those uses a specific block for attribute rendering called {% block widget_attributes %}.
What I did is edit this block (I've a separated template file with all my customized blocks) so I can add a layer of "should this value be escaped or not":
{% block widget_attributes %}
  {% spaceless %}
      id="{{ id }}" name="{{ full_name }}"{% if read_only %} disabled="disabled"{% endif %}{% if required %} required="required"{% endif %}{% if max_length %} maxlength="{{ max_length }}"{% endif %}{% if pattern %} pattern="{{ pattern }}"{% endif %}

      {% for attrname,attrvalue in attr %}
        {# Attribute value can be defined as an array. ['data']: contains the actual value, ['escape']: boolean (true if the value HAS to be escaped)#}
        {% if attrvalue.data is defined %}
          {% if not attrvalue.escape %}
            {{ attrname }}="{{ attrvalue.data|raw }}"
          {% else %}
            {{ attrname }}="{{ attrvalue.data|e }}"
          {% endif %}
        {% else %}
          {{ attrname }}="{{ attrvalue }}"
        {% endif %}
      {% endfor %}

  {% endspaceless %}
{% endblock widget_attributes %}

Called from my twig file:
{{ form_widget(form.displays.get('prototype').myField, {'attr': {'value': { 'data': myvalue, 'escape': false } } }) }}

The escape is done when printing the value so in the {{ }} twig tag, so what I was doing earlier was sending an unescaped value to a block where the print is actually called and where the value was thus escaped.
This works for me! thanks!

A: Using the raw filter is the proper way to do this. If you're not having success with that, then something else is wrong.  Try clearing your cache or disable twig caching in  app/config/config.yml
twig:
    cache: ~

If it's not a caching issue, then I'm unsure where to look next.


text:
Q: If $d(f(x), f(y)) \leq kd(x, y)$ for all $x, y \in X$. Then $f$ is continuous and has exactly one fixed point Let $d$ be a complete metric for $X$. Let $f: X \to X$ be a function. Suppose there is a number $k$, with $0 < k < 1$, such that $d(f(x), f(y)) \leq kd(x, y)$ for all $x, y \in X$. Then $f$ is continuous and has exactly one fixed point.
To show that $f$ is continuous, it felt like a good idea to use sequential continuity. So we take a convergent sequence $x_n$ with limit $x$. Since $X$ iss complete, we know that $x_n$ is a Cauchy sequence. So for every $\varepsilon/k > 0$ we have some $N \in \mathbb N$ such that for every $n, m \geq N$ we have $d(x_n, x_m) < \varepsilon/k$. But, if $d(x_n, x_m) < \varepsilon/k$, then $d(f(x_n), f(x_m)) < \varepsilon$. So $f(x_n)$ is a Cauchy sequence which converges to $f(x)$. Hence $f$ is continuous.
My problem is how to show that $f$ has exactly one fixed point. What I want to do is assume that $f$ has no fixed points, and then assume that $f$ has at least two, and obtain contradictions. However, I'm not sure how to proceed after assuming $f$ has no fixed points.

A: As for continuity, there is a simpler way: Show that for each $\varepsilon>0$ and $x\in X$, there exists some $\delta>0$ such that if $y\in X$ and $d(y,x)<\delta$, then $d(f(y),f(x))<\varepsilon$. For fixed $\varepsilon>0$ and $x\in X$, take $\delta\equiv \varepsilon/k$. Therefore, if $y\in X$ and $d(y,x)<\delta$, then $$d(f(y),f(x))\leq kd(y,x)<k\delta=\varepsilon,$$ as claimed.

The other claim is Banach's famous fixed-point theorem, also known as the contraction mapping theorem. See a proof, for example, here. The main idea is to construct a special Cauchy sequence, which, in turn, will be convergent, given that the metric space is complete. The limit of this special Cauchy sequence will be a fixed point of the function $f$.

Uniqueness is actually easier than existence, let me show it here. Suppose that the existence of a fixed point $x^{\star}\in X$ of $f$ has already been proven. Suppose also that $y^{\star}\in X$ is another fixed point of $f$. Then, $x^{\star}=f(x^{\star})$ and $y^{\star}=f(y^{\star})$. Therefore, $$d(x^{\star},y^{\star})=d(f(x^{\star}),f(y^{\star}))\leq kd(x^{\star},y^{\star}).$$ Rearranging the two extreme sides of this inequality, $$(k-1)d(x^{\star},y^{\star})\geq0.$$ Since $k-1<0$, this is possible only if $d(x^{\star},y^{\star})\leq 0$. Since $d$ is a metric, one now has $d(x^{\star},y^{\star})=0$, so $x^{\star}=y^{\star}$. It follows that the fixed point—if any exists—is unique.


text:
Q: Detect if the second div is currently seen I am trying to detect the current div that is currently div that is currently seen by the user and trigger an action: http://jsfiddle.net/w7X9N/2293/
I have tried this, but for some reason is not triggering the action. I tried also on scroll and still it did not detected the white background div

jQuery(
  function($) {
    $('#bla').bind('scroll', function() {
      if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
        alert('user viewing div');
      }
    })
  }
);
#flux {
  width: 200px;
  height: 150px;
  overflow: auto;
}
#bla {
  background: #FFF
}

    Lorem ipsum dolor sit amet

Consectetuer augue nibh lacus at

Pretium Donec felis dolor penatibus

Phasellus consequat Vivamus dui lacinia

Ornare nonummy laoreet lacus Donec

Ut ut libero Curabitur id

Dui pretium hendrerit sapien Pellentesque

    THIS IS THE DIV THAT SHOULD TIGGER ACTION

Phasellus consequat Vivamus dui lacinia

Ornare nonummy laoreet lacus Donec

Ut ut libero Curabitur id

Dui pretium hendrerit sapien Pellentesque

Pretium Donec felis dolor penatibus

Phasellus consequat Vivamus dui lacinia

Ornare nonummy laoreet lacus Donec

Ut ut libero Curabitur id

Dui pretium hendrerit sapien Pellentesque

Pretium Donec felis dolor penatibus

Phasellus consequat Vivamus dui lacinia

Ornare nonummy laoreet lacus Donec

Ut ut libero Curabitur id

Dui pretium hendrerit sapien Pellentesque

123456

123456

123456

123456

123456

123456

A:

var viewed = 0;
$('div#flux').scroll(function() {
    if ($(this).scrollTop() >= $('#bla').offset().top && viewed==0) {
      alert('user viewing div');
      viewed = 1;
    }
});
#flux {
  width: 200px;
  height: 150px;
  overflow: auto;
}
#bla {
  background: #FFF
}

    Lorem ipsum dolor sit amet

 Consectetuer augue nibh lacus at

 Pretium Donec felis dolor penatibus

 Phasellus consequat Vivamus dui lacinia

 Ornare nonummy laoreet lacus Donec

 Ut ut libero Curabitur id

 Dui pretium hendrerit sapien Pellentesque

    THIS IS THE DIV THAT SHOULD TIGGER ACTION

 Phasellus consequat Vivamus dui lacinia

 Ornare nonummy laoreet lacus Donec

 Ut ut libero Curabitur id

 Dui pretium hendrerit sapien Pellentesque

Pretium Donec felis dolor penatibus

 Phasellus consequat Vivamus dui lacinia

 Ornare nonummy laoreet lacus Donec

 Ut ut libero Curabitur id

 Dui pretium hendrerit sapien Pellentesque

Pretium Donec felis dolor penatibus

 Phasellus consequat Vivamus dui lacinia

 Ornare nonummy laoreet lacus Donec

 Ut ut libero Curabitur id

 Dui pretium hendrerit sapien Pellentesque

123456

123456

123456

123456

123456

123456

A: You are checking "on scroll" wrong element. Just rewrite  $('#bla').bind('scroll'... to  $('#flux').bind('scroll'...


text:
Q: Kofax Total Agility-Web Service Call I am currently working on building a workflow within Kofax Total Agility Process Designer. Upon analysis, understood that KTA would be able to call an external webservice.
I wanted to know if there is anyway we could send across byte[] through the webservice call from within KTA designer.
Any help is much appreciated.

A: Although much of the KTA API can be called from the interface within the KTA Designer, some functions would need to be called from code (script activity or .NET assembly).  Functions that use a byte array as inputs or output are a good example of functions that would need to be called in code, because the variables in the designer don't have a way to represent a byte array.


text:
Q: Xamarin Forms SQLite instance crash I'm learning about Xamarin Forms, FreshMVVM and SQLite. I'll give my best to explain the issue.
I'm trying to implement simple Login/Register pages. So far I've followed this Microsoft documentation. I do understand that the problem is when I call await UserDatabase.Instance in LoginPageModel.cs, the application just freeze and I am unable to understand why. But please take a note that when I try to call await UserDatabase.Instance in RegisterPageModel.cs it works as intended. Only when I try to call it in LoginModelPage.cs it crashes
UserDatabase.cs
public class UserDatabase
    {
        private static SQLiteAsyncConnection Database;

        public static readonly AsyncLazy<UserDatabase> Instance = new AsyncLazy<UserDatabase>(async () =>
        {
            var instance = new UserDatabase();
            CreateTableResult result = await Database.CreateTableAsync<User>();
            return instance;
        });

        public UserDatabase()
        {
            Database = new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);
        }

        public Task<User> LogInUserAsync(string username, string password)
        {
            return Database.Table<User>().Where(x => x.UserName == username && x.Password == password).FirstOrDefaultAsync();
        }

        public Task<int> SaveUserAsync(User user)
        {
            if (user.UserId != 0)
            {
                return Database.UpdateAsync(user);
            }
            else
            {
                return Database.InsertAsync(user);
            }
        }
}

And I have LoginPage.cs and RegisterPage.cs:
RegisterPageModel.cs
 public class RegisterPageModel : FreshBasePageModel
    {
        public Command RegisterCommand { get; }

        public string UsernameEntry { get; set; }

        public string PasswordEntry { get; set; }

        public string ConfirmPasswordEntry { get; set; }

        public RegisterPageModel()
        {
            RegisterCommand = new Command(() =>
            {
                // if passwords does not match, show alert. Otherwise register user.
                if (PasswordEntry == ConfirmPasswordEntry)
                {
                    User = new User
                    {
                        UserName = UsernameEntry,
                        Password = PasswordEntry
                    };
                    SaveUser(User);

                    CoreMethods.PushPageModel<LoginPageModel>();
                }
                else
                {
                    Application.Current.MainPage.DisplayAlert("Try again", "Passwords does not match!", "Ok");
                }
            });
        }

        private async void SaveUser(User user)
        {
            UserDatabase database = await UserDatabase.Instance;
            await database.SaveUserAsync(user);
        }
}

LoginPageModel.cs
public class LoginPageModel : FreshBasePageModel
    {
        public Command RegisterCommand { get; }

        public string UsernameEntry { get; set; }

        public string PasswordEntry { get; set; }

        public Command LoginCommand { get; set; }

        public LoginPageModel()
        {
            // When we press Register button, redirect us to the register page
            RegisterCommand = new Command(() =>
            {
                CoreMethods.PushPageModel<RegisterPageModel>();
            });

            // When we press on Login button login user and redirect to the main page
            LoginCommand = new Command(() =>
            {
                if (LoginUser().Result)
                {
                    CoreMethods.PushPageModel<MainPageModel>();
                }
                else
                {
                    Application.Current.MainPage.DisplayAlert("Login Failed", "Incorrect Username or Password!", "Ok");
                }

            });
        }

        private async Task<bool> LoginUser()
        {
            UserDatabase database = await UserDatabase.Instance;
            User user = await database.LogInUserAsync(UsernameEntry, PasswordEntry);
            if (user == null)
            {
                // store Userdetails
                Application.Current.Properties["UserDetail"] = JsonConvert.SerializeObject(user);

                // Set it to true
                Application.Current.Properties["IsLoggedIn"] = bool.TrueString;

                return true;
            }
            else
            {
                return false;
            }
        }
    }

A: To resolve this issue I needed to change LoginUser Method
From this:
        private async Task<bool> LoginUser()
        {
            UserDatabase database = await UserDatabase.Instance;
            User user = await database.LogInUserAsync(UsernameEntry, PasswordEntry);
            if (user == null)
            {
                // store Userdetails
                Application.Current.Properties["UserDetail"] = JsonConvert.SerializeObject(user);

                // Set it to true
                Application.Current.Properties["IsLoggedIn"] = bool.TrueString;

                return true;
            }
            else
            {
                return false;
            }
        }

To this:
        private async void LoginUser()
        {
            UserDatabase database = await UserDatabase.Instance;
            User user = await database.LogInUserAsync(UsernameEntry, PasswordEntry);
            if (user == null)
            {
                // store Userdetails
                Application.Current.Properties["UserDetail"] = JsonConvert.SerializeObject(user);

                // Set it to true
                Application.Current.Properties["IsLoggedIn"] = bool.TrueString;
            }
            else
            {
                await Application.Current.MainPage.DisplayAlert("Login Failed", "Incorrect Username or Password!", "Ok");
            }
        }


text:
Q: Is there a way to run Adobe CC programs that require Windows 10 on Windows Server 2016 Essentials? I am a video creator, and I am looking to offload the heavy rendering from my main computer (running Windows 10) to my home server (currently running CentOS 7, although I'm not attached to that operating system).  I know that Adobe Premiere video won't render directly on Linux, so I thought I might use my otherwise-unused Windows Server 2016 Essentials license.  Is there a way to get Adobe Media Encoder to run on Server 2016?  Or do I need to go out and get another Win10 license?
If this belongs on Server Fault as opposed to here, I apologize.  I was under the impression that since it isn't being used by a business (yet!) this question belongs here.

A: Windows Server 2016 is based on Redstone 1, the same as Windows 10 1607.  Server 2019 is based on Redstone 5, the same as Windows 10 1809.  Adobe Media Encoder CC version 13 requires Windows 10 1703 or newer.
Even though Adobe doesn't list Windows Server as a supported operating system, I would expect it to work on Server 2019, but not Server 2016.

A: By default windows server will block installation due to IE Enhanced Security Configuration. You will have to disable it by opening the Server Manager. I have shown how to do this on this YouTube Video: https://youtu.be/E46PMd4i_Gk


text:
Q: Xcode crash (stop) when he reaches a breakpoint (mix project) This question looks like it has already been asked here, but since it is not answered and it is maybe not the same problem, I ask myself.
I use everything on last version (Xcode 6.1.1, Pods and a swift project inside my app as a core).
If I add a breakpoint or if app crash on the main of my app, I always get a crash of Xcode. If the breakpoint or the crash is inside the swift core project, it won't crash, but use po myVar will crash Xcode.
For the moment I can live with the second crash, but the first one is really too hard for me as I have to make quickly a screenshot each time Xcode will crash to figure what's going on and try to debug (and wait to reload everything).
I hope someone will understand this Xcode crash log and help me.
Process:               Xcode [701]
Path:                  /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier:            com.apple.dt.Xcode
Version:               6.1.1 (6611)
Build Info:            IDEFrameworks-6611000000000000~4
App Item ID:           497799835
App External ID:       810788292
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           Xcode [701]
User ID:               501

Date/Time:             2014-12-08 10:53:34.748 +0100
OS Version:            Mac OS X 10.10.1 (14B25)
Report Version:        11
Anonymous UUID:        8AB8EC6D-DC04-2B25-FD83-704CE00176D4

Time Awake Since Boot: 4000 seconds

Crashed Thread:        19  <DBGLLDBSessionThread (pid=2045)>

Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000000090

VM Regions Near 0x90:
-->
    __TEXT                 000000010bc31000-000000010bc32000 [    4K] r-x/rwx SM=COW  /Applications/Xcode.app/Contents/MacOS/Xcode

Application Specific Information:
ProductBuildVersion: 6A2008a

Thread 0:: Dispatch queue: com.apple.main-thread
0   libsystem_kernel.dylib          0x00007fff916b752e mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff916b669f mach_msg + 55
2   com.apple.CoreFoundation        0x00007fff9afddb14 __CFRunLoopServiceMachPort + 212
3   com.apple.CoreFoundation        0x00007fff9afdcfdb __CFRunLoopRun + 1371
4   com.apple.CoreFoundation        0x00007fff9afdc838 CFRunLoopRunSpecific + 296
5   com.apple.HIToolbox             0x00007fff8f04443f RunCurrentEventLoopInMode + 235
6   com.apple.HIToolbox             0x00007fff8f0441ba ReceiveNextEventCommon + 431
7   com.apple.HIToolbox             0x00007fff8f043ffb _BlockUntilNextEventMatchingListInModeWithFilter + 71
8   com.apple.AppKit                0x00007fff995a36d1 _DPSNextEvent + 964
9   com.apple.AppKit                0x00007fff995a2e80 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 194
10  com.apple.dt.DVTKit             0x000000010c36c6fd -[DVTApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 237
11  com.apple.AppKit                0x00007fff99596e23 -[NSApplication run] + 594
12  com.apple.AppKit                0x00007fff995822d4 NSApplicationMain + 1832
13  libdyld.dylib                   0x00007fff94ea55c9 start + 1

Thread 1:: Dispatch queue: com.apple.libdispatch-manager
0   libsystem_kernel.dylib          0x00007fff916bd22e kevent64 + 10
1   libdispatch.dylib               0x00007fff9bd1ba6a _dispatch_mgr_thread + 52

Thread 2:: com.apple.NSURLConnectionLoader
0   libsystem_kernel.dylib          0x00007fff916b752e mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff916b669f mach_msg + 55
2   com.apple.CoreFoundation        0x00007fff9afddb14 __CFRunLoopServiceMachPort + 212
3   com.apple.CoreFoundation        0x00007fff9afdcfdb __CFRunLoopRun + 1371
4   com.apple.CoreFoundation        0x00007fff9afdc838 CFRunLoopRunSpecific + 296
5   com.apple.CFNetwork             0x00007fff9500dd20 +[NSURLConnection(Loader) _resourceLoadLoop:] + 434
6   com.apple.Foundation            0x00007fff8ed19b7a __NSThread__main__ + 1345
7   libsystem_pthread.dylib         0x00007fff93f812fc _pthread_body + 131
8   libsystem_pthread.dylib         0x00007fff93f81279 _pthread_start + 176
9   libsystem_pthread.dylib         0x00007fff93f7f4b1 thread_start + 13

Thread 3:: com.apple.CFSocket.private
0   libsystem_kernel.dylib          0x00007fff916bc3f6 __select + 10
1   libsystem_pthread.dylib         0x00007fff93f812fc _pthread_body + 131
2   libsystem_pthread.dylib         0x00007fff93f81279 _pthread_start + 176
3   libsystem_pthread.dylib         0x00007fff93f7f4b1 thread_start + 13

Thread 4:
0   libsystem_kernel.dylib          0x00007fff916b752e mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff916b669f mach_msg + 55
2   com.apple.CoreFoundation        0x00007fff9afddb14 __CFRunLoopServiceMachPort + 212
3   com.apple.CoreFoundation        0x00007fff9afdcfdb __CFRunLoopRun + 1371
4   com.apple.CoreFoundation        0x00007fff9afdc838 CFRunLoopRunSpecific + 296
5   com.apple.Foundation            0x00007fff8ed1bab9 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 278
6   com.apple.DTDeviceKitBase       0x000000011a36b1d2 -[DTDKRemoteDeviceDataListener listenerThreadImplementation] + 676
7   com.apple.Foundation            0x00007fff8ed19b7a __NSThread__main__ + 1345
8   libsystem_pthread.dylib         0x00007fff93f812fc _pthread_body + 131
9   libsystem_pthread.dylib         0x00007fff93f81279 _pthread_start + 176
10  libsystem_pthread.dylib         0x00007fff93f7f4b1 thread_start + 13

Thread 5:
0   libsystem_kernel.dylib          0x00007fff916b752e mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff916b669f mach_msg + 55
2   com.apple.CoreFoundation        0x00007fff9afddb14 __CFRunLoopServiceMachPort + 212
3   com.apple.CoreFoundation        0x00007fff9afdcfdb __CFRunLoopRun + 1371
4   com.apple.CoreFoundation        0x00007fff9afdc838 CFRunLoopRunSpecific + 296
5   com.apple.AppKit                0x00007fff997067a7 _NSEventThread + 137
6   libsystem_pthread.dylib         0x00007fff93f812fc _pthread_body + 131
7   libsystem_pthread.dylib         0x00007fff93f81279 _pthread_start + 176
8   libsystem_pthread.dylib         0x00007fff93f7f4b1 thread_start + 13

Thread 6:: DYMobileDeviceManager
0   libsystem_kernel.dylib          0x00007fff916b752e mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff916b669f mach_msg + 55
2   com.apple.CoreFoundation        0x00007fff9afddb14 __CFRunLoopServiceMachPort + 212
3   com.apple.CoreFoundation        0x00007fff9afdcfdb __CFRunLoopRun + 1371
4   com.apple.CoreFoundation        0x00007fff9afdc838 CFRunLoopRunSpecific + 296
5   com.apple.Foundation            0x00007fff8ed1bab9 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 278
6   com.apple.Foundation            0x00007fff8ee1745f -[NSRunLoop(NSRunLoop) run] + 74
7   com.apple.GPUToolsMobileFoundation  0x000000011bf6e9eb -[DYMobileDeviceManager _deviceNotificationThread:] + 134
8   com.apple.Foundation            0x00007fff8ed19b7a __NSThread__main__ + 1345
9   libsystem_pthread.dylib         0x00007fff93f812fc _pthread_body + 131
10  libsystem_pthread.dylib         0x00007fff93f81279 _pthread_start + 176
11  libsystem_pthread.dylib         0x00007fff93f7f4b1 thread_start + 13

Thread 7:
0   libsystem_kernel.dylib          0x00007fff916bc132 __psynch_cvwait + 10
1   com.apple.Xcode.DevToolsCore    0x00000001160daebe -[XCBlockQueue _processBlocksInThreadSlotNumber:] + 519
2   com.apple.Foundation            0x00007fff8ed19b7a __NSThread__main__ + 1345
3   libsystem_pthread.dylib         0x00007fff93f812fc _pthread_body + 131
4   libsystem_pthread.dylib         0x00007fff93f81279 _pthread_start + 176
5   libsystem_pthread.dylib         0x00007fff93f7f4b1 thread_start + 13

Thread 8:
0   libsystem_kernel.dylib          0x00007fff916bc132 __psynch_cvwait + 10
1   com.apple.Xcode.DevToolsCore    0x00000001160daebe -[XCBlockQueue _processBlocksInThreadSlotNumber:] + 519
2   com.apple.Foundation            0x00007fff8ed19b7a __NSThread__main__ + 1345
3   libsystem_pthread.dylib         0x00007fff93f812fc _pthread_body + 131
4   libsystem_pthread.dylib         0x00007fff93f81279 _pthread_start + 176
5   libsystem_pthread.dylib         0x00007fff93f7f4b1 thread_start + 13

Thread 9:
0   libsystem_kernel.dylib          0x00007fff916bc132 __psynch_cvwait + 10
1   com.apple.Xcode.DevToolsCore    0x00000001160daebe -[XCBlockQueue _processBlocksInThreadSlotNumber:] + 519
2   com.apple.Foundation            0x00007fff8ed19b7a __NSThread__main__ + 1345
3   libsystem_pthread.dylib         0x00007fff93f812fc _pthread_body + 131
4   libsystem_pthread.dylib         0x00007fff93f81279 _pthread_start + 176
5   libsystem_pthread.dylib         0x00007fff93f7f4b1 thread_start + 13

Thread 10:
0   libsystem_kernel.dylib          0x00007fff916b752e mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff916b669f mach_msg + 55
2   com.apple.CoreFoundation        0x00007fff9afddb14 __CFRunLoopServiceMachPort + 212
3   com.apple.CoreFoundation        0x00007fff9afdcfdb __CFRunLoopRun + 1371
4   com.apple.CoreFoundation        0x00007fff9afdc838 CFRunLoopRunSpecific + 296
5   com.apple.CoreFoundation        0x00007fff9b092ed1 CFRunLoopRun + 97
6   com.apple.DebugSymbols          0x00007fff8d54fb8f SpotlightQueryThread(void*) + 463
7   libsystem_pthread.dylib         0x00007fff93f812fc _pthread_body + 131
8   libsystem_pthread.dylib         0x00007fff93f81279 _pthread_start + 176
9   libsystem_pthread.dylib         0x00007fff93f7f4b1 thread_start + 13

Thread 11:: Dispatch queue: parsing queue
0   libsystem_kernel.dylib          0x00007fff916b756a semaphore_wait_trap + 10
1   libdispatch.dylib               0x00007fff9bd1fc55 _dispatch_semaphore_wait_slow + 213
2   com.apple.dt.instruments.DTXConnectionServices  0x000000010dbe5fda -[DTXMessageParser waitForMoreData:incrementalBuffer:] + 87
3   com.apple.dt.instruments.DTXConnectionServices  0x000000010dbe5c08 -[DTXMessageParser parseMessage] + 50
4   com.apple.dt.instruments.DTXConnectionServices  0x000000010dbe59c6 __43-[DTXMessageParser initWithMessageHandler:]_block_invoke + 35
5   libdispatch.dylib               0x00007fff9bd1d323 _dispatch_call_block_and_release + 12
6   libdispatch.dylib               0x00007fff9bd18c13 _dispatch_client_callout + 8
7   libdispatch.dylib               0x00007fff9bd1c365 _dispatch_queue_drain + 1100
8   libdispatch.dylib               0x00007fff9bd1decc _dispatch_queue_invoke + 202
9   libdispatch.dylib               0x00007fff9bd1b6b7 _dispatch_root_queue_drain + 463
10  libdispatch.dylib               0x00007fff9bd29fe4 _dispatch_worker_thread3 + 91
11  libsystem_pthread.dylib         0x00007fff93f816cb _pthread_wqthread + 729
12  libsystem_pthread.dylib         0x00007fff93f7f4a1 start_wqthread + 13

Thread 12:
0   libsystem_kernel.dylib          0x00007fff916bc946 __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff93f7f4a1 start_wqthread + 13

Thread 13:
0   libsystem_kernel.dylib          0x00007fff916bc946 __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff93f7f4a1 start_wqthread + 13

Thread 14:
0   libsystem_kernel.dylib          0x00007fff916bc946 __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff93f7f4a1 start_wqthread + 13

Thread 15:
0   libsystem_kernel.dylib          0x00007fff916bc946 __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff93f7f4a1 start_wqthread + 13

Thread 16:: lldb.debugger.io-handler
0   libsystem_kernel.dylib          0x00007fff916bc306 __read_nocancel + 10
1   libsystem_c.dylib               0x00007fff9c237f6b __srefill1 + 24
2   libsystem_c.dylib               0x00007fff9c2317fb fgets + 104
3   com.apple.LLDB.framework        0x000000011408928d lldb_private::IOHandlerEditline::GetLine(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, bool&) + 341
4   com.apple.LLDB.framework        0x0000000114089718 lldb_private::IOHandlerEditline::Run() + 176
5   com.apple.LLDB.framework        0x0000000113fabee0 lldb_private::Debugger::ExecuteIOHanders() + 86
6   com.apple.LLDB.framework        0x0000000113fb2f4a lldb_private::Debugger::IOHandlerThread(void*) + 14
7   libsystem_pthread.dylib         0x00007fff93f812fc _pthread_body + 131
8   libsystem_pthread.dylib         0x00007fff93f81279 _pthread_start + 176
9   libsystem_pthread.dylib         0x00007fff93f7f4b1 thread_start + 13

Thread 17:: <lldb.process.gdb-remote.async>
0   libsystem_kernel.dylib          0x00007fff916bc132 __psynch_cvwait + 10
1   com.apple.LLDB.framework        0x0000000114055325 lldb_private::Condition::Wait(lldb_private::Mutex&, lldb_private::TimeValue const*, bool*) + 109
2   com.apple.LLDB.framework        0x00000001140b8332 lldb_private::Predicate<bool>::WaitForValueEqualTo(bool, lldb_private::TimeValue const*, bool*) + 90
3   com.apple.LLDB.framework        0x0000000113fbd2ee lldb_private::Listener::WaitForEventsInternal(lldb_private::TimeValue const*, lldb_private::Broadcaster*, lldb_private::ConstString const*, unsigned int, unsigned int, std::__1::shared_ptr<lldb_private::Event>&) + 324
4   com.apple.LLDB.framework        0x0000000113fbd405 lldb_private::Listener::WaitForEvent(lldb_private::TimeValue const*, std::__1::shared_ptr<lldb_private::Event>&) + 27
5   com.apple.LLDB.framework        0x00000001140c2d9a ProcessGDBRemote::AsyncThread(void*) + 1228
6   libsystem_pthread.dylib         0x00007fff93f812fc _pthread_body + 131
7   libsystem_pthread.dylib         0x00007fff93f81279 _pthread_start + 176
8   libsystem_pthread.dylib         0x00007fff93f7f4b1 thread_start + 13

Thread 18:: <lldb.process.internal-state(pid=2045)>
0   libsystem_kernel.dylib          0x00007fff916bc132 __psynch_cvwait + 10
1   com.apple.LLDB.framework        0x0000000114055325 lldb_private::Condition::Wait(lldb_private::Mutex&, lldb_private::TimeValue const*, bool*) + 109
2   com.apple.LLDB.framework        0x00000001140b8332 lldb_private::Predicate<bool>::WaitForValueEqualTo(bool, lldb_private::TimeValue const*, bool*) + 90
3   com.apple.LLDB.framework        0x0000000113fbd2ee lldb_private::Listener::WaitForEventsInternal(lldb_private::TimeValue const*, lldb_private::Broadcaster*, lldb_private::ConstString const*, unsigned int, unsigned int, std::__1::shared_ptr<lldb_private::Event>&) + 324
4   com.apple.LLDB.framework        0x0000000113fbd405 lldb_private::Listener::WaitForEvent(lldb_private::TimeValue const*, std::__1::shared_ptr<lldb_private::Event>&) + 27
5   com.apple.LLDB.framework        0x000000011416b7bc lldb_private::Process::WaitForEventsPrivate(lldb_private::TimeValue const*, std::__1::shared_ptr<lldb_private::Event>&, bool) + 114
6   com.apple.LLDB.framework        0x0000000114171ffe lldb_private::Process::RunPrivateStateThread() + 226
7   com.apple.LLDB.framework        0x0000000114171b21 lldb_private::Process::PrivateStateThread(void*) + 9
8   libsystem_pthread.dylib         0x00007fff93f812fc _pthread_body + 131
9   libsystem_pthread.dylib         0x00007fff93f81279 _pthread_start + 176
10  libsystem_pthread.dylib         0x00007fff93f7f4b1 thread_start + 13

Thread 19 Crashed:: <DBGLLDBSessionThread (pid=2045)>
0   com.apple.LLDB.framework        0x0000000113fbc046 lldb_private::FileSpecList::GetSize() const + 4
1   com.apple.LLDB.framework        0x000000011413cc58 lldb_private::CompileUnit::GetSupportFiles() + 36
2   com.apple.LLDB.framework        0x00000001140ebb4b SymbolFileDWARF::GetLoadedModules(lldb::LanguageType, lldb_private::FileSpecList&) + 127
3   com.apple.LLDB.framework        0x0000000113fe8b2a lldb_private::Module::GetSwiftASTContext() + 1464
4   com.apple.LLDB.framework        0x00000001140e10b8 SymbolFileDWARF::GetSwiftASTContext() + 66
5   com.apple.LLDB.framework        0x00000001140ec5d9 SymbolFileDWARF::ParseType(lldb_private::SymbolContext const&, DWARFCompileUnit*, DWARFDebugInfoEntry const*, bool*) + 137
6   com.apple.LLDB.framework        0x00000001140e7dd4 SymbolFileDWARF::GetTypeForDIE(DWARFCompileUnit*, DWARFDebugInfoEntry const*) + 188
7   com.apple.LLDB.framework        0x00000001140e7c61 SymbolFileDWARF::ResolveType(DWARFCompileUnit*, DWARFDebugInfoEntry const*, bool) + 99
8   com.apple.LLDB.framework        0x00000001140dfcfa SymbolFileDWARF::ResolveTypeUID(DWARFCompileUnit*, DWARFDebugInfoEntry const*, bool) + 330
9   com.apple.LLDB.framework        0x00000001140e5d00 SymbolFileDWARF::ResolveTypeUID(unsigned long long) + 96
10  com.apple.LLDB.framework        0x0000000114154736 lldb_private::SymbolFileType::GetType() + 36
11  com.apple.LLDB.framework        0x000000011401bb0d lldb_private::ValueObjectVariable::GetClangTypeImpl() + 21
12  com.apple.LLDB.framework        0x000000011400df4d lldb_private::ValueObject::MaybeCalculateCompleteType() + 37
13  com.apple.LLDB.framework        0x0000000114011ddb lldb_private::ValueObject::GetObjectRuntimeLanguage() + 31
14  com.apple.LLDB.framework        0x000000011416d474 lldb_private::Process::IsPossibleDynamicValue(lldb_private::ValueObject&) + 68
15  com.apple.LLDB.framework        0x0000000114013204 lldb_private::ValueObject::CalculateDynamicValue(lldb::DynamicValueType) + 90
16  com.apple.LLDB.framework        0x00000001140132ab lldb_private::ValueObject::GetDynamicValue(lldb::DynamicValueType) + 65
17  com.apple.LLDB.framework        0x000000011284984a ValueImpl::GetSP(lldb_private::ProcessRunLock::ProcessRunLocker&, lldb_private::Mutex::Locker&, lldb_private::Error&) + 276
18  com.apple.LLDB.framework        0x0000000112843caa lldb::SBValue::GetSP(ValueLocker&) const + 58
19  com.apple.LLDB.framework        0x0000000112843da1 lldb::SBValue::GetName() + 41
20  com.apple.dt.dbg.DebuggerLLDB   0x00000001127a992a -[DBGLLDBDataValue initWithLLDBValueObject:forStackFrame:withParent:updateSummary:] + 247
21  com.apple.dt.dbg.DebuggerLLDB   0x00000001127a97cc -[DBGLLDBDataValue initWithLLDBValueObject:forStackFrame:withParent:] + 92
22  com.apple.dt.dbg.DebuggerLLDB   0x00000001127a6e75 ConvertValueListToDBGDataValueArray(lldb::SBValueList const&, unsigned int, DBGLLDBStackFrame*, NSArray*) + 305
23  com.apple.dt.dbg.DebuggerLLDB   0x00000001127a6d05 -[DBGLLDBStackFrame _getAllFrameVariablesOnLLDBSessionThread] + 144
24  com.apple.dt.dbg.DebuggerLLDB   0x00000001127a8445 -[DBGLLDBStackFrame _getLocalsFromLLDBOnSessionThread] + 48
25  com.apple.dt.dbg.DebuggerLLDB   0x00000001127bc0ad -[DBGLLDBSession handleNextActionWithState:withRunPending:] + 424
26  com.apple.dt.dbg.DebuggerLLDB   0x00000001127b6e89 DBGLLDBSessionThread(void*) + 1052
27  libsystem_pthread.dylib         0x00007fff93f812fc _pthread_body + 131
28  libsystem_pthread.dylib         0x00007fff93f81279 _pthread_start + 176
29  libsystem_pthread.dylib         0x00007fff93f7f4b1 thread_start + 13

Thread 20:
0   libsystem_kernel.dylib          0x00007fff916bc946 __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff93f7f4a1 start_wqthread + 13

Thread 21:
0   libsystem_kernel.dylib          0x00007fff916bc946 __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff93f7f4a1 start_wqthread + 13

Thread 22:
0   libsystem_kernel.dylib          0x00007fff916bc946 __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff93f7f4a1 start_wqthread + 13

Thread 23:
0   libsystem_kernel.dylib          0x00007fff916bc946 __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x00007fff93f7f4a1 start_wqthread + 13

Thread 19 crashed with X86 Thread State (64-bit):
  rax: 0x0000000154728218  rbx: 0x0000000000000000  rcx: 0x0000000154728164  rdx: 0x0000000000000000
  rdi: 0x0000000000000088  rsi: 0x0000000000000001  rbp: 0x0000000154728120  rsp: 0x0000000154728120
   r8: 0x0000000154728160   r9: 0x000000015472a000  r10: 0x0000000000000050  r11: 0x00007fcd20500000
  r12: 0x00007fcd20927c58  r13: 0x0000000000000002  r14: 0x0000000000000088  r15: 0x0000000000000053
  rip: 0x0000000113fbc046  rfl: 0x0000000000000206  cr2: 0x0000000000000090

Logical CPU:     0
Error Code:      0x020000b8
Trap Number:     133

Binary Images:
{I can post it if needed but have to remove some part to don't exceed characters limit}

External Modification Summary:
  Calls made by other processes targeting this process:
    task_for_pid: 9
    thread_create: 0
    thread_set_state: 0
  Calls made by this process:
    task_for_pid: 0
    thread_create: 0
    thread_set_state: 0
  Calls made by all processes on this machine:
    task_for_pid: 3008
    thread_create: 2
    thread_set_state: 94

VM Region Summary:
ReadOnly portion of Libraries: Total=403.2M resident=152.2M(38%) swapped_out_or_unallocated=251.0M(62%)
Writable regions: Total=1.7G written=430.1M(25%) resident=504.1M(29%) swapped_out=94.5M(6%) unallocated=1.2G(71%)

REGION TYPE                        VIRTUAL
===========                        =======
Activity Tracing                     2048K
CG backing stores                    7952K
CG image                             41.4M
CG raster data                        604K
CG shared images                      368K
CoreAnimation                        1804K
CoreData Object IDs                  4100K
CoreImage                               8K
CoreUI image data                     348K
Dispatch continuations               8192K
Foundation                           3584K
Image IO                             1392K
JS JIT generated code                   8K
JS JIT generated code (reserved)      1.0G        reserved VM address space (unallocated)
Kernel Alloc Once                       8K
MALLOC                              540.8M
MALLOC (admin)                         32K
Memory Tag 242                         12K
Memory Tag 249                        156K
Memory Tag 251                          8K
OpenCL                                 40K
SQLite page cache                    22.2M
STACK GUARD                          56.1M
Stack                                19.3M
VM_ALLOCATE                          19.5M
WebKit Malloc                         464K
__DATA                               44.4M
__IMAGE                               528K
__LINKEDIT                          103.9M
__TEXT                              299.3M
__UNICODE                             544K
mapped file                         609.7M
shared memory                           4K
===========                        =======
TOTAL                                 2.7G
TOTAL, minus reserved VM space        1.7G

Model: Macmini5,1, BootROM MM51.0077.B0F, 2 processors, Intel Core i5, 2.3 GHz, 8 GB, SMC 1.76f0
Graphics: Intel HD Graphics 3000, Intel HD Graphics 3000, Built-In, 512 MB
Memory Module: BANK 0/DIMM0, 4 GB, DDR3, 1333 MHz, 0x029E, 0x434D534F344758334D314131333333433920
Memory Module: BANK 1/DIMM0, 4 GB, DDR3, 1333 MHz, 0x029E, 0x434D534F344758334D314131333333433920
AirPort: spairport_wireless_card_type_airport_extreme (0x14E4, 0xE4), Broadcom BCM43xx 1.0 (5.106.98.100.24)
Bluetooth: Version 4.3.1f2 15015, 3 services, 27 devices, 1 incoming serial ports
Network Service: Ethernet, Ethernet, en0
Serial ATA Device: TOSHIBA MK5065GSXF, 500,11 GB
USB Device: Hub
USB Device: Keyboard Hub
USB Device: Apple Keyboard
USB Device: BRCM20702 Hub
USB Device: Bluetooth USB Host Controller
USB Device: Hub
USB Device: IR Receiver
Thunderbolt Bus: Mac mini, Apple Inc., 25.1


text:
Q: Concat variable inside string in powershell I am trying to concat variable in the string.
Code :
$uniqueID = "123"
$Key = '<add key="uniqueID" value="$uniqueID" />'
write-host $Key

Result i want :
<add key="uniqueID" value="123" />

Result i am getting :
<add key="uniqueID" value="$uniqueID" />

A: Try this -
$Key = "<add key=`"uniqueID`" value=`"$($uniqueID)`" />"

OR
$Key = "<add key=`"uniqueID`" value=`"$uniqueID`" />"

To force Windows PowerShell to interpret a double quotation mark
literally, use a backtick character. This prevents Windows PowerShell
from interpreting the quotation mark as a string delimiter.
INFO -
If you look at Get-Help about_Quoting_Rules, it says,
SINGLE AND DOUBLE-QUOTED STRINGS
   When you enclose a string in double quotation marks (a double-quoted
   string), variable names that are preceded by a dollar sign ($) are
   replaced with the variable's value before the string is passed to the
   command for processing.

   For example:

       $i = 5
       "The value of $i is $i."

   The output of this command is:
       The value of 5 is 5.

   Also, in a double-quoted string, expressions are evaluated, and the
   result is inserted in the string. For example:

       "The value of $(2+3) is 5."

   The output of this command is:

       The value of 5 is 5.

   When you enclose a string in single-quotation marks (a single-quoted
   string), the string is passed to the command exactly as you type it.
   No substitution is performed. For example:

       $i = 5
       'The value of $i is $i.'

   The output of this command is:

       The value $i is $i.

   Similarly, expressions in single-quoted strings are not evaluated. They
   are interpreted as literals. For example:

       'The value of $(2+3) is 5.'

   The output of this command is:

       The value of $(2+3) is 5.

The reason your code wasn't evaluating the value was because you were using a single quote to wrap the variable $key. Wrapping it with double quote and using a sub-expression operator ($($UniqueID) along with backtick does the trick, or simply using the $UniqueID will also suffice.

A: I find using the '-f' formatting option works great for this kind of request.  Try:
$uniqueID = "123"
$Key = ('<add key="{0}" value="{1}" />' -f 'uniqueID', $uniqueID)
write-host $Key


text:
Q: SQL Query: Current and Previous month values in two columns Need a SQL Query to have Previous month values against to the monthly values.
Constraint: DO NOT USE ANY LAG, OVER, PARTITION, Row_number() etc. Use only LEFT, RIGHT or INNER Joins and achieve it.
I have a table as follows

LoanID1 Jan   2000
LoanID1 Feb   3000
LoanID1 March 2500
LoanID1 April 1000
LoanID1 May   500
LoanID2 Jan   750
LoanID2 FEB   3500
LoanID2 March 2700
LoanID2 April 1500
LoanID2 May   4000

Basically, These are Monthly values for each LoanID, what i need is i need to have another column with the Previous month values like the following table:
LoanID1 Jan   2000
LoanID1 Feb   3000   2000
LoanID1 March 2500   3000
LoanID1 April 1000   2500
LoanID1 May   500    1000
LoanID2 Jan   750
LoanID2 FEB   3500   750
LoanID2 March 2700   3500
LoanID2 April 1500   2700
LoanID2 May   4000   1500

I tried with Joining the same table but could not achieve it. Please guide me and throw me some light how can i make it.
Update to provide actual details:
Illustration images: the actual data how it is available and how i need it in the 2nd image
[This is the actual database with the records looks like

This is what i need with another column(Previous Month Values)

Appreciate your guidance and thanks in advance.

A: Depending on RDBMS you are using, you need to add a "row number" column ordered by date, based on which you would perform join.
It will look like this
select
t1.month,
t1.value as curr_mon_val,
t2.value as prev_mon_val
from
(select t1.month, t1.value, row_number from t1) as t1
join (select t1.value, row_number from t1 where row_number > 1) as t2
on t1.row_number = t2.row_number-1

this is approximation to what you need to write depending on your RDBMS

A: You can do it by using LAG function
    declare @myt table (id nvarchar(50),monthnames nvarchar(50),amount int)

insert into @myt

values

('LoanID1','Jan', 2000       ),
('LoanID1','Feb', 3000       ),
('LoanID1','March',   2500   ),
('LoanID1','April',   1000   ),
('LoanID1','May', 500        ),
('LoanID2','Jan', 750        ),
('LoanID2','Feb', 3500       ),
('LoanID2','March',   2700   ),
('LoanID2','April',   1500   ),
('LoanID2','May', 4000       )

select *,LAG(Amount,1,0) Over(partition by ID order by id,MonthNumber) as PreviousMonth  from (
select *,Month(cast(monthnames+'1 2018' as date)) as MonthNumber from @myt
)x


text:
Q: Copying over NTFS ACL's from one offline server to another server We have two machines on the same domain: Machine A (Windows 2003) and Machine B (Windows 2003). Both have a set of files that are identical and have been kept identical by a scheduled process. However, the Machine A is now offline (i.e., not on the network but I still have physical access to the machine) and we realize that the ACL's were not identical.
What would be the most elegant way to copy over the ACL's with Machine A being offline?

A: Assuming that your dataset is identical on both machines, except for the ACL, you could do:
icacls c:\path\to\data\* /save ACLData /T

Copy the "ACLData" file to the destination machine, and then:
icacls c:\path\to\data /restore ACLData

This will replicate the ACLs (and just the ACLs) assuming the data structure is identical, and you have the rights to do so.

A: Try this:
SET SOURCEFOLDER=\\server\share\folder
SET DESTFOLDER=C:\folder

REM copy all security ACLs
ROBOCOPY "%SOURCEFOLDER%" "%DESTFOLDER%" /IS /E /COPY:S /NDL /TEE /LOG+:C:\temp\robocopy.log

/IS - include "same" files
/E - copy subdirectories, including Empty ones.
/COPY:S - copy NTFS acls
/TEE - output to screen and log file
/NDL - don't include directory name in log
/LOG+: append to log file
You may need to use quotes if the folders have spaces in the names.

A: If I'm understanding your question correctly xcopy with /o could do this for you.


text:
Q: request timed out error while creating User profile service application after long time in order to configure my sites in sharepoint 2013, we need to start user profile synchronization service. while starting that service it should populate user profile application. for me it is not populating. so im trying to create user profile service application,then im getting this request timed out error.

A: Let's do it step by step:

*

*Make sure that Farm Administrator account must be a Local
Administrator on the server where the User Profile Synchronization
Service will be provisioned.

*Navigate to Central
Administration >> Application Management >> Manage Service Manage
Application>> Click on New >> Select

*

*Enter Name, Application Pool Name and account

*

*Now enter the name of other databases like Social, profile etc. I will leave it by default

*

*Now start the User profile service by going into Central Admin >>
System Service>> Manage Services on the server

*Now start User Profile Synchronization Service by giving the Farm admin credentials

*

*Make sure that ForeFront Identity Manager Services (FIM) are correctly configured and started

*Perform an IISReset and go get a coffee cup :)

*Now, set up the sync connection by going to Manage Service Application > User Profile Service > Configure Synchronization Connection > Create new Connection (Note sync account in this case, dev_spadaccount must be granted the Create Child Objects (permissions) on the OU you are Syncing with.

*Populate the containers and select the required AD's Organization
Unit to be Synced. Click on and Start the Full Import.

*Remove the Farm account from local admins on the box running FIM

Happy SharePointing!


text:
Q: Prove that $\left\{\frac{x_{n}-y_{n}}{x_{n}+y_{n}}\right\}_{n\in\Bbb N}$ converges, given that ... Prove that $\left\{\frac{x_{n}-y_{n}}{x_{n}+y_{n}}\right\}_{n\in\Bbb N}$ converges, given that $\{x_{n}\}_{n\in\Bbb N}$, $\{y_{n}\}_{n\in\Bbb N}$ are sequences that are increasing in $\Bbb R^+$ so that $\{x_{n}-y_{n}\}_{n\in\Bbb N}$ is bounded.
I apologize in advance because I'm an absolute beginner in this kind of website. If you can do this, I would be eternally grateful.

A: *

*If $\lim_{n\to\infty}x_n=+\infty$ then because of boundedness $\{x_n-y_n\}$ the limit is equal to 0.

*Let both sequences are bounded. Because they are increasing, they are convergent to, say, $x$ and $y$ respectively. Hence $x_n+y_n$ tends to $x+y$ and $x_n-y_n$ to $x-y$, which ends the proof.


text:
Q: Save file info that already uploaded with Meteor files I am using https://github.com/VeliovGroup/Meteor-Files, This package provide a collection of uploaded files via Meteor-Files.
How can I insert a document about the file that is already uploaded and not via Meteor-Files? I want to use Meteor-Files to save file info only not uploading. Because I need to get a generated download link for the file. This is provided by Meteor-Files.
Anyone can help me guide how to solve this problem?

A: I used addFile() function provided by FilesCollection class.


text:
Q: Cannot find place to insert finally block to get rid of the error: Insert Finally to complete TryStatement I've tried several spots to insert the finally block but no matter what I try it ends up making the code worse.
Here is my code, the 4th to last ending curly bracket is the one giving me the error.  Any thoughts?

    package com.tunestore.action;

    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.PreparedStatement;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;

    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.ActionMessage;
    import org.apache.struts.action.ActionMessages;
    import org.apache.struts.action.DynaActionForm;

    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import org.owasp.validator.html.*;
    import org.owasp.esapi.*;

    public class DownloadAction extends Action
    {
      private static final Log log = LogFactory.getLog(DownloadAction.class);

      public static String DB_URL;

        static
        {
                if (System.getProperty("tunestore.db.location") != null)
                {
                    DB_URL = "jdbc:derby://localhost:1527/" + System.getProperty("tunestore.db.location");
                }
                else
                {
                    DB_URL = "jdbc:derby://localhost:1527/" + System.getProperty("user.home") + "/.tunestore";
                }
                System.setProperty("jdbc.tunestore.url", DB_URL);
        }

        public static Connection getConnection() throws Exception
        {
            log.info("Opening database at " + DB_URL);
            Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
            Connection conn = DriverManager.getConnection(DB_URL);
            return conn;
        }

        public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
        throws Exception
        {
            DynaActionForm daf = (DynaActionForm)form;
            String user = (String)request.getSession(true).getAttribute("USERNAME");
            if(user != null)
            {
                Connection conn = null;
                try
                {
                    conn = DownloadAction.getConnection();
                    String sql2 = "SELECT ID FROM CD WHERE CD.BITS = ?";
                    PreparedStatement stmt2 = conn.prepareStatement(sql2);
                    stmt2.setString(1, request.getParameter("cd"));
                    ResultSet rs2 = stmt2.executeQuery();
                    rs2.next();

                    String sql = "SELECT COUNT(*) "
                    + "FROM TUNEUSER_CD "
                    + "WHERE TUNEUSER_CD.TUNEUSER = ? AND TUNEUSER_CD.CD = ?";
                    PreparedStatement stmt = conn.prepareStatement(sql);
                    stmt.setString(1, user);
                    stmt.setInt(2, rs2.getInt(1));
                    ResultSet rs = stmt.executeQuery();
                    rs.next();
                    int owned = rs.getInt(1);

                    if(owned == 1)
                    {
                        try
                        {
                            // Try to open the stream first - if there's a goof, it'll be here
                            InputStream is = this.getServlet().getServletContext().getResourceAsStream("/WEB-INF/bits/" + request.getParameter("cd"));

                            if (is != null)
                            {
                                response.setContentType("audio/mpeg");
                                response.setHeader("Content-disposition", "attachment; filename=" + daf.getString("cd"));
                                byte[] buff = new byte[4096];
                                int bread = 0;
                                while ((bread = is.read(buff)) >= 0)
                                {
                                    response.getOutputStream().write(buff, 0, bread);
                                }
                            }
                            else
                            {
                                ActionMessages errors = getErrors(request);
                                errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("download.error"));
                                saveErrors(request, errors);
                                return mapping.findForward("error");
                            }
                        }

                        catch (Exception e)
                        {
                            e.printStackTrace();
                            ActionMessages errors = getErrors(request);
                            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("download.error"));
                            saveErrors(request, errors);
                            return mapping.findForward("error");
                        }

                        return null;

                    }
                }
            }
        }
    }

A: That bracket is the location where your outer try block ends. It has no catch block and no finally block, so you get an error. Just add one or the other immediately after the bracket, or remove the try if it's not needed.

A: You only have one catch block, but two trys. Add a catch block for the first try-catch and you should have your issue solved.
Edit: Why are you nesting try-catch in the first place? I don't believe there is any need to do so.


text:
Q: why can't I use in a search query The username in the aspnet_users table is BlackR\johnBurns
I'm trying to write a query to get this record where username = but it is flagging
string username1 = @"BlackR\" + johnBurns;
var s = DbContext.ExecuteStoreQuery<string>("Select UserId FROM aspnet_Users where UserName = " + username1);

this fails saying Additional information: Incorrect syntax near '\'.
Does the @ not cancel this out? Is it because of its a SQL query?

A: Assume variable johnBurns store value johnBurns, then your code is similar to this:
string username1 = "BlackR\\johnBurns";
var s = DbContext.ExecuteStoreQuery<string>("Select UserId FROM aspnet_Users where UserName = BlackR\johnBurns");

The first line, @ will lets you specify a string without having to escape any characters (see this post)
The second line, compiler will try to find the escape character.  In this example, it will looking to \j, which is not a valid escape character.
You may find the escape character list here: MSDN
And finally, you may need to add the single quotes for string parameter of SQL, and better to use parameterized query as Tetsuya Yamamoto suggested.
With parameterized query, you don't need to escape the special character, system will help you do that.


text:
Q: What kind of dev do I need? (cross platform mobile app + Google Cloud Vision API) I am writing a job offer to find a dev. The goal is to code the following iOS app:

*

*Enables users to take a picture of a list

*Extracts the text in this picture

*Compares the extracted items with items on a pre-populated spreadsheet

*If some extracted items are found in the list, strikes those items out on the picture

I am pretty sure that I need someone experienced with Swift. Although, if the app could be cross-platform, it would be even better.
What skills do I need to expect from this dev?

A: Google Cloud Vision Api is very simple to implement. I am a student with around 3 years experience and I did not have much problems implementing it on Android for a simple application.
Anyone that can manipulate the basics of the language should be able to implement it.
However, I do not know any swift developer. I do not know anything about swift development. All I can tell is that it is possible.
I would recommend 2-4 student developers. Give them 6 months minimum. Students are familiar with modern tools and won't fear learning a new language such as swift.


text:
Q: Embedding SQL Server Compact 3.5 in the application I am confused about embedding the sql server compact 3.5 files in my application.
I have included 7 files in the setup but application fails to run on some computers.
Is there some version problem?
I wish to embed both (32 & 64 bit) as I do not know the target platform.
How to do this?
Thanks

A: Your best bet is to build for x86 and only include the x86 dll files in the project folder.
If you are using raw ADO.NET, you may be able to make Any CPU Work, if you follow the many steps in my blog post here, but I do not recommend this: http://erikej.blogspot.dk/2012/05/private-deployment-of-sql-server.html


text:
Q: Weblogic and Hibernate 3.6.5, migrating DB layer from Oracle 10g to 11g, pitfalls, gotachas and experiences? We currently have a large enterprise java-based codebase consisting of numerous legacy and new projects running within Weblogic using frameworks such as struts 1, spring MVC, etc.
We use hibernate 3.6.5 as our ORM.
Our IT is upgrading the database layer from Oracle 10g to 11g. They are looking after all db and pl/sql related issue relating to that.
From the code/java/weblogic/hibernate point of view, is there anything we should be specially aware of? Hibernate 3.6.5 supports Oracle 11g and the same dialect is used, so technically speaking there should be no difference whatsoever from client side.
Am I missing something? If you had experience with a similar migration could you please share any gotchas and pitfalls you may have stumbled upon so that we can look for that.
Thanks!

A: I believe you have to specifically set the Oracle dialect to 10g, because Hibernate 3.6.x does not autodetect Oracle 11g. If your application fully relies on the SQL statements generated by Hibernate, you should be fine.
If you use some explicit Oracle SQL statements, you might need to doublechek if they still work - 11gR2 tightened up SQL syntax checks comparing to 10g. Also, if you have explicit SQL and have some hints in it, you might as well delete hints and do perfromance testing all over again - chances are you will need different hints in different places than before. Good luck!


text:
Q: How do I set an individual path variable for each user within the database? Basically I want the users to upload files into their own individual folders within the server and then store the url/name of the file/folder into the database. I have already managed to upload files into one folder overall so what I need is to separate folders and locations according to the user

A: To create a folder you can use the following code and store the same $structure ein the database
 <?php
    // Desired folder structure
    $structure = './depth1/$username';

    // To create the nested structure, the $recursive parameter
    // to mkdir() must be specified.

    if (!mkdir($structure, 0777, true)) {
        die('Failed to create folders...');
    }

    // ...
    ?>


text:
Q: NUnit addin - do I have to include addin implementations in each test projects? I've found a useful post recently in here: NUnit extension
However my question is still not answered.
First of all, what is a 'test assembly' anyway?
Second, could someone give me a more detailed explanation of 'NUnit searches each test assembly for addins to be loaded'?
For example, I have two projects in my VS2010 solution, say, project A and project B. A is a test project(contains '[Test]' inside), B is an NUnit addin project(contains addin installer, EventListener interface implementations, etc. inside), and, A references B. Does this work? Will the addin be called?
If not, I assume it means that I must have the various .cs files(which implements the NUnit addin) directly included in project A, rather than have them placed into a separate project and reference it in test project. Is that what you mean?
If so, another problem raised, that, when I have project C, D, E... which are also test projects, I have to include those various .cs files(which implements the NUnit addin) in each test project?

A: For the Add-In to run, one of two conditions must be satisfied:

*

*The Add-in is a compiled .dll which is placed in the 'AddIns' folder.

*The Add-in code is in the same Assembly as the tests.

There is a way to have the bulk of the Add-in code in a different Assembly, however, and to have a small shim class in your Test Assembly which allows NUnit to find it, for example:
In Addin Assembly
public class CustomEventListener : IAddin, EventListener
{
    public bool Install(IExtensionHost host)
    {
        IExtensionPoint listeners = host.GetExtensionPoint("EventListeners");
        if (listeners == null)
            return false;

        listeners.Install(this);
        return true;
    }

    ........ <Implemented Interfaces> .......

}

In Test Assembly
Add this class anywhere you like:
[NUnitAddin]
public class MyAddin : CustomEventListener { }

NUnit will spot the NUnitAddin attribute and invoke the code in the base CustomerEventListener code, even though it is in a different assembly.

A: This is the answer Charlie provided on google groups. Many thanks to Charlie!
https://groups.google.com/forum/?fromgroups#!topic/nunit-discuss/yTKRKf2APLI
Re: [nunit-discuss] Re: NUnit extension
On Mon, May 21, 2012 at 8:13 AM, Athrun Sun  wrote:

Hi Charlie,
Could you give me a more detailed explanation of 'NUnit searches each test assembly for addins to be loaded'?
For example, I have two projects in my VS2010 solution, say, project A and project B. A is a test project(contains '[Test]' inside), B is an NUnit addin project(contains addin installer, EventListener interface implementations, etc. inside), and, A references B. Does this work? Will the addin be called?

In that situation, no. B is not a test assembly.

If not, I assume you mean that I must have the various .cs files(which implements the NUnit addin) directly included in project A, rather than have them placed into a separate project and reference it in test project. Is that what you mean?

Exactly

If so, another problem raised, that, when I have project C, D, E... which are also test projects, I have to include those various .cs files(which implements the NUnit addin) in each test project?

This feature is provided to allow testing of extensions under
development, so it's not really a problem with needing to use the
extension in multiple assemblies. In fact, if you were to duplicate
the code in two assemblies, I imagine NUnit would try to register two
different addins, with potentially surprising results. :-)
For production use, you should install the addin in the addins folder
in the normal way. In addition, it's best not to reference the addin
assembly from your code. Although this may not always cause a problem,
it sometimes does lead to the addin being loaded twice.
Charlie
- show quoted text -

To view this discussion on the web visit https://groups.google.com/d/msg/nunit-discuss/-/a730uESbNJUJ.
  - show quoted text -


text:
Q: Custom Blinking Insertion Point Is is possible to change the color or any custom features of the blinking insertion point without overwriting private methods (so that there's no issue with deploying to the app store) ?
To be clear, currently it's blinking blue, and I'd like to change it to white for my context, or even black, but not blue.

A: Assuming that you are talking about UITextField or UITextView, change the object's tintColor property to the color you would like your cursor to be.


text:
Q: Issue with initializing global variable in Shaderlab I just realized that a global variable in Unity must be initialized in a function. Being new to shaders, I can't tell if I am doing this the wrong way.
For example, when I define a const variable:
const float PI = 3.14159265359;

then try to write a code that uses in the frag functiion:
fixed4 frag(v2f i) : SV_Target
{
    float result = PI * otherVariable;
    ///Use the result value...
}

It doesn't work. I gets a black screen as the result or the expected result wont show up.
The confusing part is that when I re-initialize the global variable (PI) again in the frag function, I get the expected result.
For example, this is what works:
float PI = 3.14159265359;

then try to write a code that uses in the frag function:
fixed4 frag(v2f i) : SV_Target
{
    //re-initialize
    PI = 3.14159265359;

    float result = PI * otherVariable;
}

I have so many constant global variables that I can't keep re-initiated them.
One complete example of this problem is this Shadertoy code I ported.
Shader "Unlit/Atmospheric Scattering 2"
{
    Properties
    {
        _MainTex("Texture", 2D) = "white" {}
    }
        SubShader
    {
        Tags { "RenderType" = "Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            v2f vert(appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                UNITY_TRANSFER_FOG(o,o.vertex);
                return o;
            }

            ////////////////////////////////////////////////////////////////////////////////////////////////////////
            //https://www.shadertoy.com/view/lslXDr
            // math const
              float PI = 3.14159265359;
              float DEG_TO_RAD = (3.14159265359 / 180.0);
              float MAX = 10000.0;

              // scatter const
               float K_R = 0.166;
               float K_M = 0.0025;
               float E = 14.3;

               float C_R = float3(0.3, 0.7, 1.0);   // 1 / wavelength ^ 4
               float G_M = -0.85;                   // Mie g

               float R = 1.0;
               float R_INNER = 0.7;
               float SCALE_H = 4.0 / (1.0 - 0.7);
               float SCALE_L = 1.0 / (1.0 - 0.7);

               int NUM_OUT_SCATTER = 10;
               float FNUM_OUT_SCATTER = 10.0;

               int NUM_IN_SCATTER = 10;
               float FNUM_IN_SCATTER = 10.0;

               // angle : pitch, yaw
               float3x3 rot3xy(float2 angle) {
                   float2 c = cos(angle);
                   float2 s = sin(angle);

                   return float3x3(
                       c.y, 0.0, -s.y,
                       s.y * s.x, c.x, c.y * s.x,
                       s.y * c.x, -s.x, c.y * c.x
                   );
               }

               // ray direction
               float3 ray_dir(float fov, float2 size, float2 pos) {
                   float2 xy = pos - size * 0.5;

                   float cot_half_fov = tan((90.0 - fov * 0.5) * DEG_TO_RAD);
                   float z = size.y * 0.5 * cot_half_fov;

                   return normalize(float3(xy, -z));
               }

               // ray intersects sphere
               // e = -b +/- sqrt( b^2 - c )
               float2 ray_vs_sphere(float3 p, float3 dir, float r) {
                   float b = dot(p, dir);
                   float c = dot(p, p) - r * r;

                   float d = b * b - c;
                   if (d < 0.0) {
                       return float2(MAX, -MAX);
                   }
                   d = sqrt(d);

                   return float2(-b - d, -b + d);
               }

               // Mie
               // g : ( -0.75, -0.999 )
               //      3 * ( 1 - g^2 )               1 + c^2
               // F = ----------------- * -------------------------------
               //      2 * ( 2 + g^2 )     ( 1 + g^2 - 2 * g * c )^(3/2)
               float phase_mie(float g, float c, float cc) {
                   float gg = g * g;

                   float a = (1.0 - gg) * (1.0 + cc);

                   float b = 1.0 + gg - 2.0 * g * c;
                   b *= sqrt(b);
                   b *= 2.0 + gg;

                   //b = mul(b,sqrt(b));
                   //b = mul(b,2.0 + gg);

                   return 1.5 * a / b;
               }

               // Reyleigh
               // g : 0
               // F = 3/4 * ( 1 + c^2 )
               float phase_reyleigh(float cc) {
                   return 0.75 * (1.0 + cc);
               }

               float density(float3 p) {
                   return exp(-(length(p) - R_INNER) * SCALE_H);
               }

               float optic(float3 p, float3 q) {
                   float3 step = (q - p) / FNUM_OUT_SCATTER;
                   float3 v = p + step * 0.5;

                   float sum = 0.0;
                   for (int i = 0; i < NUM_OUT_SCATTER; i++) {
                       sum += density(v);
                       v += step;
                   }
                   sum *= length(step) * SCALE_L;
                   //sum = mul(sum,length(step) * SCALE_L);

                   return sum;
               }

               float3 in_scatter(float3 o, float3 dir, float2 e, float3 l) {
                   float len = (e.y - e.x) / FNUM_IN_SCATTER;
                   float3 step = dir * len;
                   float3 p = o + dir * e.x;
                   float3 v = p + dir * (len * 0.5);

                   float3 sum = float3(0.,0.,0.);
                   for (int i = 0; i < NUM_IN_SCATTER; i++) {
                       float2 f = ray_vs_sphere(v, l, R);
                       float3 u = v + l * f.y;

                       float n = (optic(p, v) + optic(v, u)) * (PI * 4.0);

                       sum += density(v) * exp(-n * (K_R * C_R + K_M));

                       v += step;
                   }
                   sum *= len * SCALE_L;
                   //sum = mul(sum,len * SCALE_L);

                   float c = dot(dir, -l);
                   float cc = c * c;

                   return sum * (K_R * C_R * phase_reyleigh(cc) + K_M * phase_mie(G_M, c, cc)) * E;
               }
               ////////////////////////////////////////////////////////////////////////////////////////////////////////

               fixed4 frag(v2f i) : SV_Target
               {
                   //Re-initialize BEGIN
                   // math const
                   PI = 3.14159265359;
                   DEG_TO_RAD = (3.14159265359 / 180.0);
                   MAX = 10000.0;

                   // scatter const
                   K_R = 0.166;
                   K_M = 0.0025;
                   E = 14.3;

                   C_R = float3(0.3, 0.7, 1.0);     // 1 / wavelength ^ 4
                   G_M = -0.85;                 // Mie g

                   R = 1.0;
                   R_INNER = 0.7;
                   SCALE_H = 4.0 / (1.0 - 0.7);
                   SCALE_L = 1.0 / (1.0 - 0.7);

                   NUM_OUT_SCATTER = 10;
                   FNUM_OUT_SCATTER = 10.0;
                   NUM_IN_SCATTER = 10;
                   FNUM_IN_SCATTER = 10.0;
                   //Re-initialize END

                       float4 fragColor = 0;
                       float2 fragCoord = i.vertex.xy;

                       // default ray dir
                       float3 dir = ray_dir(45.0, _ScreenParams.xy, fragCoord.xy);

                       // default ray origin
                       float3 eye = float3(0.0, 0.0, 2.4);

                       // rotate camera
                       float3x3 rot = rot3xy(float2(0.0, _Time.y * 0.5));
                       /* dir = rot * dir;
                        eye = rot * eye;*/

                           dir = mul(rot,dir);
                           eye = mul(rot,eye);

                           // sun light dir
                           float3 l = float3(0, 0, 1);

                           float2 e = ray_vs_sphere(eye, dir, R);
                           if (e.x > e.y) {
                               discard;
                           }

                           float2 f = ray_vs_sphere(eye, dir, R_INNER);
                           e.y = min(e.y, f.x);

                           float3 I = in_scatter(eye, dir, e, l);

                           fragColor = float4(I, 1.0);

                           return fragColor;
                       }
                       ENDCG
                   }
    }
}

This shader is attached to a Material that is then attached to the camera with the code below:
[ExecuteInEditMode]
public class CameraEffect : MonoBehaviour
{
    public Material mat;

    // Called by camera to apply image effect
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (mat != null)
        {
            Graphics.Blit(source, destination, mat);
        }
        else
        {
            Graphics.Blit(source, destination);
        }
    }
}

It works fine but notice how I had to re-initialize the PI, DEG_TO_RAD, MAX and other global variables...Without doing that it won't work.The screen is simply black and this is not the first shader that has caused this same issue.
Why is this happening?
Am I declaring the variables the wrong way?

A: Hi!
Any constants you can write like this:
//float my_constant = 104.3;
#define my_constant   104.3f

You can create custom library for shaders and use variables and functions as you wish. For example create file with name MyConstants.cginc and put in in your project. Code:
#ifndef MY_CONSTANTS_INCLUDED
#define MY_CONSTANTS_INCLUDED

#define DEG_TO_RAD    0.01745329251994f
#define MAX           10000.0f
#define PI            3.14159265359f

//scatter const
// .....
// .....

float3 ray_dir(float fov, float2 size, float2 pos) {
    float2 xy = pos - size * 0.5;
    float cot_half_fov = tan((90.0 - fov * 0.5) * DEG_TO_RAD);
    float z = size.y * 0.5 * cot_half_fov;
    return normalize(float3(xy, -z));
}
//.... and other methods
#endif

And Using library in your shader
//.....
#include "UnityCG.cginc"
#include "MyConstants.cginc"
//.....