filedownloading is making the file to view instead of download in drupal7

Question: Hi i have followed Working with files in Drupal 7 and created the content type for file download.Everything is working fine i can upload a file and displaying it in the front page.But when i click on particular file for downloading it is just viewing the file in another tab in the browser with url like this
drupal7.22/sites/default/files/file.txt
I can view the file but not able to download it.Can you just say me where i did the mistake.
Comment: You have simply file field in content type? If so, then browser's default behaviour is respected, and txt files are, by default, opened in browser. If your manual added anything to this, tell us what else you have done, and how.
Comment: No in content type i just have a file field
Comment: As @Mołot mentions this is simply a browser issue. Most browsers will open files with an extension of .txt internally, unless of course the file sends a force-download header (which won't happen in Drupal as it just passes through requests for existing files without getting involved). Try changing your browser settings to force-download those files, or simply click 'File -> Save As...' as with any other document viewed inside your browser
Answer: Read Force Files to Download Instead of Showing Up in the Browser as the page suggests you can achieve this by adding these lines to  .htaccess file
<FilesMatch "\.(?i:doc|odf|pdf|rtf|txt)$">
  Header set Content-Disposition attachment
</FilesMatch>

Or alter mime type
Comment: Good answer, I'm not sure this'll work for Internet Explorer though. It can be a bit funny about attachments. Not that we should care about IE these days anyway, but probably worth mentioning


What are the IOPS and physical block size for modern magnetic tapes?

Question: It's obvious that magnetic tape media performs IO operations as well as HDDs and SSDs, although this storage device is not designed for a random access pattern.
LTO standards define maximal data transfer rate (also known as throughput) measured in bytes/sec for every LTO generation. But I wasn't able to find any information about IO rate with exception to this paper claiming that

Tape drive is available with 1000 IOPS

Also I'm curious if some kind of elementary entity similar to HDD's sector and SSD's block of pages exists in a magnetic tapes world, because its size directly impacts throughput:
<code>  Throughput = IOPS * BlockSize
</code>
Answer: Physical tape is a sequential medium, so forget about (random access) IOPS. I've got some 90 seconds maximum rewind time in my head for LTO. Translated to 45 seconds mean access time, you'd get .02 IOPS.
It's the sustained transfer rate that's of interest. LTO-9 runs at up to 400 MB/s.
Perhaps the authors are using some exotic definition for IOPS - usually the term is used for random access. If you use it to count sequential blocks, you'd get around 6000 blocks/s with average sized 64 KiB blocks for LTO-9 (block size isn't fixed for most tape drives).
Virtual tapes or libraries are a completely different story. They're not hampered by tape's physical limitations, so you could get several hundred or thousand IOPS when backed by HDDs, or even millions when backed by SSDs.


How to solve this line integral?

Question: I have this line integral $\int_{C}(x^2+y^2)ds$, where $C=\{(x,y)|x^2+y^2=ay\}$. I tried solving it by substituting the variables as $x=r\cos{t}$ and $y=r\sin{t}$. So when I differentiate, I get $dx=-r\sin{t}$ and $dy=r\cos{t}$.
So popping this into the integral we get:
$\int_{C}((\cos{t})^2+(\sin{t})^2)*\sqrt{(-r\sin{t})^2+(r\cos{t})^2}dt$
I could probably integrate this if I knew how to apply the given circle.
Answer: If $x=r\cos t$ and $y=r\sin t$, then $x^2+y^2=r^2\ne ay$; besides, what is $r$?
Instead, since$$x^2+y^2=ay\iff x^2+\left(y-\frac a2\right)^2=\frac{a^2}4,$$you should take $x=\frac a2\cos t$ and $y=\frac a2+\frac a2\sin t$. And then you compute$$\int_0^{2\pi}\left(\frac{a^2}4\cos^2t+\frac{a^2}4(1+\sin t)^2\right)\left\|\left(-\frac a2\sin t,\frac a2\cos t\right)\right\|\,\mathrm dt.$$
Comment: (+1) It looks as if I used the Law of Cosines to do the same thing that you did with coordinate geometry.
Answer: An alternative parametrization comes from polar coordinates centered at the origin. As you can check (you can draw a picture and draw the right triangle to see this), we have the polar equation $r=a\sin\theta$, $0\le\theta\le\pi$, so you can parametrize by
$$x=r\cos\theta = a\sin\theta\cos\theta, \quad y = r\sin\theta = a\sin^2\theta, \quad 0\le\theta\le\pi.$$
Given the integrand $x^2+y^2$, this would be my choice.
Comment: Could not agree more!
Answer: Your value for $\mathrm{d}s$ looks off.  Here is a trigonometric approach.

$$
\begin{align}
\oint\left(x^2+y^2\right)\mathrm{d}s
&=\int_0^{2\pi}\left(\frac{a^2}2-\frac{a^2}2\cos(\theta)\right)\,\frac a2\,\mathrm{d}\theta\\
&=\frac{a^3}{4}\,2\pi\\[3pt]
&=\frac{\pi a^3}2
\end{align}
$$

How to solve this line integral?


Java: How to save console output to a text file?

Question: For example, in the code, I have: System.out.println("Hello World");
The console will print: Hello World
So, I want to save the console output into a text file. Can anyone please hint me through this?
Comment: http://stackoverflow.com/questions/1994255/how-to-write-console-output-to-a-txt-file

Possible duplicate.
Comment: Have you googled `writing to a file in java` ?
Comment: You can either write directly to a file, or redirect the output of the program to a file using OS commands (see redirection in linux for example)
Answer: Create a file, and set as the  out of the System class.
File file = new File("out.txt"); //Your file
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
System.out.println("This goes to out.txt");

Comment: Won't this rewrite the entry each time you want to write into the file?
Comment: nice, easy and will help
Comment: This doesn't seem to work, the output file is pretty empty...comments?
Comment: Doesn't work ! did not find any console text inside file . after getting NPEx.
Answer: System class provide you a way to dump output in different stream which is  System#setOut(PrintStream out)
Using this method you can pass you FileInputstream to System.setOut and you can save the console output.
PrintStream printStream = new PrintStream(new FileOutputStream(file));
System.setOut(printStream);

One interesting part of this question is though out is declared as final in System class but still you reassign this by System#setOut.
Comment: No content found inside file. still having npEx.
Comment: please share the `exception stacktrace`


fatal python error (pygame parachute) Segmentation Fault when using Tkinter

Question: I made small game in pygame and python 2.7 and added submit box with Tkinter.
It worked fine till I compiled it with py2exe / pygame2exe.
Compilation was error-free.
But when i clicked on exe file to launch the application, compiled-code threw this error:
    fatal python error (pygame parachute) Segmentation Fault
    This application has terminated in unusal way for more
    information contact application support team.

When I delete Tkinter code and compile it it runs fine.
This is a part of Tkinter code:
    #i tried importing both with import Tkinter and from Tkinter import*

    if event.key==pygame.K_s:
        subbox=Tkinter.Tk()
        subbox_label=Tkinter.Label(subbox,text="Type your name:")
        subbox_label.pack()
        subbox_entry=Tkinter.Entry(subbox)
        subbox_entry.pack()
        def savescore(a):
            a=str(a)
            print a
            print subbox_entry.get()
            player_name=subbox_entry.get()
            player_score=a
        subbox_button=Tkinter.Button(text="Click",command=lambda:savescore(score))
        subbox_button.pack()
        subbox.mainloop()

UPDATE:
I kicked out Tkinter code line by line and it came up that importing Tkinter causes error!
That means that if I have just:
import Tkinter

my game won't work!!! What should I do?
setup file(pygame2exe but I may accidently delete something inside):
try:
    from distutils.core import setup
    import py2exe, pygame
    from modulefinder import Module
    import glob, fnmatch
    import sys, os, shutil
    import operator

except ImportError, message:
    raise SystemExit,  "Unable to load module. %s" % message

#hack which fixes the pygame mixer and pygame font
origIsSystemDLL = py2exe.build_exe.isSystemDLL # save the orginal before we edit it
def isSystemDLL(pathname):
    # checks if the freetype and ogg dll files are being included
    if os.path.basename(pathname).lower() in ("libfreetype-6.dll", "libogg-0.dll","sdl_ttf.dll"): # "sdl_ttf.dll" added by arit.
            return 0
    return origIsSystemDLL(pathname) # return the orginal function
py2exe.build_exe.isSystemDLL = isSystemDLL # override the default function with this one

class pygame2exe(py2exe.build_exe.py2exe): #This hack make sure that pygame default font is copied: no need to modify code for specifying default font
    def copy_extensions(self, extensions):
        #Get pygame default font
        pygamedir = os.path.split(pygame.base.__file__)[0]
        pygame_default_font = os.path.join(pygamedir, pygame.font.get_default_font())

        #Add font to list of extension to be copied
        extensions.append(Module("pygame.font", pygame_default_font))
        py2exe.build_exe.py2exe.copy_extensions(self, extensions)

class BuildExe:
    def __init__(self):
        #Name of starting .py
        self.script = "game_0.3.py"

        #Name of program
        self.project_name = "game"

        #Project url
        self.project_url = "it will be  on sourceforge and indieDB"

        #Version of program
        self.project_version = "0.3"

        #License of the program
        self.license = "gnu gpl 2.0"

        #Auhor of program
        self.author_name = "John Doe "
        self.author_email = "i dont want spam"
        self.copyright = "John Doe 2014"

        #Description
        self.project_description = None

        #Icon file (None will use pygame default icon)
        self.icon_file = "icon.ico"

        #Extra files/dirs copied to game
        self.extra_datas = ["block.png","CHARACTER.png","icon.ico","COPYING.txt","README1.txt","name.txt","score.txt"]

        #Extra/excludes python modules
        self.extra_modules = []
        self.exclude_modules =['AppKit', 'Foundation', 'Numeric', 'OpenGL.GL', '_scproxy', '_sysconfigdata', 'copyreg', 'dummy.Process', 'numpy', 'pkg_resources', 'queue', 'winreg', 'pygame.sdlmain_osx']

        #DLL Excludes
        self.exclude_dll = ['']
        #python scripts (strings) to be included, seperated by a comma
        self.extra_scripts = []

        #Zip file name (None will bundle files in exe instead of zip file)
        self.zipfile_name =None

        #Dist directory
        self.dist_dir ='dist'

    ## Code from DistUtils tutorial at http://wiki.python.org/moin/Distutils/Tutorial
    ## Originally borrowed from wxPython's setup and config files
    def opj(self, *args):
        path = os.path.join(*args)
        return os.path.normpath(path)

    def find_data_files(self, srcdir, *wildcards, **kw):
        # get a list of all files under the srcdir matching wildcards,
        # returned in a format to be used for install_data
        def walk_helper(arg, dirname, files):
            if '.svn' in dirname:
                return
            names = []
            lst, wildcards = arg
            for wc in wildcards:
                wc_name = self.opj(dirname, wc)
                for f in files:
                    filename = self.opj(dirname, f)

                    if fnmatch.fnmatch(filename, wc_name) and not os.path.isdir(filename):
                        names.append(filename)
            if names:
                lst.append( (dirname, names ) )

        file_list = []
        recursive = kw.get('recursive', True)
        if recursive:
            os.path.walk(srcdir, walk_helper, (file_list, wildcards))
        else:
            walk_helper((file_list, wildcards),
                        srcdir,
                        [os.path.basename(f) for f in glob.glob(self.opj(srcdir, '*'))])
        return file_list

    def run(self):
        if os.path.isdir(self.dist_dir): #Erase previous destination dir
            shutil.rmtree(self.dist_dir)

        #Use the default pygame icon, if none given
        if self.icon_file == None:
            path = os.path.split(pygame.__file__)[0]
            self.icon_file = os.path.join(path, 'pygame.ico')

        #List all data files to add
        extra_datas = []
        for data in self.extra_datas:
            if os.path.isdir(data):
                extra_datas.extend(self.find_data_files(data, '*'))
            else:
                extra_datas.append(('.', [data]))

        setup(
            cmdclass = {'py2exe': pygame2exe},
            version = self.project_version,
            description = self.project_description,
            name = self.project_name,
            url = self.project_url,
            author = self.author_name,
            author_email = self.author_email,
            license = self.license,

            # targets to build
            console = [{
                'script': self.script,
                'icon_resources': [(0, self.icon_file)],
                'copyright': self.copyright
            }],
            options = {'py2exe': {'optimize': 2, 'bundle_files': 1, 'compressed': True, \
                                  'excludes': self.exclude_modules, 'packages': self.extra_modules, \
                                  'dll_excludes': self.exclude_dll,
                                  'includes': self.extra_scripts} },
            zipfile = self.zipfile_name,
            data_files = extra_datas,
            dist_dir = self.dist_dir
            )

        if os.path.isdir('build'): #Clean up build dir
            shutil.rmtree('build')

if __name__ == '__main__':
    if operator.lt(len(sys.argv), 2):
        sys.argv.append('py2exe')
    BuildExe().run() #Run generation
    raw_input("Press any key to continue") #Pause to let user see that things ends

another important thing:if i import Tkinter before pygame there is no segmentation error but game doesn't run and error window pops out and says this application requested runtime to terminate in unusal way for more information contact app support
Comment: Not sure if it has to do with your issue, but your `command-lambda...` is going to bite you in the future, that's going to call once and only ever once when you assign it, not when its clicked.
Comment: Take a look at this: http://pygame-users.25799.x6.nabble.com/Python-error-pygame-parachute-Segmentation-Fault-td457.html  apparently it's about Pygame loosing focus on Windows.
Comment: @user2085282 Why? It's creating a lambda function, not calling it.
Comment: @parchment ah, you're correct, i was thinking in terms of no lambda, ignore me.
Comment: Should I try some other module this is really annoying as the submit should not be so important and it takes my time from making other game feautures
Comment: Have you performed any fault-isolation efforts to diagnose, on which exact operation the SegFault appears? Pygame's event-loop controls might get in troubles with Tkinter .mainloop(), so be rather specific and post the code, where you have backtracked the SegFault to appear.
Comment: I'll try to remove just parts of Tkinter code thanks
Comment: @user3666197 I did that look at edited question.Help?
Comment: Would you kindly post also your `setup.py` file used for `py2exe` compilation?
Answer: Did you check py2exe/Bugs?
While it is not exactly the same crash, the root-cause, related to Tkinter internal dependence on sub-layer of Tcl & Tk DLL services seems similar:
cit.:
"""
Using Tkinter, and bundle_files = 1, i get an immediate crash.
Here's my setup:
    winxp sp2
    py2exe 0.6.8
    python 2.5.1

My test file is "example.py", as follows:
#### start
from Tkinter import *
if __name__ == '__main__':
print "hello"
#### end
my setup.py is as follows:
#### start
from distutils.core import setup
import py2exe
setup(
options = {'py2exe': {'bundle_files': 1}},
zipfile = None,
console=['example.py'])
#### end

it compiles just fine, but when running the "example.exe" that is produced in the "dist" directory, it immediately gets the error message "example.exe has encountered a problem and needs to close. We are sorry for the inconvenience".
Using the same setup.py, but with bundle_files = 3 works fine; using bundle_files = 2 causes the same crash.
I hope this is sufficient information to replicate this bug. I will be happy to provide any other info if you need it - just post back here.
"""
+ a there proposed workaround:
cit.:
"""
I "fixed" this by editing site-packages/py2exe/build_exe.py,
adding "tcl85.dll" and"tk85.dll" to the "dlls_in_exedir" list
-- meaning that they get put next to the .exe rather than bundled inside it.
Slightly messy, but much better than bundled=3
"""


Getting the "Branch" Directory Name when using SVN in Teamcity

Question: Is there anything similar to %teamcity.build.branch% when using SVN? Or even the full URI for the checked out SVN directories?
I have a project setup as follows:
ProjectA
-- trunk/
-- release/
-- tags/
----build.x.x.x

The VCS Root is  http://svnhost/svn/repo/ProjectA and then I add Checkout Rules per build config -- e.g.  +/trunk=>.
Is there anyway to access the relative path, full url, etc to parse? For example, if this was a working directory, svn info would give the information I need.
Basically, I want to append part of the folder name to the version number, e.g. #.#.#.#-trunk or #.#.#.#-release or #.#.#.#-tag
Answer: Define a variable in the target, say "folder.name" and change the "VCS checkout rule" to
+:%folder.name% -> whatever
You can now use this variable folder name in your versioning and tagging operations as well
Comment: This is more or less what I ended up using.  Not as clean as branching when you use DVCS but seems like the only choice.


The vertical velocity of a ball hit by a bat is given in the following options. Which of them is right?

Question:
Which of the above graphs describe the variation of the ball's velocity v with time between the time t1 as it hits the bat and t2 as it touches the ground?
I solved it, and my imperfect visualisation gave me c as the right option. Obviously, and unfortunately, it was wrong, as the answer is b.
HOW I DEDUCED MY ANSWER
When the ball hits the bat, it's velocity is v, which goes on decreasing until it reaches its maximum height where velocity is zero. It then falls down, with the magnitude of velocity increasing in the negative direction. Only c supports this method of representation of the given motion. What is the thought proccess behind arriving at b?
Comment: velocity Always has a direction.
Answer: I agree with you that (c) seems to be the best answer to the question you quote.
Note that the graph in (b) shows the absolute value of (c). However, the usual way to use the words in English -- or at least the usage that educators generally insist on -- is that "velocity" means a quantity with a direction (that is, in one dimension is has both a magnitude and a sign) whereas "speed" is the usual word for just the magnitude (or absolute value) of the velocity. So by this standard usage, the graph (c) shows the velocity that you're asked for, whereas (b) shows the speed.
If you're translating the question from a different language than English, something may have been lost in translation.

(In fact all the graphs look wrong to me unless we assume that the ball is hit directly upwards and lands atop the batter. If its velocity has a horizontal component too (which will certainly be the case in most ball-and-bat sports (possibly excepting cricket in which all manner of strange things seem to happen)) that component is not affected by falling, so the speed will never drop to zero, and there should really be a graph looking like the upper branch of a hyperbola, not touching the $t$ axis.)
Comment: Yeah, I edited the question. It's now only the vertical component. The vertical velocity is only asked between the time when the ball hits the bat and touches the ground.


How to fix "Response to preflight request doesn't pass access control check: It does not have HTTP ok status" error in react app with nodejs api

Question: I have been trying to do an api call (nodejs with express running on localhost) from a react app running in the browser over a local dev server (web-pack dev server). Everything was working well until I tried to call the api. They are both running on separate ports.
I have tried adding the cors headers (Recommended by MDN) to both the post call (from the app in browser) and to the response from the Nodejs API but neither of these solved the issue.
Code for the api call (in browser):
const headers = {
  'Content-Type': 'application/json',
  'access-token': '',
  'Access-Control-Allow-Origin': '*',
}

export default async () => {
  try {
    const body = JSON.stringify({
      test: true,
    })
    const response = await fetch('http://localhost:1337/internal/provider/check_email_exist', {
      method: 'POST',
      headers,
      body,
    })
    console.log(response)
  } catch (e) {
    return e
  }
}

API Middleware (in nodejs):
// Verify All Requests
app.use(VerifyToken)

// Compress
app.use(compression())

// Helmet middlware
app.use(helmet())

// Body Parser
app.use(bodyParser.urlencoded({
  extended: false,
}))
app.use(bodyParser.json())

The expected result is to just give a 200 status code and respond with the data.
The actual output is:
OPTIONS http://localhost:1337/internal/provider/check_email_exist 404 (Not Found)

Access to fetch at 'http://localhost:1337/internal/provider/check_email_exist' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Comment: The `Access-Control-Allow-Origin` header should come from the server, not the client. You can try using the `cors` module (`app.use(cors())`) to get this working, but I suggest you read up on CORS and how it is used to protect web browser users. It also looks like you haven't implemented a route for `/internal/provider/check_email_exist` which is why the request is failing in general.
Comment: The server you're sending the request to must be configured to respond to OPTIONS requests with a 200 OK success response. Right now, it's responding with a 404 error to the CORS preflight OPTIONS request your browser is sending. So you don't have the server properly CORS-enabled yet.
Answer: Since you're using webpack-dev-server you can use the proxy option DevServerProxy.
Your configuration will look like this:
// webpack.config.js
devServer: {
    proxy: {
      '/internal': 'http://localhost:1337'
    }
  }

Since I can't see your express routes on your question I'm speculating about the proxy route if your API lives on /internal endpoint then you should modify your React code like this:
const response = await fetch('/internal/provider/check_email_exist', {
   method: 'POST',
   headers,
   body,
})

As you can see I ommited the https://localhost:1337 because the proxy option from webpack-dev-server will handle this and it will redirect to http://localhost:1337. Hope this will help you. Cheers, sigfried.
EDIT
As the comment on your question pointed out you should set the headers on your express server, not the client, for this task you can use the cors-middleware package.
Answer: Maybe this can help if you face with preflight errors.
My full config:
const cors = require('cors');
const express = require('express');
const { createProxyMiddleware: proxy } = require('http-proxy-middleware');

...
const logLevel = 'info';
const ip = require('ip').address();

const proxyOptions = {
  xfwd: true,
  target,
  changeOrigin: true,
  logLevel,
  cookieDomainRewrite: {
    '*': 'localhost',
  },
  headers: {
    'X-Forwarded-For': ip,
    'X-Node': 'true',
  },
};

const backNginxApp = express();

backNginxApp.use(
  cors({
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    origin: 'http://localhost:3000',
    optionsSuccessStatus: 200,
    credentials: true,
  })
);
backNginxApp.use('/api', proxy(proxyOptions));

API: const target = 'https://someapi.com'
Local development running at: http://localhost:3000


How to print taxonomy id of the current taxonomy term

Question: I have custom taxonomy term pages which I'm using to override forum pages and I want to emulate advanced forum node/add/forum/tid button so I have to get tid but don't know how, I can only find examples on how to print tid of the current node.
Answer: You can use below code to get Taxonomy id by Taxonomy Name
<code> $taxonomy_term = taxonomy_get_term_by_name('Taxonomy Term Name');
 $tid = $taxonomy_term>tid;
</code>
Comment: No it's not working at all, I tried this but it didn't work either tid; ?>">
Answer: You can use taxonomy_get_term_by_name and use arg(3) (those are the URL args find out more about those here in the docs) or something similar to pull the name. That function should return an array of match term objects. There should be more information on the taxonomy.module docs that could help as well, you can find them here: https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/6
I have experience in D6 but not as much as D7 but something like that should work or a custom query but I'd advise against those since there is already a function for it in the API.
Comment: I'm using drupal 6 I need to print it just the number
Comment: Is the tid part of the URL?
Comment: yes I want it to be a link


Qual é a diferença entre essas duas declarações?

Question: Digamos que eu criei uma struct ponto que dá um certo ponto num "mapa".
struct Ponto {
    let x: Int
    let y: Int

    init(x: Int, y: Int) {
        self.x = x
        self.y = y
    }

Qual seria a diferença entre criar uma variável do tipo Ponto e criar uma variável que contenha Ponto como valor?
var ponto1: Ponto

//e

var ponto2 = Ponto(x: 1, y: -1)

Comment: Não precisa implementar o init basic usando structures. `struct Ponto {
    let x, y: Int }`
Answer: As duas estão criando uma variável do tipo Ponto, a primeira não cria uma instância do objeto do tipo Ponto e se tentar acessar em seguida dará um erro de compilação, se inicializar depois da declaração funcionará normalmente:
struct Ponto {
    let x: Int
    let y: Int
    init(x: Int, y: Int) {
      self.x = x
      self.y = y
    }
}
var ponto1: Ponto;
ponto1 = Ponto(x: 1, y: -1);
print(ponto1.x, ponto1.y);

Coloquei no GitHub para referência futura.
O segundo cria e inicializa o objeto com valores passados no construtor (o init()) que faz o que ele tem que fazer para inicializar. No caso ele passou argumentos nomeados que é a cultura de Swift para deixar mais legível.
Answer: O primeiro é declaração do tipo var ponto1: Ponto, ou seja, só está dizendo que a variável ponto1 é do tipo Ponto e não há uma instância, já a outra var ponto2 = Ponto(x: 1, y: -1) é a instância de Ponto na variável ponto2, tem que tomar cuidado porque a ponto1 não é uma instância e consequentemente não tem acesso aos seus membros.
struct Ponto {
  let x: Int
  let y: Int

  init(x: Int, y: Int) {
    self.x = x
    self.y = y
  }
}

var ponto1: Ponto = Ponto(x: 6,y: 3); // tipo e depois instância
var ponto2 = Ponto(x: 100, y: 200); // instância

print(ponto1.x);

Exemplo Online

O que pude perceber também que segue uma nomenclatura onde para ter um membro inicial padrão com uma sobrecarga de construtor tem que fazer dessa forma:
struct Ponto {
  let x: Int;
  let y: Int;
  init() {
    self.x = 0;
    self.y = 0;
  }
  init(x: Int, y: Int) {
    self.x = x
    self.y = y
  }
}

e no caso da sua instância trabalhar assim:
var ponto0 = Ponto(); // valor padrão
var ponto1 = Ponto(x: 6,y: 3); // valor pelo construtor

Saída:
print(ponto0.x); // 0
print(ponto1.x); // 6

Exemplo Online
Se quiser somente ter os membros com valores padrões não precisa criar o construtor e passe diretamente os valores nos membros e troque let (que define uma constante) por var (que define uma variável) na declaração:
struct Ponto {
  var x: Int = 0;
  var y: Int = 0;
}

var ponto1: Ponto = Ponto();
var ponto2 = Ponto();

print(ponto1.x); // 0
print(ponto2.x); // 0

Realmente são vários conceitos que precisa entender e recomendo uma lida na documentação.

Referencias

Initialization - swift
Structures and Classes


Calculated spread and mean using mean results only

Question: Background: We have a large database of measurement data. The individual data points are actually the mean results of a particular sampling. No further information is available against each data point, only the sample mean is available. We can assume that the sample sizes are the same for each sampling. Commissioning a new study to gather new data with the appropriate details is not feasible from a resource, time, and access perspective, therefore we can only perform the analysis to the best of our ability using this information on hand.
Objective: To determine the "spread of the mean" and the "mean of the mean", using which we hope to determine the probability of failure given a target "pass" value. To clarify, the requestor of this analysis does not care whether an individual measurement fails the target value, but the mean of each sampling must exceed the target value (the requirement coming from an old industry standard).
My original concern was that the data do not provide information on sample standard deviation and therefore we can make no further comments on the population distribution given incomplete information. However, because we are not interested in the behaviour of individual measurements, and instead we wish to analyse the distribution of the mean, it has been argued that we should dispense of the notion that each data point is a mean, and just simply treat the analysis as we would if each data point was a single measurement value.
Question to the community: Is this a sound argument? If not, what statistical principle have we fallen afoul of, and what is our alternative?
Comment: Will the future means have the same sample size as the past data? Alternatively  are the two same sizes known?
Comment: Yes, we are expecting any future values to retain the same sample size.
Answer: Sounds fine to me. Here's an illustration which should be close enough to your scenario.
Say we have a set of $H$ datapoints. Each of these is a mean taken from $n$ individual observations, which are identical and independently distributed with some mean $\mu$ and variance $\sigma^2$.
So we have $\bar X_1, \cdots, \bar X_H$ where $E[\bar X_h]=\mu$ and $V(\bar X_h)=\sigma^2/n$. Implicitly, we assume $\bar X_h = \frac{1}{n} \sum_{i=1}^n X_{hi}$, except we don't have access to $X_{hi}$, only $\bar X_h$.
If we want the best guess of the mean overall, we can take a mean of means: $\bar X = \frac{1}{H}\sum_{h=1}^H \bar X_h$. Then, the expectation of this can be shown to be $\mu$ (good, it's unbiased). The variance of this estimator can be shown to be $\frac{\sigma^2}{nH}$. And taking the square root of the variance of the estimator, will give a standard error on the mean.
Technically: under this framework, the mean doesn't have a distribution. It's just a value. But the uncertainty on the mean is what you care about, I think.
Comment: Thanks for the comments, I do believe you have the correct understanding of the problem we're trying to solve.
I follow your explanation for most of the post, however I'm unsure on the calculation of the variance of the estimator that you've given. Sigma-squared is the variance of the underlying population, which is a piece of information that I do not have. In this particular case, I do not even have the sample standard deviations to use as an estimate of the population standard deviation.
How do I get to the variance of the estimator, and therefore the SE of mean?
Comment: Ah. I was just trying to illustrate that your concern "My original concern was that the data do not provide information on sample standard deviation" was unfounded - the means themselves _do_ provide information on the standard deviation. Just taking the standard error on the mean of means (i.e. treating the means themselves as individual data points) is OK, and gives the uncertainty on the mean of the original ($X_{hi}$) variables.
Comment: @AlexJ , Why is there $H$ in the denominator of the formula for the standard error estimate? I think it should be $SE(\bar{X_h}) = \frac{\hat{\sigma}_h}{\sqrt{n}}$. SEM (standard error of the mean doesn't depend on $H$ which is the number of samples)
Comment: @HappyCretine I don't understand the edits you made, can you explain your intentions? If the distribution are iid, then $\mu_i = \mu$ and $\sigma_i = \sigma$ for all variables. Is the change from $X_{hi}$ to $X_{h_i}$ just visual preference or does it have a different meaning? And there is a $H$ in the denominator because there are $H$ observations (each of which itself is a mean).
Comment: For now, I've reverted the edits. If you think something can be clarified, I'm happy to do so, but I'm not convinced at this stage that you've understood what I wrote.
Answer: "However, because we are not interested in the behaviour of individual measurements, and instead we wish to analyse the distribution of the mean, it has been argued that we should dispense of the notion that each data point is a mean, and just simply treat the analysis as we would if each data point was a single measurement value."
I see no problem with that approach; it is sound.
The one major caveat is that you need to be able to treat all you data points as identically distributed; i.e. no change in the process occured while collecting the data. In particular, $n$ remained constant, the sampling process remain the same (how/when, etc. the samples were collected, the mean computed, etc..). If this holds, no need to worry about not knowing the original data.
Basically, you have a sampling distribution of the mean, with a given sample size. The mean of the sampling distribution is the mean of the population, and the variance of your sampling distribution is the variance of the population (unknown, but you can estimate it) divided by $\sqrt{n}$. So you can get estimates of both the population mean and variance...


Location module should lookup address before saving

Question: This question is related to Adding geo location content to node.
I'm trying to get a location saved to a node. The Location module supports this, but I don't like the workflow of this module.
It does the look-up after the node is saved, but I would rather do the location look-up before the node is saved, e.g. by having a look-up button that, when pressed, queries Google, updates the gmap, and lets the user see the location before saving and not afterwards, which causes troubles, if the input address couldn't be found.
Do you have any idea on how to address this issue?
Comment: I switched away from the Location and Gmap module because they were a bit hard to work with. I went with OpenLayers module using the geocoder. The OpenLayers module is pretty impressive.
Answer: This doesn't help you with the Location module, but OpenLayers will map the location before the node is saved.
Answer: I think that OpenLayers Geocoder can be the module you are looking for.

This module extends OpenLayers CCK input widget allowing to mark a location on the map by simply providing its address. A future version will also include support for reverse geocoding.
Comment: Hello, and welcome on _Drupal Answers_. Answers that just contain a link are normally not considered an answer, on SE sites.
Comment: Yes, looks interesting. I looked on it yesterday. Best module I have found so far has been http://drupal.org/project/gmaps but sadly not any port going on for drupal7.


Hover em seletor :before

Question: Me deparei em uma situação, até sei como contornar, fazendo de outra forma, mas gostaria de saber, se é possível utilizar :hover em um elemento :before, tenho a seguinte estrutura:

  Informações da cidade

  Benefícios Fiscais

Onde, o elemento call-box, tem um seletor :before, na seguinte forma:
.call-box {
    float: left;
    font-family: 'LatoBold', arial, sans-serif;
    color: #909090;
    height: 52px;
    width: 150px;
    padding: 10px 0 0 62px;
    line-height: 16px;
    position: relative;
}
.call-box:before {
    position: absolute;
    content: '';
    left: 0;
    top: 0;
    border: 2px solid #00BF8B;
    height: 50px;
    width: 50px;
    -webkit-border-radius: 50%;
       -moz-border-radius: 50%;
            border-radius: 50%;
}

No hover do elemento call-box, gostaria de modificar o seletor :before, é possível?
Answer: Pfss, resolvido.
.call-box:hover:before {
  background-color: #00BF8B;
}

Answer: Sim, é possível da seguinte maneira: http://jsfiddle.net/jhwmxfrz/
.call-box:hover:before {
    background-color: #00BF8B;
}

Hover em seletor :before


Configure CDN for Rails 6 ActiveStorage

Question: I have configured ActiveStorage and it works properly.
However I need to change the final URLs returned to the users, so that they use a CDN.
Currently the final image URL is:
https://mywebsite.nyc1.digitaloceanspaces.com/...

But I need this instead:
https://mywebsite.nyc1.cdn.digitaloceanspaces.com/...

Is it possible to achieve that in Rails 6?
Answer: It seems not possible to configure Rails 6.0 to use a CDN at the moment... However I was able to achieve that by using:
variant.service_url.sub('digitaloceanspaces.com', 'cdn.digitaloceanspaces.com')

Comment: For anyone looking for a complete solution: https://stackoverflow.com/a/59107484/51387

Configure CDN for Rails 6 ActiveStorage


Formulario gravando os mesmos dados

Question: Boa tarde galera. Estou com um problema que não consigo achar uma solução.
Fiz um formulario para gravar os cadastros de um web site , mas muitas vezes esta sendo salvo o mesmo cadastro diversas vezes (vide print)

EU valido todo o formulário para não correr risco de dar nenhum , mas não consigo resolver esse problema, abaixo segue o código para cadastro
UPDATE ---
Abaixo , segue o código praticamente completo , só retirei o código do formulário e parte do código que monta o corpo do email enviado , para não ficar muito grande.
class compra_onlineController extends baseController
{

    public function index()
    {
        $args = func_get_args();

        if (isset($args[0]) && $args[0] == 'nobanner')
            $vars['arg'] = $args[0];
        else
            $vars['arg'] = 'banner';

        if (defined('CANONICAL'))
            $vars['canonical'] = CANONICAL;

        $this->visitCheck();

        new Load('index', $vars);
    }

    public function assinar()
    {
        $args = func_get_args();

        if(isset($args[0]))
                $vars['arg'] = $args[0];
                $package = new PackageModel();

                $package->selectById((int) $vars['arg']);

       $vars['text'] = $package->getHtml().'

        //aqui fico o código do formulario ///

 //fim formulario ';

        if ( isset($_POST['txtNome']) && $_POST['txtNome'] != '' &&
            isset($_POST['txtTel1']) && $_POST['txtTel1'] != '' &&
            isset($_POST['txtEmail']) && $_POST['txtEmail'] != ''
            ) {

                    require_once(SITE_PATH.'inc/phpmailer/class.phpmailer.php');

            //codigo que monta corpo email
            $message_html .= 'Nome: '.$_POST['txtNome'].'
';
            $message_html .= 'Sexo: '.$_POST['txtSexo'].'
';

            $message_html .= 'CPF: '.$_POST['txtCpf'].'
';
            $message_html .= 'RG: '.$_POST['txtRg'].'
';

            ....

            /* --------------------------------- */

             //codigo que monta corpo email
            $message_txt .= 'Nome: '.$_POST['txtNome'].'
';
            $message_txt .= 'Sexo: '.$_POST['txtSexo'].'
';

            $message_txt .= 'CPF: '.$_POST['txtCpf'].'
';
            $message_txt .= 'RG: '.$_POST['txtRg'].'
';

            $message_txt .= 'Por favor, não responda este e-mail.'."\r\n";

            .......

            $mail = new PHPMailer();

            try {
                $mail->addAddress(EMAIL, 'Contato');
                $mail->Subject = $subject;
                $mail->msgHTML($message_html);
                $mail->AltBody = $message_txt;
                $mail->send();
                if($mail->send()){
                    $vars['script'] = "window.location.href='".SITE_HTTP.PREF_HOST.SELF_PATH."controllers/obrigado_2.html'; "; //Nessa pagina , obrigado_2.html , tem os códigos de conversão do GOOGLE ADWORDS  , Bing Ads e Facebook Ads , nela também é feito o redirecionamento.

                }

                $this->visitCheck(true);
            } catch (phpmailerException $e) {
                echo $e->errorMessage(); //Pretty error messages from PHPMailer
            } catch (Exception $e) {
                echo $e->getMessage(); //Boring error messages from anything else!
            }
        }
        else {

            $this->visitCheck();
        }

        if (defined('CANONICAL'))

            $vars['canonical'] = CANONICAL;

        new Load('compra_online', $vars);
    }

function inserir_contato($pdo,$corrige){

    try {

        $arr = array();

        $sql = 'INSERT INTO contatos(telefone)VALUES(:telefone)';
        $stmt = $pdo->prepare($sql);
        $dados = array(

                    ':telefone' => str_replace($corrige, "", $_POST['txtTel1'])
                );

        $stmt-> execute($dados);
        $linha = $stmt->rowCount();
            if($linha == 1){

                return $stmt = $pdo->lastInsertId();
                $pdo = null;

            }else{

               return 0;
            }

    } catch(Exception $e) {

        print 'Erro ao inserir os dados no banco: ' . $e->getMessage();

    }

}

function inserir_contato_nome($pdo,$id_contato){

    try {

            $arr = array();
            $sql = 'INSERT INTO contato_dados_nome(id_contato,nome)VALUES(:id_contato,:nome)';
            $stmt = $pdo->prepare($sql);
            $dados = array(

                ':id_contato'=> $id_contato,
                ':nome' => $_POST['txtNome']
            );

            $stmt-> execute($dados);
            $linha = $stmt->rowCount();
                if($linha == 1){

                    $arr['retorno'] = 1;
                    $pdo = null;

                }else{

                    $arr['retorno'] = 0;
                }

        } catch(Exception $e) {

            print 'Erro ao inserir os dados no banco: ' . $e->getMessage();

        }

        return $arr;
}

function inserir_contato_dados($pdo,$id_contato,$corrige){

    try {

            $arr = array();

            $data = explode("/",$_POST['txtData_nasc']);

            $data_nasc = $data[2]."-".$data[1]."-".$data[0];

            $sql = 'INSERT INTO contato_dados_principal(id_contato,tipo_contato,data_nascimento,sexo,telefone_2)
                                VALUES
                                (:id_contato,:tipo,:data,:sexo,:telefone_2)';
            $stmt = $pdo->prepare($sql);
            $dados = array(
                ':id_contato' => $id_contato,
                ':tipo' => 'fisica',
                ':data'=> $data_nasc,
                ':sexo' => $_POST['txtSexo'],
                ':telefone_2' => str_replace($corrige, "", $_POST['txtTel2'])
            );

            $stmt-> execute($dados);
            $linha = $stmt->rowCount();
                if($linha == 1){

                    $arr['retorno'] = 1;
                    $pdo = null;

                }else{
                    $arr['retorno'] = 0;
                }

        } catch(Exception $e) {

            print 'Erro ao inserir os dados no banco: ' . $e->getMessage();

        }

        return $arr;
}

function inserir_contato_pessoa_fisica($pdo,$id_contato,$corrige){

    try {

            $arr = array();

            $sql = 'INSERT INTO contato_pessoa_fisica(id_contato,rg,cpf)VALUES(:id_contato,:rg,:cpf)';
            $stmt = $pdo->prepare($sql);
            $dados = array(
                ':id_contato' => $id_contato,
                ':rg' => str_replace($corrige, "", $_POST['txtRg']),
                ':cpf' => str_replace($corrige, "", $_POST['txtCpf'])
            );

            $stmt-> execute($dados);
            $linha = $stmt->rowCount();
                if($linha == 1){

                    $arr['retorno'] = 1;
                    $pdo = null;

                }else{

                    $arr['retorno'] = 0;
                }

        } catch(Exception $e) {

            print 'Erro ao inserir os dados no banco: ' . $e->getMessage();

        }

        return $arr;
}

function inserir_contato_endereco($pdo,$id_contato,$corrige){

    try {

            $arr = array();

            $sql = 'INSERT INTO contato_endereco(id_contato,tipo,cep,rua,numero,bairro,cidade,uf)
                                VALUES  (:id_contato,:tipo,:cep,:rua,:num,:bairro,:cidade,:uf)';

            $stmt = $pdo->prepare($sql);
            $dados = array(

                    ':id_contato' => $id_contato,
                    ':tipo' => $_POST['txtTipo_endereco'],
                    ':cep' => str_replace($corrige, "", $_POST['txtCep']),
                    ':rua' =>$_POST['txtRua'],
                    ':num' => $_POST['txtNumero'] ,
                    ':bairro' => $_POST['txtBairro'],
                    ':cidade' => $_POST['txtCidade'],
                    ':uf' => $_POST['txtEstado']
                );

            $stmt-> execute($dados);
            $linha = $stmt->rowCount();
                if($linha == 1){

                    $arr['retorno'] = 1;
                    $pdo = null;

                }else{
                    $arr['retorno'] = 0;
                }

        } catch(Exception $e) {

            print 'Erro ao inserir os dados no banco: ' . $e->getMessage();

        }

        return $arr;
}

if(isset($_POST['enviar'])){

    $corrigir = array(' ','-','(',')','.');

    $contato = new compra_onlineController();
    $conexao = $contato->fn_conexao();
    $id = $contato->inserir_contato($conexao,$corrigir);
    $contato->inserir_contato_nome($conexao,$id);
    $contato->inserir_contato_dados($conexao,$id,$corrigir);
    $contato->inserir_contato_pessoa_fisica($conexao,$id,$corrigir);
    $contato->inserir_contato_endereco($conexao,$id,$corrigir);
}

EDIT --
Pagina obrigado_2.html
//codigo do adwords
//codigo bing

Por que que é feita a inserção diversas vezes de um mesmo cadastro ? Acho difícil ser o usuário pois aconteceu varias e varias vezes .
Obrigado desde já.
Answer: Oi.
Muda o campo telefone para UNIQUE. Assim você não terá mais dados duplicados.
ADD UNIQUE INDEX `telefone`

Sempre que você tentar cadastrar outro celular com os mesmos dígitos, a consulta vai falhar.
Ou então, faz um redirect, para quando você cadastrar esse valor, assim não vai ter como reenviar o mesmo formulário duas vezes.
header("Location: formulário.php");
exit;

Comment: Você não mostrou onde tá fazendo o redireccionamento.
Comment: Boa tarde laura , então , o problema é que gravo na tabela de telefones tanto os dados de cadastro do web site quanto de ligações que a empresa recebe.Se eu deixar como unique o campo de telefone , se a pessoa ligar aqui e depois for fazer um cadastro  , vai dar erro  , pois o telefone ja estaria na base de dados .
Comment: @HenriqueFelix Você pode redirecionar o usuário quando inserir o valor.
Comment: Boa tarde,  ja faço o redirecionamento hehe . Vou editar a pergunta e colocar o restante do código para você ver .
Comment: Continua o mesmo código.
Comment: Acrescentei o código da pagina completa , só omiti o código do formulario
Answer: Verifique se o usuário não esta dando doubleclick no botão e o mesmo esta disparando várias vezes a mesma ação, já vi muito disso.
Faz um teste, crie um script que após o primeiro click desabilite o botão, e veja como se comporta.
Comment: Boa tarde @RBoschini , ja tinha pensado em algo do tipo , mas quando a pessoa clica no botão de submit  , ele aciona um script que valida o formulário , se tiver algum erro , o botão ficar desabilitado e ai a pessoa não vai conseguir enviar novamente .
Comment: Você testou preenchendo todos os campos e clicando varias vezes, se estiver com lentidão apos clicar 1x, o botão fica realmente desabilitado?
se o usuario der ENTER em algum campo e o form estiver com dados correto, ele nao da outro submit nao?

Ve isso com carinho, pq ta com cara de ser isso, pelos horarios dos registros.
Comment: Boa tarde . Apertando o enter envia sim  , mas os campos são validados ,se não estiverem preenchidos ou no tamanho que devem ter ( ex: cpf tem que ter 11 caracteres no campo) , da um alerta js e não envia o formulario.
Comment: Boa tarde @RBoschini , fiz o teste de apertar diversas vezes o botão de submit ,e vi que o sistema ficou lento  ,onde cada vez que eu apertava ele aumentava ainda mais o carregamento  , até que deu timeout na pagina.Acredito que o problema deva ser ai mesmo , como proceder ?
Comment: Faz assim, cria uma variavel, e quando der submit seta essa variavel para true, e deixa passar no suibmit apenas quando essa variavel for false.

deve resolver.
Comment: Fiz dessa forma : $key = false;

if($key == false){

    if(isset($_POST['enviar'])){

        $corrigir = array(' ','-','(',')','.');

        $contato = new compra_onlineController(); //resto do código                           $key = true; } }   .   Mas não deu certo . =(
Comment: Faz isso no javascript nao no PHP.
Tem que ser onde vc da seu $('form').submit().

O objetivo e nao deixar ele dar submit mais de 1x, tem que ser no client-side.
Comment: Boa noite @RBoschini , foi mal sumir ( trampo ) , deu certo a forma que você recomendou. Posta uma resposta mostrando a solução ou marco aqui como solução ? Desde ja , grato
Comment: Marca aqui como solução, ai eu ajudo vc e vc me ajuda!
Que bom que deu certo, qlq coisa é só chamar. abracos

Formulario gravando os mesmos dados


Como armazenar o valor de um input type number em uma variável JS

Question: Não consigo armazenar o value do input na minha variável. Como devo proceder? Meu código abaixo:
<input type="number" id="numero">
<input type="button" class="adicionar" value="Comprar" onclick="add()" />

Quero alterar o value do input e a minha variável alterar também quando eu clicar no botão.
Answer: Só faltou você fechar as chaves, porem existe uma propriedade onchange.
Com a propriedade onchange a cada vez que você alterar o valor do input ele chama sua funçao add(), assim alterando junto o input ele ira alterar sua variável junto;

<input type="number" id="numero" onchange="add()">
<input type="button" class="adicionar" value="Comprar" onclick="add()">

Comment: É verdade, deu certo. Muito obrigado!
Answer: Faltou você fechar as chaves.

<input type="number" id="numero">
<input type="button" class="adicionar" value="Comprar" onclick="add()" />

Comment: Verdade, erro bobo. Valeu pela ajuda!


map json to property on knockout view model

Question: This works fine:
var vm = {};
$.getJSON('file.json', function (data) {
    vm.objects = data;
});
ko.applyBindings(vm);

But this doesn't work:
var vm = {
    objects: $.getJSON('file.json', function (data) {});
};
ko.applyBindings(vm);

Why not?
Thanks
Answer: Because $.getJSON doesn't return anything (or, at least, it doesn't return your data). It's asynchronous, so the only way to access the data is in the callback function.


Como calcular a média excluindo os zeros no R?

Question: Calculei a média dos seguintes valores:
MÉDIA = mean(c(12,20,15,0,7,0))

print(MÉDIA)

[1] "9"

Mas eu preciso da média que não considere os zeros:
MÉDIA_Sem Zeros = mean(c(12,20,15,7))

print(MÉDIA_Sem Zeros)

[1] "13,5"

Como posso calcular a média com a condição excluindo as variáveis de valor zero?
Answer: É só indexar o vetor de modo a excluir os zeros.
x <- c(12,20,15,0,7,0)
mean(x[x != 0])
#[1] 13.5

Se o vetor tiver valores NA, use o argumento na.rm = TRUE ou a função which.
y <- x
y[3] <- NA

mean(y[y != 0], na.rm = TRUE)
#[1] 13

mean(y[which(y != 0)])
#[1] 13

Comment: Obrigado pela resposta vou testar.
Answer: Outra solução é utilizar a função subset:
x <- c(12,20,15,0,7,0)

mean(subset(x, x != 0))
[1] 13.5

ou
mean(subset(x, x > 0))
[1] 13.5

No entanto, é preferível dar preferência ao operador [, como propôs o @Rui. Nesta pergunta há uma explicação mais detalhada sobre a preferência do uso de [ ao invés de subset.
Comment: Obrigado pela resposta vou testar.


Measuring share contribution of each var/cov term to the standard deviation of a sum of variables

Question: Say, for a simple example, I have a random variable $X = \alpha_1 X_1 + \alpha_2 X_2$, where $X_i$ are random variables and $\alpha_i$ are weights. I then calculate the standard deviation of $X$ as $\sigma_X = \sqrt{(\alpha_1)^2 \mathrm{Var}(X_1) + (\alpha_2)^2 \mathrm{Var}(X_2) + 2\alpha_1 \alpha_2 \mathrm{Cov}(X_1,X_2)}$.
What I'm wondering is: what is a good way to calculate the "share" of each of the three individual variance/covariance terms in the total standard deviation of $X$?
It seems like, because of the concavity of the square root function, e.g. $(\alpha_1)^2 \mathrm{Var}(X_1) / \mathrm{Var}(X)$ would not be a good, representative measure of the variance of $\alpha_1 X_1$'s "share contribution" to $X$'s standard deviation; and neither would the share of the square root of each variance/covariance term in the sum of these individual square roots, not the least because I would run into issues trying to take the square root of a negative covariance term.
The motivation for my question is as follows: I'm measuring sampling error in survey-based economic indexes (e.g. the Institute for Supply Management's PMI). For composite indexes (i.e. indexes that are calculated from responses to multiple questions, as weighted sums--the PMI is an example of this), both variance and covariance terms enter into the sampling error formula, as in the example above. I want to look at the time series of the "contributions" to the sampling error of the composite index of each of these individual variance and covariance terms. I want to do this to examine how both dispersion in responses to different questions and co-variation in responses to different questions (a) vary with economic conditions and (b) affect uncertainty in the composite index.
Does this question make sense? If so, do you have any ideas or suggestions?
Comment: Why do you want to compute these shares? What are you going to use them for?
Comment: Please edit your question and put these clarification back to the question text, @XtremeCurling.
Comment: @StasK I'm measuring sampling error in survey-based economic indexes (e.g. the Institute for Supply Management's PMI). For composite indexes (i.e. indexes that are calculated from responses to multiple questions, as weighted sums--the PMI is an example of this), both variance and covariance terms enter into the sampling error formula, as in the example above. I want to look at the time series of the "contributions" to the sampling error of the composite index of each of these individual variance and covariance terms.
Comment: And I want to do this to examine how both dispersion in responses to different questions and covariation between questions (a) vary with economic conditions and (b) affect uncertainty in the composite index.
Answer: Here's my current best guess, in case someone later has this same question.
Make the problem more general in the following way: say you are looking at the expression $x = \sqrt{x_1 + x_2 + \ldots + x_n}$ and want to figure out the "share contribution" of $x_i$ in $x$ (the $x_i$'s are simply the variance and covariance terms in the expression in the question). Suppose we have reason to believe that $\sum x_i \geq 0$ (as in variance expression in the question).
The concavity of the square root makes this kind of difficult. So too does the fact that some $x_i$ could be negative. But, let's look at how this might work for a simple example with just two terms: $x = \sqrt{x_1 + x_2}$. Say $x_1 = 36$ and $x_2 = 64$, so that $x = \sqrt{100} = 10$. We might say that $x_1$ contributes $(36/100)\cdot 10 = 3.6$ and $x_2$ contributes $(64/100)\cdot 10 = 6.4$ to this figure. Or, we might instead say $x_1$ contributes $(\sqrt{36}/(\sqrt{36}+\sqrt{64}))\cdot 10 \approx 4.29$ and $x_2$ contributes $\approx 5.71$ to this figure.
One problem with the first method is, of course, that it understates the contributions of smaller terms. By itself, $\sqrt{x_1}$ is $6$, only $25\%$ lower than $\sqrt{x_2} = 8$; while its calculated contribution is almost $45\%$ lower than that of $x_2$. This doesn't seem right. On the other hand, at least the denominator ($x_1+x_2$) has some natural connection to $x = \sqrt{x_1+x_2}$; while the denominator in the second method, $\sqrt{x_1}+\sqrt{x_2}$, is hardly natural.
I'm going to propose a third method and claim that it is better than these first two, though I'm having trouble supporting the claim; it just seems right to me.
Here's the third method, with the simple example from above. Look at $\min\{x_1,x_2\} = x_1$. Both $x_1$ and $x_2$ contribute the amount $x_1$ to the sum inside the square root; so, we should figure out how much of $x$ is contributed by the first $x_1$ amount of both terms, together, and then divide it evenly between $x_1$ and $x_2$; and this amount will eventually be included in the total contributed by each term (in fact, it will represent all of the contribution from $x_1$. To do this, we simply compute $s_1 = \frac{1}{2}\cdot \sqrt{x_1+x_1} = sqrt{72}/2 \approx 4.24$. So, $x_1$'s share contribution to $x$ is $.424$; while $x_2$'s is $.424$ plus something else. Here's how we compute that "something else": we figure out the additional amount contributed by all terms of size at least $x_2$ (in this case, just $x_2$), i.e. compute $\sqrt{x_1 + x_2} - sqrt{x_1 + x_1}$, and add this amount to the $.424$ contributed by the first $x_1$ amount of $x_2$. In numbers, this is $\sqrt{100}-sqrt{72} \approx 10 - 8.49 = 1.51$. So, $x_2$ contributes $\approx 4.24 + 1.51 = 5.75$ to $x$, so that its share contribution is $\approx .575$.
Now I'll write out general formulas for the case with $x = \sqrt{x_1 + \ldots + x_n}$. Reorder the $x_i$ so that $x_1 \leq x_2 \leq \ldots \leq x_n$. Then the contribution of $x_1$ is $s_1 = \frac{1}{n}\cdot\sqrt{n x_1}$; the contribution of $x_2$ is $s_2 = s_1 + \frac{1}{n-1}\cdot(\sqrt{(n-1)x_2 + x_1}-\sqrt{n x_1})$; of $x_3$ is $s_3 = s_1 + s_2 + \frac{1}{n-2}\cdot(\sqrt{(n-2) x_3 + x_2 + x_1}-\sqrt{(n-1)x_2 + x_1})$; and so on. The shares are obtained simply by dividing $s_i$ by $x$ (that the shares add up to $1$ is straightforward to verify).
As long as $\sum x_i \geq 0$, we can account for negative $x_i$ simply by taking the negative of the square root of the absolute value of the expression, as long as the expression inside the square root is negative. In computer code, for example, this would be achieved by replacing sqrt(...) with (real(sqrt(...))-imag(sqrt(...))).
If anyone reads this and has any thoughts (it sucks, it makes sense, have a way to explain why it makes sense because I'm kind of failing at that), please share; I'd really appreciate it.
Comment: The fact that you have to restrict the sum of the $x_i$ suggests (correctly) that your attempt to apportion "shares" of a standard deviation is not well-defined.  (See what happens if you merely re-order the $x_i$, for instance.)  What analytical problem are you attempting to solve with this calculation?  That is, what is the intended meaning?


analitycs solutions to the equation $f'(x)=f(x)f(x-1)$

Question: As the title says I'm serching for functions ($C^n$ or analitycs $f$) that satisfies
$f'(x)=f(x)f(x-1)$

some details: I've come at this equation after looking for a function $g$ satisfying for some given $h$
$g'(g^{-1}(x))=x\cdot h(x)$
I tried to manipulate the equation
$g'(g^{-1}(g(x)))=g(x)\cdot h(g(x))$
And since I assume (define)that $h(g(x))=g(x-1)$ holds the equation should turn into
$g'(x)=g(x)g(x-1)$
Comment: I think it's obvious that no non-constant polynomial $f(x)$ can satisfy this equation, as $f'(x)$ is a polynomial of lower degree than $f(x)$, and $f(x)f(x−1)$ is a polynomial of higher degree than $f(x)$. As to constant polynomials, it's obvious that $f(x)=0$ is the only solution. So apart from this solution, you should probably look for non-polynomial functions.
Comment: @barakmanos ah ok, well.. then what about special functions or conbination of those? At the beginning I was hoping for solutions of that kind (gamma function-like)...
Answer: Define $f(x)$ for $x\in[0,1]$ to be anything.
$$\frac{f'(x)}{f(x)}=f(x-1)\\
\int\frac{f'(x)}{f(x)}dx=\int f(x-1)dx\\
\ln(f(x))+c=\int f(x-1) dx\\
f(x)=A\exp(\int f(x-1) dx)$$
Then, since you already know $f(1)$,
$$f(x)=f(1)\exp(\int_1^x f(t-1)dt)$$
defines $f(x)$ for $x\in[1,2]$
Comment: I'm really sorry but can you expand you answer a little bit? I'm not really good with calculus and differential equations, so maybe you could explain me the deduction and show me the steps, thank you in advance.
Comment: The constant $A$ is meant to be $e^{-c}$? Anyways at the and I get only a function defined on $[0,2]$? Sorry but I'm worse than I expected at this, I'm not very familiar with integrals...
Comment: Then repeat the process to get a function defined on $[2,3]$, and again for $[3,4]$.  Sorry, that's all I've got.  Actually $A=\pm e^{-c}$ because the previous integral should be $|\ln(f(x))|+c$.
Comment: Does $f(x)=1/(1-\{x\})$ count, where $\{x\}$ is the fractional part of $x$?  It is discontinuous at integers.
Comment: well, it works. Even if I was serching for some nicer function, but you showed that one can use every function on $[0,1]$ and define it picewise, in that case nvm, there is not even unicity (even up to integration costant).


Como passar valor dentro do modal com PHP

Question: Estou tentando criar um botão de excluir para uma tabela. A exclusão será feia em duas etapas:
1. clica na lixeira
2. confirma
Acredito que estou me confundindo na hora de passar o valor do $id pro modal.

    <title>Estoque</title>

    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet">

                Código Produto
                Descrição
                Preço
                Quantidade Estoque

    <?php
        REQUIRE_ONCE "conexao.php";
        $sql = "SELECT id, cod_produto, dsc_produto, preco_produto, qtd_estoque, qtd_limitador FROM estoque";
        $result = mysqli_query($conexao, $sql);
        while ($row = mysqli_fetch_assoc($result)){
    ?>

            <tr bgcolor="<?php echo $bg ?>">
                <?php echo $row[cod_produto] ?>
                <?php echo $row[dsc_produto] ?>
                <?php echo $row[preco_produto] ?>
                <?php echo $row[qtd_estoque] ?>
                <?php echo $row[qtd_limitador] ?>

                    <form method="get" action="edit.php">
                        <button type="hidden" name="id" class="btn btn-default" value="<?php echo $row[id]?>"> </button>
                    </form>
                    <form method="POST" action="<?php $_SERVER['PHP_SELF']; ?>">
                        <button type="button" name="botaoDelete" class="btn btn-default" data-toggle="modal" value="<?php echo $row[id] ?>" data-target="#myModal"></button>
                    </form>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Excluir produto

Você tem certeza que deseja excluir?

        <form method="POST">
            <button type="button" name="botaoConfirma" value="<?php echo $dlt ?>" class="btn btn-danger">Excluir</button>
            <button type="button" class="btn btnn-default" data-dismiss="modal">Fechar</button>
        </form>

    <?php
        if (isset($_POST["botaoDelete"])) {
            $dlt = $_POST["botaoDelete"];
            if (isset($_POST["botaoConfirma"])) {
                $cnf = $_POST["botaoConfirma"];
                $deleteSql = mysqli_query($conexao, "DELETE * FROM estoque WHERE id='".$cnf."'");
            }
        }
    }
    ?>

Há alguma forma de passar valor de botão sem ser usando form?
E também, como posso chamar esse valor (caso o botão for pressionado) sem usar if (isset)? Vale a pena?
Comment: Qual o problema que está acontecendo?
Comment: Não está excluindo a linha desejada, ou seja, não estou conseguindo passar a ID até o botão "confirmar". Compensa eu utilizar java nessa parte mesmo focando no desenvolvimento em PHP? Ainda sou iniciante e isso me deixa confuso.
Comment: Tem vários jeitos de resolver isso, a forma mais simples de fazer isso seria, utilizar o `confirm()` do javascript, separar a exclusão do registro em arquivo a parte(talvez em uma função posteriormente ;]) se a resposta do `confirm()` for `true` vc redirecione para esse arquivo novo(excluir.php) caso não só da um `return false` na sua função javascript.
Comment: Mas se eu fizer essa função fora do arquivo, ele vai precisar sair da página ou consigo fazer tudo no modal? Como já havia dito, não seria uma boa prática tentar fazer isso com php uma vez que o código é basicamente todo em php?
Comment: Vai sair da pagina se for confirmada a exclusão, inicie dessa forma, depois vc pode fazer isso via ajax(ai sim não sai da tela nem da refresh na tela).
Answer: Ó, pelo que eu entendi, é isso aqui que você fazer. Seguinte:
1º: Neste passo você chama o modal e, no metodo onclick, você passa o id que deseja. Vai colocar no botão de deletar um link:
<a href="#deletar-dado" role="button" data-toggle="modal" onclick="deletaDado(<?php echo $id ?>)" class="deletar">Excluir

2º: Cria o seu modal da seguinte forma:

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Confirmação

Deseja realmente excluir este registro?

            <button type="button" data-dismiss="modal" class="btn default">Cancelar</button>
            Apagar

3º: criar uma funcao que js que vai receber o id do dado pra deletar:

Se precisar de alguma coisa, chama a gente ai. :D Valeu!
Comment: Eu não entendo muito bem javascript, mas eu não tenho que chamar essa função? Testei aqui o que você disse que o botão de confirmação não faz nada.
Comment: você chama ela dentro do onclick, lá no primeiro passo
Comment: Estou tendo teste.php/deletar/undefined na URL como retorno.
Comment: Você está colocando o id dentro do onclick?
Answer: Seguindo as orientações do Matheus, obtive:

   <title>Estoque</title>

<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">

<link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet">

                Código Produto
                Descrição
                Preço
                Quantidade Estoque

<?php
REQUIRE_ONCE "conexao.php";
$sql = "SELECT id, cod_produto, dsc_produto, preco_produto, qtd_estoque, qtd_limitador FROM estoque";
$result = mysqli_query($conexao, $sql);
    while ($row = mysqli_fetch_assoc($result))
        {

?>

            <tr bgcolor="<?php echo $bg ?>">
                <?php echo $row[cod_produto] ?>
                <?php echo $row[dsc_produto] ?>
                <?php echo $row[preco_produto] ?>
                <?php echo $row[qtd_estoque] ?>
                <?php echo $row[qtd_limitador] ?>

                    <form method="get" action="edit.php">
                        <button type="hidden" name="id" class="btn btn-default" value="<?php echo $row[id]?>"> </button>
                    </form>
                    <a href="#deletar-dado" role="button" data-toggle="modal" onclick="deletaDado(<?php echo $row[id]?>)" class="deletar">Excluir

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Confirmação

Deseja realmente excluir este registro?

        <button type="button" data-dismiss="modal" class="btn default">Cancelar</button>
        Apagar

<?php

}
?>

Ao clicar no link apagar na tela de confirmação, nada acontece.
Comment: Cara, você tem que trocar o seu _href_ dentro da funcao de deletar.
Comment: Desculpa, mas eu ainda não entendo muito bem a sintaxe do javascript. Você poderia dar mais detalhes sobre isso? Se possível explicar o que cada elemento está fazendo na função, talvez isso ajude mais pessoas também.
Comment: você conseguiu resolver dessa forma?
Comment: Na verdade eu estou tentando usar SweetAlert no lugar, mas ainda estou tendo alguns problemas.


Sequences $(\lambda_n)$ such that for every summable sequence $(a_n)$, $(\lambda_na_n)$ is also summable.

Question: An oral examination exercise :

Find all the sequences $(\lambda _n)_n$ of real numbers such that :
  $$\sum a_n \; \text{is convergent} \Longrightarrow \sum \lambda_n a_n \; \text{is convergent}$$

I think the only working sequences are the ones which are bounded and ultimately of constant sign.
I've not seen it on the site so if you have seen it please tell me how you would solve it.
Thanks.
Comment: Boundedness is not enough. If you take $a_n = (-1)^n / \sqrt{n}$, then the series converges. But, even if the sequence is of constant sign, you can slightly "bump up" the positive $a_n$, so that the series given by $\lambda_n a_n$ is not convergent.
Comment: @Dr.MV, well, take value 1 on even numbers and 1/2 on odd numbers.... You can tweak the example as you wish.
Comment: Maybe there is something to try with the abel transformation: https://en.wikipedia.org/wiki/Summation_by_parts#Applications
Comment: @JohnMath take $a_n=1/n^2$ so that $\sum a_n$ converge but with $\lambda_n=n $ you get $\sum \lambda_na_n= \sum 1/n$ which diverge. So $\lambda_n=n$ is not a suitable sequence
Comment: you are right, sorry. my bad
Comment: @D.Thomine What was the $\lambda_n$ in your example?
Comment: @Dr.MV: you may take $\lambda_{2n} = 1$ and $\lambda_{2n+1} = 0$, but there are examples where $(\lambda_n)$ converges.
Comment: @D.Thomine you're right I said that $\lambda _n$ should be ultimately of constant sign for example $\lambda _n \geqslant 0$ for $n \geqslant N$. But if $\lambda_n$ is absolutely convergent there is no need.
Comment: @D.Thomine So, you classify $0$ as having positive sign?
Comment: @D.Thomine Yes; that works! +1 for you comments!
Answer: The sequences of bounded variation, we must have
$$\sum_{n = 0}^\infty \lvert \lambda_{n+1} - \lambda_n\rvert < +\infty.$$
For a convergent series $\sum a_n$, consider the sequence of tail sums
$$r_n = \sum_{k = n}^\infty a_k.$$
Then $(r_n)$ is a sequence converging to $0$, and with $a_n = r_n - r_{n+1}$ a summation by parts yields
\begin{align}
\sum_{n = 0}^N \lambda_n a_n &= \sum_{n = 0}^N \lambda_n (r_n - r_{n+1})\\
&= \sum_{n = 0}^N \lambda_n r_n - \sum_{n = 1}^{N+1} \lambda_{n-1} r_n\\
&= \lambda_0 r_0 - \lambda_N r_{N+1} + \sum_{n = 1}^N (\lambda_{n} - \lambda_{n-1}) r_n.
\end{align}
It is easy to see that the boundedness of $(\lambda_n)$ is necessary, so with that restriction we have $\lambda_N r_{N+1} \to 0$, and
$$\sum_{n = 0}^\infty \lambda_n a_n$$
is convergent if and only if
$$\sum_{n = 1}^\infty (\lambda_n - \lambda_{n-1})r_n\tag{1}$$
is convergent. Since $\sum \lambda_n a_n$ shall converge for all convergent $\sum a_n$, $(1)$ must converge for all $r \in c_0$, where $c_0$ is the Banach space of sequences converging to $0$, endowed with the supremum norm. The topological dual of $c_0$ is $\ell^1$, and by the Banach-Steinhaus theorem, a sequence $(\mu_n)$ such that
$$\lim_{N\to\infty} \sum_{n = 1}^N \mu_n\cdot r_n$$
exists for all $r\in c_0$ belongs to $\ell^1$.
Conversely, it is elementary to see that all sequences $(\lambda_n)$ of bounded variation have the desired property.
Comment: I don't know the Banach Steinhaus theorem neither the topological dual, can you be more precise or give reference please. In fact I just discovered the theorem and don't know how to apply it in this case.
Comment: Have you any background in functional analysis? It's going to be a lot to explain if not.
Comment: Just a little bit, I've seen the Baire's theorem. I understand the proof of Banach Steinhaus and I know what is a dual in linear algebra
Comment: Then we should be close to home. The topological dual, or continuous dual, of a topological vector space $X$ is the vector space of _continuous_ linear functionals on $X$. If you understand the proof of Banach-Steinhaus, you probably know and have understood that for a normed space $X$ we have the norm $\lVert \varphi\rVert = \sup \{ \lvert \varphi(x)\rvert : x\in X,\, \lVert x\rVert \leqslant 1\}$ on the topological dual. Is that all clear so far, or is there something new (beyond terminology) that needs further explanation?
Comment: This is clear I am friendly with operator norms
Comment: Hum.. I see what is your point, you used Banach Steinhaus for the continuity ! Clever !
Comment: Good. Next we have the identification between $\ell^1$ and $c_0'$ [or $c_0^{\ast}$, the notation for dual spaces is not uniform]. On the one hand, for $\xi \in \ell^1$ and $x\in c_0$, we know that $\sum \xi_n\cdot x_n$ converges absolutely, and thus $\varphi_{\xi} \colon x \mapsto \sum \xi_n \cdot x_n$ defines a linear functional on $c_0$. We have $$\lvert \varphi_{\xi}(x)\rvert \leqslant \sum \lvert \xi_n\rvert\cdot \lvert x_n\rvert \leqslant \sum \lvert\xi_n\rvert \cdot \lVert x\rVert_{c_0} = \lVert\xi\rVert_{\ell^1}\cdot \lvert x\rVert_{c_0},$$ so $\varphi_{\xi}$ is continuous with norm …
Comment: Can you give me a good reference for Banach analysis (I mean functional analysis and stuff like the duality) it would be so nice !
Comment: @M.LTA There are lots of good references around, but of course tastes differ, so what's good for one need not be good for all. I like Rudin's _Functional Analysis_, and _Introduction to Functional Analysis_ by Meise and Vogt is also a great book. But before spending a lot of money, I'd recommend going to the nearest university library and looking at the books on functional analysis they have. Spend some time looking whose style you like.
Answer: If $\lambda_n$ is not bounded consider the sequence
$$a_n=\begin{cases}{}\sum_{j=p}^q\frac1{j^2}&\text{ if }\lambda_n<p\le q\le\lambda_{n+1}\\0&\text{ otherwise}\end{cases}$$
Comment: in the future, use `\begin{array}{}...\end{array}` with the "extra" `{}` there.  Or, use the `\begin{cases}... \end{cases}` environment
Comment: Thank you. I could not remember the keywotd cases.


Predicting tree structure

Question: This topic is actually rather hard to google for as 'tree' has been overloaded in this domain to refer to decision trees.
I'd be interested in having a learning algorithm produce code, such as used in Microsoft Power BI's feature to query databases using natural language ('Q&A', formerly 'InfoNav').
Evidently, natural language and database queries can both be expressed as text, so we have a good answer: recurrent neural networks.
However, if we take at SQL queries for one, then intuitively the actual prediction job can be simplified if we'd look at their AST representation rather than their textual one.
If we were to predict an AST representation, language keywords would suddenly no longer clog up the output vector to be predicted, as we could use the BNF describing the language and have the decisions at each node be represented as an integer or the like, along with other info (e.g. the content of number/string literals).
Is there a standard way to approach this? What are best practices here?
Wikipedia has an article on structured prediction, but obviously it's based on theory and academics, and even articles featured are fairly old (for ML), so I'm inclined to think it may not necessarily tell me much about current best practice, if any...
Comment: This is way out of my experience, but a quick search suggests [this](https://scholar.google.com/scholar?cluster=8781853956244507565) might be relevant? (as a more specific and recent article that is well cited, rather than an answer per se.)
Comment: Rather than recurrent, see *recursive* neural networks. The Wikipedia intro:

`A recursive neural network (RNN) is a kind of deep neural network created by applying the same set of weights recursively over a structure, to produce a structured prediction over variable-size input structures, or a scalar prediction on it, by traversing a given structure in topological order. RNNs have been successful for instance in learning sequence and tree structures in natural language processing, mainly phrase and sentence continuous representations based on word embedding.`
Comment: Thanks guys, looks like recursive nets do indeed seem the answer. It looks like we may have a good implementation in [TensorFlow Fold](https://github.com/tensorflow/fold). If either of you would like to post this as an answer I'll gladly accept.
Comment: in retrospect, genetic programming, a type of evolutionary algorithm, is also relevant here.
Answer: I know its too late to answer, but still find below:
I think you are looking for Natural language to SQL statement kind of problem statement, there are few solutions developed in last few months listed below:

SEQ2SEQ method for SEQ2SQL
SQLNET  https://arxiv.org/pdf/1711.04436.pdf

few more:  https://github.com/sriniiyer/nl2sql
Enjoy!

Predicting tree structure


Decoding ssl packets with cipher TLS_ECDHE_RSA in wireshark

Question: I am trying to decode ssl packets in a packet capture using wireshark.
I am able to successfully decode the packets with server key when the
cipher selected by the server during TLS handshake is TLS_RSA_WITH_AES_256_CBC_SHA256.I just mention the server ip/port/protocol(http)/server.key in edit->preferences->Protocols->ssl.
But it doesnot work when the cipher used is TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
I am using Wireshark Version 2.0.2.
Is there any other way to decode ?
Answer: The answer to your question is

No, because of ECDHE_RSA.

Now let us see why this is so. Let's look at the entire ciphersuite specification TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 in detail:

TLS - the protocol
ECDHE_RSA - authentication and key exchange algorithms
WITH_AES_128 - the encryption/decryption algorithm
GCM - the mode used for scrambling the data so it can be securely used with the algorithm
SHA256 - message authentication code algorithm

The key exchange algorithm is specifying how keys for the bulk encryption/decryption cipher are exchanged. And there is something special about the Diffie-Hellman key exchange used in ECDHE_RSA:

DHE_RSA offers something known as Perfect Forward Secrecy, a pompous name for the following property: if your server gets thoroughly hacked, to the point that the attacker obtains a copy of the server private key, then he will also be able to decrypt past TLS sessions (which he recorded) if these sessions used RSA, while he will not be able to do so if these sessions used DHE_RSA.

 stolen from an answer on security.SE
In other words, with (EC)DHE, the AES key used for encryption and decryption cannot be retrieved from the TLS ciphertext conversation, not even if you have the server's private key.
This is different when solely relying on RSA for key exchange: in this operation mode, the bulk cipher key to be used is generated by the client, RSA-encrypted with the server's public key and sent to the server. If an eavesdropping third party has the server's private key, it simply can decrypt the RSA ciphertext of the key exchange, get at the bulk cipher key and decrypt eveything else. This is exactly what Wireshark is doing when decoding a TLS stream for you.
So, what works for RSA-based key exchanges, won't do for DHE-based ones.
Comment: Wireshark since 1.6 (about 5 years ago) in addition to akRSA-using-serverkey can _also_ decrypt SSL/TLS using per-session premaster or master secret extracted from either endpoint. Firefox/NSS and Chrome can do this using SSLKEYLOGFILE; other programs vary, and Q didn't mention any programs. See https://security.stackexchange.com/questions/35639/decrypting-tls-in-wireshark-when-using-dhe-rsa-ciphersuites (but +1 for a wabbit supporting a bear :)
Comment: @dave_thompson_085 I took the question as one from a server admin looking at existing packet captures trying out to figure what went wrong. But thank you for bringing in this additional aspect. Even without control over the clients and not pushing the server-side ability to export master keys, for new captures he might modify his web server infrastructure and decrypt all communications as a man-in-the-middle.


Comparing Page.User.Identity.Name to value in sql Table

Question: First, I am SO sorry if the answer is out there. I've looked and looked and feel this is such a simple thing that it should be obvious.
I'm wanting to make sure only the person who added an event can modify it. Simple!
I already have a datasource that has event_added_by as a data point. It is populating a FormView.
       SelectCommand="SELECT * FROM [tbl_events] WHERE ([event_ID] = @event_ID)"

And I have Page.User.Identity.Name.
How do I compare the two? I can't pull the value from the label in the FormView so I need to find another way.
    if (!IsPostBack)
    {
        string uname = Page.User.Identity.Name;
        string owner = ""// this is where I need to grab the value from dsEvents;

        if (uname != owner)
        {
            //Send them somewhere saying they're not allowed to be here
        }

    }

TIA for any help!
Answer: Maybe I'm misunderstanding what you're already storing the name of who created the event in the table tbl_events and with your select all sentence you're bringing back that information also, so why don't compare that? The value returned from your select command specific column directly with your user name?
Comment: I know. It should be simple. How do I do it? Give me the code. I think I'm having tunnel vision and just don't see it. I'm missing something that's so easy, I'm sure.
Comment: Then put the structure of the `tbl_events`


RavenDB: How to do a simple map/reduce aggregation

Question: Ok given a collection of documents like this:
{
  "Name": "A",
  "Price": 1.50
}

How do I perform a simple aggregation on the prices in the list? I don't want to perform any grouping, just a simple scalar result.
ie. sum, avg etc
I have tried both of the following without success:
Map only:
for doc in docs
select new { sumPrices = Sum(d => d.Price) }

and
Map:
for doc in docs
select new { price = d.Price }

Reduce:
for result in results
select new { sumPrices = Sum(result) }

Answer: This should do the trick.
Map:
from doc in docs.Products
select new { Name = "Total", Total = doc.Price }

Reduce:
select new
{
    Name = g.Key,
    Total = g.Sum(x => (double)x.Total)
}

Each doc goes through the Map, and the aggregation happens in the Reduce.  But the schema coming out of the Map still needs to match your result. The "Total" for each document is just its Price.  These all then get summed in the reduce.
The Name property is kind of useless, its just there to give the reduce something to group every single document on.
Answer: Here's what I came up with.
Map:
from doc in docs
where doc["@metadata"]["Raven-Entity-Name"] == "Books"
select new { Name = "Total", Price = doc.Price };

Reduce:
from result in results
group result by result.Name
into g
select new { Name = g.Key, Price = g.Sum(x => x.Price) }

However, I was only able to get this to work if I changed the price to an integer.  So my two docs look like this:
{
    "Name":"B",
    "Price":4
}
{
    "Name":"A",
    "Price":10
}

And my JSON output looks like this:
{"Results":[{"Name":"Total","Price":"14","Price_Range":"14"}],"IsStale":false,"TotalResults":1}

Obviously, changing the price to integers is not the solution.  It may be a bug in RavenDB, but I'm pretty new to it myself, so I'm hoping it's just the way I'm doing my Sum() or the way that the data is represented in the document.


Show is a continuous linear operator

Question: I am reading the book introduction to functional analysis by Christian Clason. I need help with the problem 4.2 from the book:
Let $T:C[a, b] \rightarrow C[a, b],\ [Tx](t)=tx(t) \quad \forall t \in [a, b]$

Show T is a continuous linear operator
Calculate $\|T\|$
Show or give a counterexample for the closedness of ranT

What I have done:

(i) linear: $[T(\lambda x + y)](t) = t(\lambda x(t) + y(t)) = t\lambda x(t)+ ty(t) = [T(\lambda x)](t) + [Ty](t)$.

(ii) How can I show it is continuous. My idea was: Since $[a, b]$ is compact, it follows $x(a) \leq x(t) \leq x(b),\ \forall t \in [a, b]$. Take $x_0 \in C[a, b]$. $\forall \epsilon > 0 \exists \delta>0 : \|x - x_0\| < \delta \Rightarrow \|Tx(t) - Tx_0(t)\| = \|tx(t) - tx_0(t)\| = |t| \|x - x_0\| < |t| \delta = \epsilon$.
We can choose $\delta = \epsilon / |t|$. This proves T is continuous.

We know $\|T\| = \sup_{x \in C[a, b]} \frac{\|Tx\|}{\|x\|}$
$\|Tx\| = \sup_{t \in [a, b]} |tx(t)| \leq \sup_{t \in [a, b]} |t|\|x\| \leq \sup_{t \in [a, b]}|t| |x(b)|$.
Let $x(t) = 1 \in C[a, b]$, then $\|x\|=1$ and $\|Tx\| = \sup_{t \in [a, b]} |tx(t)| = \sup_{t \in [a, b]} |t|$

Is it correct what I have done so far?

I have no idea
Comment: Also, you can show continuity by showing boundedness. Or are you unfamiliar with this equivalence?
Comment: The norm you are working with is the sup norm, right?
Comment: @Keen-ameteur Yes, the norm I am working with is the sup norm
Yes, I also used the equivalence of boundedness to show continuity:
$\|Tx\| = \|tx(t)\| = |t| \|x(t)\| \leq |t| x(b) < \infty $
Comment: Hint for 3: $T$ is injective, so by open mapping theorem, if $ran(T)$ is closed then $T$ admits a bounded inverse (defined on the range). What is this inverse? Can it be bounded if $0 \in [a, b]$?
Comment: Concerning $3$ and the casel $0\in [a,b]$   show that $\sqrt{|t|}$ does not belong to the range but can be approximated by the elements in the range, by applying the Weierstrass approximation theorem or just by indicating the approximating sequence. For example if $a=0$ and $b=1$ you may take the MacLaurin series of $\sqrt{1-x}$ and plug in $x=1-t.$ In this way you may avoid applying advanced theorems.
Answer: Assume $0\in [a,b].$ The range of $T$ consists of all functions of the form $tx(t),$ where $x\in C[a,b].$ On the other hand the closure of the range of $T$ consists of all functions in $C[a,b],$ which vanish at $t=0.$ Indeed, if $x(0)=0,$ then by the Weierstrass approximation theorem there exists a sequence of polynomials $q_n(t)$ such that $q_n(t)\rightrightarrows x(t).$ Then $p_n(t):=q_n(t)-q_n(0)\rightrightarrows x(t),$ and $p_n$ belong to the range of $T.$
Therefore the function $\sqrt{|t|}$ does not belong to the range of $T$ but belongs to the closure of the range.
Remark For $\sqrt{|t|}$ the sequence $p_n(t)$ can be indicated explicitly by applying the MacLaurin expansion of $\sqrt{1-u}.$

Show is a continuous linear operator


foward declaring class in namespace throwing compiler error

Question: namespace chk{

class Car;
        Car abc()
        {
                return Car();
        }

class Car
{
        private:
                int sides;

        public:
                Car()
                {
                        std::cout<<"\ndefault called constructor";
                }
                Car(int nsides)
                {
                        std::cout<<"\ncalled constructor";
                        sides=nsides;
                }

                ~Car()
                {

                        std::cout<<"\nDeleting objext";
                }

};

       /* Car abc()
        {
                return Car();
        }*/
}

I am getting following error for above code :-
check.cpp: In function 'chk::Car chk::abc()':
check.cpp:25: error: return type 'struct chk::Car' is incomplete
check.cpp:27: error: invalid use of incomplete type 'struct chk::Car'
check.cpp:24: error: forward declaration of 'struct chk::Car'

Now when uncomment the below abc() and comment above abc() then it works fine.
Why c++ is not allowing me to forward declare class inside namespace?
Comment: It allows you to forward declare. The problem is that `abc()` needs the class definition.
Comment: But if i am forward declaring the class.compiler should know that the definition exits somewhere in code.
Comment: But it needs more than the declaration. See my answer.
Answer:
Why c++ is not allowing me to forward declare class inside namespace?

What C++ does not allow is to have a function such as
Car abc()
{
    return Car();
}

without class Car's definition. This is needed because a) the size of a Car object is required, and b) there is a call to the default constructor of the class. Without the class definition, there is no way to know whether the constructor exists or not.
Answer: The problem is that your abc() function needs the complete definition of Car.
Car abc() { return Car(); }

Not least here is the requirement that it has to know the definition so it can determine which constructor this would resolve to.
Forward declaration only covers cases where you need a pointer or a reference to a type, it does not cover cases where you need to resolve internal details.
Figuring out which constructor to use is an internal detail. In addition, the compiler also needs to know how big a "Car" object is going to be in order to return one as you are returning it by value.
One way to solve this would be to forward declare the function:
class Car abc();

class Car { ... };

Car abc() { return Car(); }


Automorphism group of the Leech lattice

Question: I have seen that the automorphism group of the Leech lattice is the Conway group $\ Co_0$, which is a finite group.
But for example the lattice $\mathbb Z^n$ has an infinite automorhism group. Can anyone explain me, what is the difference between these two lattices, that results in the (in)finiteness of their respective automorphism  groups?
Comment: Here we want automorphisms $\Lambda = A \mathbb{Z}^n \mapsto AB \mathbb{Z}^n$ (for some $B \in SL_n(\mathbb{Z})$) preserving $\| \lambda \|^2= \| A v \|^2= v^T A^T A v$ ie. preserving the Gram matrix $A^T A \mapsto B^T A^T A B$. How to compute it ? We can take a basis of $\Lambda$ and send each basis element to an other element of $\Lambda$ of same $\|.\|^2$ (finite many) and test if it generates an isometry (so the isometry-automorphism group is always finite for any lattice)
Answer: You are confusing isometries of a lattice, and isometries fixing
the identity. Each lattice in $\Bbb R^n$, considered as a point set, has infinitely
many isometries, since each translation by a lattice vector is
an isometry.
What is more interesting is studying the isometries that fix the origin.
They form a finite group, always non-trivial, as the map $x\mapsto-x$
is a (central) isometry. The first Conway group is obtained by taking
the group of Leech lattice isometries fixing $0$, and factoring out the two-element group generated by $x\mapsto-x$.
In $\Bbb Z^n$ the group of isometries fixing $0$ has $2^nn!$ elements,
and are the monomial matrices with nonzero entries either $1$ or $-1$.
Answer: I may be wrong, but I suspect that here we consider automorphisms of a lattice as subsets of a Euclidean space, and we thus assume an automorphism to also be an isometry. Unless I'm wrong you were thinking about automorphisms of abelian groups. But, as abelian groups the Leetch lattice and $\Bbb{Z}^{24}$ are isomorphic. They differ only in their metric properties. In my opinion this strongly points at the groups of isometries being relevant here. To get finite groups we also assume that the origin is a fixed point.
In that interpretation an automorphism of $\Bbb{Z}^n$ is fully determined by its action on the short length 1 vectors. Therefore the automorphisms of $\Bbb{Z}^n$  form the group $C_2\wr S_n$ of signed permutations (of coordinates).

Automorphism group of the Leech lattice


Alternative to block bootstrap for multivariate time series

Question: I currently use the following process for bootstrapping a multivariate time series in R:

Determine block sizes -- run the function b.star in the np package which produces a block size for each series
Select maximum block size
Run tsboot on any series using the selected block size
Use index from bootstrap output to reconstruct multivariate time series

Someone suggested using the meboot package as an alternative to the block bootstrap but since I am not using the entire data set to select a block size, I am unsure of how to preserve correlations between series if I were to use the index created by running meboot on one series. If anyone has experience with meboot in a multivariate setting, I would greatly appreciate advice on the process.
Answer: First, I want to highly recommend the maximum entropy bootstrap (meboot). I abandoned the block bootstrap in favor of meboot, and I've been very pleased with the results. The algorithm does not use blocking in any way, it does not require stationarity, and yet it incorporates the correlation structure of the data. It's cool.
Second, while I confess that I've never done a multivariate bootstrap using meboot, I believe you can recast your time series data as panel data and use the meboot.pdata.frame function to perform an essentially multivariate bootstrap.
Comment: I think the function is meboot.pdata.frame.
Comment: Yikes! Thanks, P.P. Yes, I misspelled the function, and the correct name is meboot.pdata.frame. Sorry 'bout that.
Comment: I came across this thread and got interested in the ME bootstrap.  Playing with it a bit, I found that it replicated time series quite closely -- not a lot of variability in the bootstrap DGP.  Digging further, I found the following paper by Davidson that includes a critique of the ME Bootstrap:  www.monticini.eu/wp/rdavidson.pdf.  Not sure if there has been any rebuttal of it, but given my own simulation results, I'd be hesitant to use it.
Comment: @generic_user Thank you for that reference! I read it with great interest. I, too, have noted the lack of variability in the bootstrap replicates under certain circumstances. I'm not yet convinced that, as a result, the ME bootstrap is never valid. But the paper is sobering. More investigation is needed.