How to train the Model in Time Series with Holiday, Weekends

Question: I am working on time series to forecast the number of inbound calls for next 1 month on a daily basis.
I built a model using auto.arima and forecasted. My forecasting data is showing gradually increasing no. of calls irrespective of holiday or weekend.
(I have data for 2 months Aug-1-2016 to Dec-31- 2016. Here I want to forecast for next 1 month data.)
Historical data is saying that there are fewer calls on weekends and holidays (for instance week days average no. calls per day: 1200, weekend average no. of calls: 700).
Comment: The question should really be, how to *build* a model rather than how to *train* a model. You have trained a model and you see it does poorly, and this is because it is poorly designed, not poorly trained. You could consider adding seasonal dummies or Fourier terms (via the `xreg` argument in `auto.arima`) or running a Seasonal ARIMA model (also via `auto.arima` if you pass your series as a seasonal `ts` object to it).
Answer: http://autobox.com/cms/index.php/afs-university/intro-to-forecasting/doc_download/53-capabilities-presentation starting at slide 49 may be of some help to you. What you should do is totally ignore advice regarding ARIMA approaches as they are simply rear-window driving analogues and use (the front window ) causal structures such as day-of-the-week, week-of-the-month , month-of-the-year, day-of-the-month , week-of-the month etc... while incorporating any additionally identified latent variables such as level shifts, local time trends etc. Given your paucity of data some of which I mentioned is evidently inestimable but should be an inspiration for you to collect more data , possibly then identifying long-weekend effects, lead and lag effects around holidays etc. all while adjusting for anomalous data points.
As one of my gurus pointed out recently .....
"ARIMA, for example is fine for some kinds of data, okay for others and poor for still others; the same could be said of essentially anything else. There's no magic pill. – Glen_b  "
Comment: If I can be of further help please let me know.
Comment: Thank you Sir, Sure I will approach you if I want any further help.


Open image via DIV data

Question: Again I ask your help, I have an ftp where some music covers that I want to use http://inlivefm.6te.net/capas/.
Also I have a javascript that gives me the data of the cover link: link that he is now to provide
http://inlivefm.6te.net/capas/I NEED YOUR LOVE.jpg
 the last song played
I use JavaScript to provide the covers

Knowing that div gives me the link of the cover, wanted to open the through image of the data provided

The example I want is something like this:

I'm trying to do this but I am not able to because the image does not open, so I came to ask your help.
Thank you so much!
Comment: You have an IMG tag with a DIV tag inside. Was this on purpose?
HTML code is not a valid source for an image, you should give an ID to your IMG and change source with Javascript.
Comment: @goncalopinto The goal was that the div provides the link is the image opened up, it seems it was not like he was doing
Comment: Do you mean something like  ?
Comment: No, that does not work at all. You need something like `$('.cancion').html('');`
Comment: @ClaudioKing  yes, DIV cancion behind the cover link and what I wanted was to open the DIV link it to have the cover
Comment: @JohannesJander
Even changing to like you said, the DIV recognizes jpg, but does not open the image
Comment: If I can understand you want the image to be a link and open in fullsize when you click it? If that's the case then you have to surround your IMG tag with an A tag.
Answer: I believe you want an image, which when clicked on takes you to another resource; done like this:

Clicking on image.URL  will take you to  resource.URL
Comment: What I wanted even though she soon opened without having to click on anything, but as I said I put the div in img leads nowhere
Comment: No, you need                                                 **src="http://inlivefm.6te.net/capas/I NEED YOUR LOVE.jpg"**
Comment: Yes, but as the xml will be active the cover will always be changing, so the importance of DIV, so it does not exchange cover and is always the same
Comment: So, you want a DIV with an image inside and make it behave as a link but without using IMG and A tags? Only the DIV? Is that it?
Comment: @goncalopinto he could use a div with a **background-image** specified in CSS, a separate class for each div !
Comment: @Arif Burhan , that's why I asked, it can be done in different ways, wrapping a DIV with a background image in a A tag it's probably the one he is looking for, of create an event in JavaScript for the DIV.
Comment: @goncalopinto I just want to open a page to appear the music cover, this is the link where you want to appear http://inlivefm.6te.net/current.php ,as you can see I apply the code and am trying to immediately open without be to click on anything.
Comment: A new webpage opens when you hover the mouse? Or an overlaying box with the image inside? Please clarify this so I can help you.
If it's hard for you to explain exaclty what you want, please include images of something similar and/or include your own drawings explaining better your idea.
Comment: I have a hover on text example - done with CSS3 and HTML5 alone **http://www.wisephoenix.org/examples/html5/RayHarryhausen3.htm** --- pink left sidebar.
Comment: @goncalopinto On page I have provided you this Javascript that produces information that is provided through   this information refers to the last cover that touched xml http://inlivefm.6te.net/AirPlayHistory. xml and fTP where estam the covers is this: http://inlivefm.6te.net/capas/
In this case the information is div this link http://inlivefm.6te.net/capas/I NEED YOUR Love.jpg
Comment: @goncalopinto  but as the cover will always be changing (when you spend being active xml) thought using this form  " /> so that the cover is open as this link http://inlivefm.6te.net/exemplo.php and do the same with the other cases of automatic way, but I'm not able to open the covers.

Open image via DIV data


Unresolved reference: firebasemessaging

Question: Getting this error i have try to fixed this ref:Application.kt: Unresolved reference: firebasemessaging but didnt work so i need to posted again i also tried to delete the application.kt file but didnt work. If anyone know the solution please let me know what i am doing wrong so i can learn to not repeat these again
<code> ext.kotlin_version = '1.4.32'
    dependencies {
            classpath 'com.android.tools.build:gradle:3.6.4'
            classpath 'com.google.gms:google-services:4.3.3'
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        }

package com.godatu.dance

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService

class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {

    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this)
    }

    override fun registerWith(registry: PluginRegistry?) {
        if (registry != null) {
            FirebaseCloudMessagingPluginRegistrant.registerWith(registry)
            FlutterLocalNotificationPluginRegistrant.registerWith(registry)
            FlutterPathProviderPluginRegistrant.registerWith(registry)
        }
    }

}

enter code here
   [   +2 ms] e: C:\Users\Admin\Desktop\Android\godatu-App\android\app\src\main\kotlin\com\godatu\dance\Application.kt: (6, 27): Unresolved reference: firebasemessaging
    [   +3 ms] e: C:\Users\Admin\Desktop\Android\godatu-App\android\app\src\main\kotlin\com\godatu\dance\Application.kt: (7, 27): Unresolved reference: firebasemessaging
    [        ] e: C:\Users\Admin\Desktop\Android\godatu-App\android\app\src\main\kotlin\com\godatu\dance\Application.kt: (12, 9): Unresolved reference: FlutterFirebaseMessagingService
    [        ] e: C:\Users\Admin\Desktop\Android\godatu-App\android\app\src\main\kotlin\com\godatu\dance\Application.kt: (20, 7): Redeclaration: FirebaseCloudMessagingPluginRegistrant
    [        ] e: C:\Users\Admin\Desktop\Android\godatu-App\android\app\src\main\kotlin\com\godatu\dance\Application.kt: (26, 13): Unresolved reference: FirebaseMessagingPlugin
    [        ] e: C:\Users\Admin\Desktop\Android\godatu-App\android\app\src\main\kotlin\com\godatu\dance\FirebaseCloudMessagingPluginRegistrant.kt: (5, 27): Unresolved reference: firebasemessaging
    [        ] e: C:\Users\Admin\Desktop\Android\godatu-App\android\app\src\main\kotlin\com\godatu\dance\FirebaseCloudMessagingPluginRegistrant.kt: (8, 7): Redeclaration: FirebaseCloudMessagingPluginRegistrant
    [        ] e: C:\Users\Admin\Desktop\Android\godatu-App\android\app\src\main\kotlin\com\godatu\dance\FirebaseCloudMessagingPluginRegistrant.kt: (17, 17): Unresolved reference: FirebaseMessagingPlugin
    [  +84 ms] FAILURE: Build failed with an exception.
    [        ] * What went wrong:
    [        ] Execution failed for task ':app:compileDebugKotlin'.
    [        ] > Compilation error. See log for more details
    [        ] * Try:
    [        ] Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
    [        ] * Get more help at https://help.gradle.org
    [        ] BUILD FAILED in 27s
    [        ] 399 actionable tasks: 5 executed, 394 up-to-date
    [{"event":"app.progress","params":{"appId":"82f5465d-087d-4b13-8c4a-7ae1698e399b","id":"0","progressId":null,"finished":true}}]
    [+5408 ms] Exception: Gradle task assembleDebug failed with exit code 1
    [   +4 ms]
               #0      throwToolExit (package:flutter_tools/src/base/common.dart:10:3)
               #1      RunCommand.runCommand (package:flutter_tools/src/commands/run.dart:550:9)
               <asynchronous suspension>
               #2      FlutterCommand.verifyThenRunCommand (package:flutter_tools/src/runner/flutter_command.dart:1157:12)
               <asynchronous suspension>
               #3      FlutterCommand.run.<anonymous closure> (package:flutter_tools/src/runner/flutter_command.dart:1009:27)
               <asynchronous suspension>
               #4      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
               <asynchronous suspension>
               #5      AppContext.run (package:flutter_tools/src/base/context.dart:149:12)
               <asynchronous suspension>
               #6      CommandRunner.runCommand (package:args/command_runner.dart:197:13)
               <asynchronous suspension>
               #7      FlutterCommandRunner.runCommand.<anonymous closure> (package:flutter_tools/src/runner/flutter_command_runner.dart:278:9)
               <asynchronous suspension>
               #8      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
               <asynchronous suspension>
               #9      AppContext.run (package:flutter_tools/src/base/context.dart:149:12)
               <asynchronous suspension>
               #10     FlutterCommandRunner.runCommand (package:flutter_tools/src/runner/flutter_command_runner.dart:234:5)
               <asynchronous suspension>
               #11     run.<anonymous closure>.<anonymous closure> (package:flutter_tools/runner.dart:64:9)
               <asynchronous suspension>
               #12     run.<anonymous closure> (package:flutter_tools/runner.dart:62:12)
               <asynchronous suspension>
               #13     AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
               <asynchronous suspension>
               #14     AppContext.run (package:flutter_tools/src/base/context.dart:149:12)
               <asynchronous suspension>
               #15     runInContext (package:flutter_tools/src/context_runner.dart:73:10)
               <asynchronous suspension>
               #16     main (package:flutter_tools/executable.dart:90:3)
               <asynchronous suspension>

    [{"event":"app.stop","params":{"appId":"82f5465d-087d-4b13-8c4a-7ae1698e399b"}}]
    [  +18 ms] "flutter run" took 36,338ms.
    [{"id":0,"error":"app '82f5465d-087d-4b13-8c4a-7ae1698e399b' not found","trace":"#0      AppDomain.stop (package:flutter_tools/src/commands/daemon.dart:698:7)\n#1      Domain.handleCommand.<anonymous closure> (package:flutter_tools/src/commands/daemon.dart:217:34)\n#2      new Future.sync (dart:async/future.dart:218:31)\n#3      Domain.handleCommand (package:flutter_tools/src/commands/daemon.dart:215:5)\n#4      Daemon._handleRequest (package:flutter_tools/src/commands/daemon.dart:141:28)\n#5      _rootRunUnary (dart:async/zone.dart:1362:47)\n#6      _CustomZone.runUnary (dart:async/zone.dart:1265:19)\n#7      _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)\n#8      _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)\n#9      _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)\n#10     _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)\n#11     _MapStream._handleData (dart:async/stream_pipe.dart:218:10)\n#12     _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)\n#13     _rootRunUnary (dart:async/zone.dart:1362:47)\n#14     _CustomZone.runUnary (dart:async/zone.dart:1265:19)\n#15     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)\n#16     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)\n#17     _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)\n#18     _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)\n#19     _WhereStream._handleData (dart:async/stream_pipe.dart:195:12)\n#20     _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)\n#21     _rootRunUnary (dart:async/zone.dart:1362:47)\n#22     _CustomZone.runUnary (dart:async/zone.dart:1265:19)\n#23     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)\n#24     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)\n#25     _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)\n#26     _SinkTransformerStreamSubscription._add (dart:async/stream_transformers.dart:63:11)\n#27     _EventSinkWrapper.add (dart:async/stream_transformers.dart:13:11)\n#28     _StringAdapterSink.add (dart:convert/string_conversion.dart:238:11)\n#29     _LineSplitterSink._addLines (dart:convert/line_splitter.dart:155:13)\n#30     _LineSplitterSink.addSlice (dart:convert/line_splitter.dart:130:5)\n#31     StringConversionSinkMixin.add (dart:convert/string_conversion.dart:163:5)\n#32     _SinkTransformerStreamSubscription._handleData (dart:async/stream_transformers.dart:111:24)\n#33     _rootRunUnary (dart:async/zone.dart:1362:47)\n#34     _CustomZone.runUnary (dart:async/zone.dart:1265:19)\n#35     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)\n#36     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)\n#37     _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)\n#38     _SinkTransformerStreamSubscription._add (dart:async/stream_transformers.dart:63:11)\n#39     _EventSinkWrapper.add (dart:async/stream_transformers.dart:13:11)\n#40     _StringAdapterSink.add (dart:convert/string_conversion.dart:238:11)\n#41     _StringAdapterSink.addSlice (dart:convert/string_conversion.dart:243:7)\n#42     _Utf8ConversionSink.addSlice (dart:convert/string_conversion.dart:317:20)\n#43     _Utf8ConversionSink.add (dart:convert/string_conversion.dart:310:5)\n#44     _ConverterStreamEventSink.add (dart:convert/chunked_conversion.dart:72:18)\n#45     _SinkTransformerStreamSubscription._handleData (dart:async/stream_transformers.dart:111:24)\n#46     _rootRunUnary (dart:async/zone.dart:1362:47)\n#47     _CustomZone.runUnary (dart:async/zone.dart:1265:19)\n#48     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)\n#49     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)\n#50     _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)\n#51     _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:733:19)\n#52     _StreamController._add (dart:async/stream_controller.dart:607:7)\n#53     _StreamController.add (dart:async/stream_controller.dart:554:5)\n#54     _Socket._onData (dart:io-patch/socket_patch.dart:2144:41)\n#55     _rootRunUnary (dart:async/zone.dart:1370:13)\n#56     _CustomZone.runUnary (dart:async/zone.dart:1265:19)\n#57     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)\n#58     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)\n#59     _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)\n#60     _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:733:19)\n#61     _StreamController._add (dart:async/stream_controller.dart:607:7)\n#62     _StreamController.add (dart:async/stream_controller.dart:554:5)\n#63     new _RawSocket.<anonymous closure> (dart:io-patch/socket_patch.dart:1680:33)\n#64     _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:1192:14)\n#65     _microtaskLoop (dart:async/schedule_microtask.dart:40:21)\n#66     _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)\n#67     _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:120:13)\n#68     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:185:5)\n"}]
</code>
Answer: You don't need to take care of registrant in flutter v2. It will automatically handles it by itself. Hence you don't need to include Application class.
Comment: works... i deleted the Application.kt and remove the reference in the manifest.xml ( android:name=".Application")
Answer: I'm guessing you're on an older version of Firebase core and messaging and any other firebase plugins you have. I just went through a bunch of similar headaches, tried all those solutions, went through a bunch of github threads, nothing worked.
What did work, was forcing myself to upgrade to null safety just so I could use all the up to date firebase plugins. After that, FCM works like a charm and you don't have to touch your Kotlin/Java file.
When I first tried to implement FCM, I had ended up with a chain of firebase dependency conflicts with firebase storage/analytics etc...that wasn't resolved until I was down to versions 1-2 years old on some of those plugins.
Now with all these current versions
<code>  firebase_analytics: ^8.0.0
  firebase_core: ^1.0.3
  firebase_messaging: ^9.1.1
  firebase_storage: ^8.0.3
</code>
My Kotlin file is untouched and background notifications don't crash my app.
So it may not be the answer you're looking for, and perhaps not all your dependencies have upgraded to null safety and you can't upgrade anyway, but it's something to consider.
Because if you do upgrade to all the current versions (and Android Embedding if your app is still on V1), then you just follow the FlutterFire FCM Guide and it all just works with very minimal setup.
It appears the Google team did a lot of work to make it a smoother process because people were justifiably pissed off that it was such a messy process getting 2 Google products to play nicely together.

Unresolved reference: firebasemessaging


Powershell find webserver certificate expiration with context in URL

Question: need help with Powershell.
We need to find server certificate expiration using powershell. These are weblogic console Urls. The URLs have context and port like https://server:7020/context .  If I browse URL without context, I get error -
Error 404--Not Found
From RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1:
10.4.5 404 Not Found

I have tried with following code -
Try{
$Conn = New-Object

System.Net.Sockets.TcpClient($WebsiteURL,$WebsitePort)

Try {
$Stream = New-Object

System.Net.Security.SslStream($Conn.GetStream(),$false, {

param($sender, $certificate, $chain, $sslPolicyErrors)
return $true
})
$Stream.AuthenticateAsClient($CommonName)

If I try a server without context it gives following error -
A call to SSPI failed, see inner exception.

What are commands and options to query in powershell?
Any help is appreciated.
Comment: The path stem ("context") won't have any bearing on the certificate being presented, so you only need to worry about changing the port - maybe show us an example of what you've tried/failed to do?
Comment: Updated the original post. When tried on browser, do not see a response without a context. Using powershell get above error.
Comment: The error is caused by mismatching TLS versions. Presumably, your server is using TLS 1.2 - set your PS session to match at the start of your script with `[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12`
Comment: Thanks CrookedJ.. The issue was with TLS 1.2. Need to update the script.
Answer: Using Get-RemoteSslCertificate from jstangroome you can simply run the following to return the expiration.
(Get-RemoteSslCertificate -ComputerName server -Port 7020).NotAfter

The Get-RemoteSslCertificate function:
function Get-RemoteSslCertificate {
    # Author: jstangroome https://gist.github.com/jstangroome/5945820
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string]
        $ComputerName,

        [int]
        $Port = 443
    )

    $Certificate = $null
    $TcpClient = New-Object -TypeName System.Net.Sockets.TcpClient
    try {

        $TcpClient.Connect($ComputerName, $Port)
        $TcpStream = $TcpClient.GetStream()

        $Callback = { param($sender, $cert, $chain, $errors) return $true }

        $SslStream = New-Object -TypeName System.Net.Security.SslStream -ArgumentList @($TcpStream, $true, $Callback)
        try {

            $SslStream.AuthenticateAsClient('')
            $Certificate = $SslStream.RemoteCertificate

        } finally {
            $SslStream.Dispose()
        }

    } finally {
        $TcpClient.Dispose()
    }

    if ($Certificate) {
        if ($Certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
            $Certificate = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList $Certificate
        }

        Write-Output $Certificate
    }
}

Comment: Looks good. But does not help if we have to context.
Comment: That's not how HTTPS works, `context` is entirely unnecessary.
Comment: Thanks CrookedJ.. The issue was with TLS 1.2. Need to update the script.


como fazer um login dividido em duas partes?

Question: Oque eu quero fazer é tipo um sistema de login de banco com duas senhas de acesso, a primeira parte ja fiz, então eu queria levar o login a parte 2 onde pede a senha 2 e o nome do usuario.
Caso ele acesse coretamente a parte 1 ele vai para a parte dois com os respectivos dados, mas se ele não tenha feito o login da parte 1 da erro.
Comment: Podes colocar o código que já fizeste? senão é dificil saber o que te está a faltar...
Answer: Estou bem enferrujado com PHP, então tentar exemplificar com um codigo generico aqui...
Acho que o jeito mais interessante seria trabalhando com session
    if(classeDeLogin.validaUsuarioParte1('usuario','senha')
    {
         $_SESSION['login1'] = true;
         //Redireciona para a pagina de login 2
    }

Nessa pagina você poderia fazer o seguinte
    //Verifica se o login parte 1 foi realizado
    if($_SESSION['login1'] == true)
    {
    if(classeDeLogin.validaUsuarioParte2('usuario','senha')
       {
          //Aqui não lembro exatamente o comando, mas a idéia é atribuir null a variável de sessão login1
          $_SESSION['login1'] = null;
          $_SESSION['userLogged'] = true;
          //Redireciona para sua pagina principal

       }
    }
    else
    {
        //Redireciona para pagina de login parte 1
    }

Answer: Bom dia  ,
Após validar o 1 login ,você joga o nome de login dele em uma sessão e redireciona para a tela login2.
Na tela login 2  , no campo login você exibe o nome que esta na sessão e pede para informar a senha . Ao informar a senha você faria uma validação normal igual na etapa 1.Se a verificação na etapa 2 der certo , você redireciona o usuairio para index , senão  , você pode mandar ele de volta para a pagina de login 1 ou para a pagina de login 2 mesmo .


String para Date

Question: Estou criando alguns parsers e estava fazendo uns testes para desenvolver o de Date.
Este código:
value = '2015-12-31 23:16:00'
value = value.replace(/(\d{4}-\d{2}-\d{2}) ?(\d{2}:\d{2})?(:\d{2})?.*/, '$1T$2$3');
value = value.replace(/T$/, '');
value = value.replace(/(:\d{2})$/, '$1Z');

value = new Date(value)

executa corretamente no Firefox, retornando Date 2015-12-31T23:16:00.000Z, contudo no Chrome ele exibe Thu Dec 31 2015 21:16:00 GMT-0200 (BRST)
Além de estarem exibindo diferente, o Chrome abateu duas horas do horário original.
Alguém saberia como posso revolver isto?
Comment: Pelos meus testes não ha problema na hora, é apenas sua exibição que é divergente nos navegadores. Em ambos executando o `getUTCHours()`, me retornou `23`. Assim como nas demais funções.
Comment: sem o 'Z' funcionou corretamente aqui no meu `Chrome`, talvez te oriente em algo http://stackoverflow.com/questions/15109894/new-date-works-differently-in-chrome-and-firefox
Comment: @MaiconCarraro na verdade eu já tinha encontrado esta referencia, do `Z` no final, e estou aplicando ela, se você comentar a minha que tem `value = new Date(value)` o valor exibido no console sera, `"2015-12-31T23:16:00Z"`, contudo ainda permanece uma diferença de duas horas no `Chrome`
Answer: Como o @Guilherme Lautert disse no comentário, nos dois casos retorna o mesmo valor, apenas apresentando-o de forma diferente. O que muda é apenas o fuso horário que foi usado, sendo que GMT-0200 indica duas horas a menos do que a hora atual no meridiano de Greenwich. Exemplo: http://www.donathan.com/dave/m0200.html.
Tente usar
var horarioAtual = date.toLocaleTimeString();

para verificar. É provável que irá retornar o valor correto nos dois casos.

String para Date


Calculating Formula of Line from a Discrete Distribution

Question: Say you have(1,2,3,...,19,20) each with the same probability of occurring (5%). You know the distribution is normal, but you have only a discrete graph of each outcome. We do know, the normal bell curve can be overlayed.
Now, let's say for this example, you know it is normally distributed (maybe not exactly, but very, very close) so you want to apply the normal distribution. Is there any sort of boolean test or anyway of testing a distribution to see if it is normal, Bernoulli, etc, etc, and then applying it?
I am asking because I am a computer programmer looking at stock data for fun from a statistics perspective, and I am trying to apply different distributions to match different sets of data for analysis purposes.
Comment: This doesn't make much sense. If you have "(1,2,3,...,19,20) each with the same probability of occurring (5%)", you have a discrete uniform distribution, which is not remotely like the normal. You generally distinguish between distributions like the normal & the Bernoulli by thinking about what your data are for 10 seconds, not by applying any test.
Comment: ie how do I say, this data is a ______ distribution without eye balling it
Comment: What is the "line" you refer to in your title? How does that relate to the body of your question?
Answer: [The example in your question doesn't make sense; a discrete uniform distribution isn't approximately normal in any reasonable sense of the word.]
There are tests of goodness of fit which can (sometimes) tell you when a distributional model fails to describe data in some way. Quite literally hundreds of them -- and dozens just for the case of normality.
However, it's generally not useful to test for something we know for sure to be false (we can often know before we even see them that our data are not exactly normal, even if the population distribution may be fairly close); in any case it answers the wrong question (a good questions is something like "is this distributional model sufficiently good to be useful for our purposes" which is simply not addressed by a goodness of fit test)
As the famous saying goes, "All models are wrong, some are useful" (actually there's a couple of different versions - a different version of the Box quote is on my profile - but that one will do for now).

ie how do I say, this data is a ______ distribution without eye balling it

In general you can't say it is something, but you can use knowledge of the variable, of the subject area and of the characteristics of distributions to pick models that are likely to be reasonable.
Nothing will tell you the population distribution the data were drawn from is $F_1$ rather than the very similar $F_2$, $F_3$, $F_4$, $...\,$. Even worse, with enough data I may be able to reject every simple distributional model I can think of.
In the absence of rock-solid theory (which still may fail to capture aspects of the entire data generating process by the time the data ends up on your computer) the best you can usually hope to do is identify distributional models that capture the most salient features in a fruitful way.
As gung suggests, you usually choose models by thinking about what you're dealing with (how the characteristics of the situation / data-generating-process / kind of variable you'll observe match up with the characteristics of a distributional model).
If I am dealing with counts or times, say, my first thought won't be the normal distribution but something more directly related to those types of variables (there are several models commonly used for count data, and it's often clear that some of those can be ruled out before you even see the data).
If I know something will be close to normal (though for me this sort of knowledge is fairly rare), then often I'll just use it; it may work just about as well as anything else. However, if I can see that the way it isn't quite normal may be an issue for what I want to do, then I might do something a bit different. For example, if I was just doing a t-test or a regression, being more or less close to normal may often present little problem but if I was (say) interested in computing a conditional tail expectation for a very high quantile, just saying "well that's more or less close to normal" may not be nearly adequate; the behaviour of the extreme tail will matter.
Sometimes you simply have no theory and not enough practical subject area knowledge to choose a model, and then you might begin by (say) looking at some fraction of your data, or in more complicated cases, choosing a convenient model for that portion and examining diagnostics to help choose a better one.
Answer: I think @Glen_b has made excellent points, I want to add (or rephrase):

Normal distribution is not ideal for modelling stock price, unless the time interval is sufficiently small. More commonly (but still not quite correct), the returns of the stock is modelled by log-normal distribution. In any case, stock price exhibits asymmetrical performance.
Generally, you'd only use a distribution test to verify whether the distribution is a reasonable approximation for small sample size.
Furthermore, what statistical method to use is generally pre-defined or known, the problem would be more on how exactly to specify the model. For example, if I have count data and I want to do regression, my first impression would be Poisson GLM or quasi-likelihood methods.


What hypothesis test to use for partially paired non-normal data

Question: I have two groups control and test. For both groups data was collected at two time points : One is Baseline and other End of Study. Data is not normally distributed. However, only 50% of data is available for End of study as compared to baseline.
So to compare my baseline data with End of study data... it is mix of unpaired and paired data and also it is not normally distributed.
I want to know which statistical test can I use?
Comment: [here](https://stats.stackexchange.com/questions/25941/t-test-for-partially-paired-and-partially-unpaired-data) is an answer for the same situation, but normal assumption. Same thinking can be applied
Comment: Possible duplicate of [t-test for partially paired and partially unpaired data](https://stats.stackexchange.com/questions/25941/t-test-for-partially-paired-and-partially-unpaired-data)
Comment: I don't think that's really a duplicate, unless the title of the other question is made more general.
Answer:
Separate the data into 4 groups: Baseline-control, end of study-control, baseline-test, end of study-test. Then check if your measurements are normal distributed or not in each group. If not, try to do some transformations until they look like normal.
Fit a mixed model with baseline vs end of study and control vs test as fixed effect, and the subject specific intercept as random effect.
After model fitting, construct the null hypothesis you want to test.


Jquery Remove php code from string

Question: I have a string that contains php code I am trying to find a way to remove the php code from the string.
text = '<?php // This is a test sample ?> This is a description';
text.replace(/\<\?.*\?\?\>/, "");

I am not the best with regex. Any help is greatly appreciated.
Comment: what's your true goal here? did you write a php app and are wanting to remove unsafe code that is being eval'd by javascript?
Answer: A very naive approach (assuming php code will have no ternary operator, and inner comments will have no question symbol, ;)):
var s = '<?php // This is a test sample ?> This is a description'
s.replace(/<\?php\s*[^\?]+\s*\?>/g, '')
// output: " This is a description"

Answer: the php will execute before the javascript ever gets a chance to do it's thing on the php code.  You can't use javascript to change php code.  (Although it does work the other way around.)

Jquery Remove php code from string


Sum of euclidean norms with box constraints

Question: minimizing the sum of euclidean norms with box constraints
I am a graduate student in computer science, making a thesis on uncertainty geometry. During my thesis I came across the following optimization problem:
($q \in R^k$)   and  ($\forall {1 \leq i \leq n}  \quad   A_i   \in R^{2 \times k})$  and  ($b_i \in R^2$)
Target: min $\sum_{i=1}^n ||A_iq-b_i||_2$
Subject to constrains: $\forall 1 \leq j  \leq k  \hspace {10 mm}  0 \leq q_{j}  \leq 1$
To finish my work I need to find a solution (exact or close to Epsilon arbitrarily small) in polynomial time complexity. Are there any solutions to this problem which have already appeared in previous articles, or is this still an open problem in optimization?
I found some articles that gave numerical solutions for the problem but without explicit definition of run time complexity:
2007 - A quadratically convergent method for minimizing a sum of euclidean norms.
2001 - Semismooth newton methods for Minimizing a Sum of Euclidean Norms with linear constraints.
2000 - A Smoothing Newton Method for Minimizing a Sum of Euclidean Norms.
1995 - A newton barrier method for minimizing a sum of euclidean norms subject to linear equality constraints.
And other  articles that solve Similar problems but none of them fits my case (box constrains):
2006 - Smoothing techniques in euclidean jordan algebras.
2000 - An efficient primal dual interior point method for minimizing a sum of euclidean norms.
1998 - A newton acceleration of the weiszfeld algorithm for minimizing the sum of euclidean distances.
1997 - A primal dual algorithm for minimizing a sum of euclidean norms.
1995 - symmetric primal dual newton methods for minimizing a sum of norms.
The two articles:
2000 -  An efficient algorithm for minimizing a sum of p-norms.
1997 -  An efficient algorithm for minimizing a sum of euclidean norms with applications.
Gave polynomial time solution(close to Epsilon arbitrarily small) but for the unconstrained problem.
Please help me. links to articles with solutions are welcome.
Answer: If performance is not a big concern, just cast your problem in this form:
$ min_q \sum_{i=1}^n t_i\\
\quad t\geq ||A_i q - b_i||_2,\quad i=i,\ldots,n\\
\quad q_j \in [0,1] \quad j=1,\ldots,k$
then make one more transformation and cast the problem as
$ min_q \sum_{i=1}^n t_i\\
\quad (t, A_i q - b_i) \in Q,\quad i=i,\ldots,n\\
\quad q_j \in [0,1] \quad j=1,\ldots,k$
where $Q$ is the second order cone. Not all solver accept this form. For more details you can take a look to
http://docs.mosek.com/generic/modeling-a4.pdf
You can solve using open-source one as CVX or YALMIP. They all use polynomial time algorithms, though maybe not the most efficient one, being them quite generic.
If you need more low level interfaces look at MOSEK (commercial but free for academics).
Specialized algorithms are mostly likely faster, but you must implement them and often it takes a while to make them work reliably.


Not getting desire output

Question: What I want to do is,
I am initializing $message variable for mail body.
And I has to iterate through loop if multiple files are there.
So how can i iterate loop and store values in a variable.
Like,
$message = "Dear " . $fname . "

Manuscript and Other Documents :

Source File : " .$file1 . "

Source PDF File : ".$file2 . "

Cover Letter : " . $file3 . "

Supplementary Files : " . while($row=mysql_fetch_array($supplementary)){ echo $row[0] } . ";

So how can i do this if i have multiple supplementary files?
Comment: use string concatenation operator dot(.) like $message .= "....", check http://php.net/manual/en/language.operators.string.php
Comment: assign your supplimentary file names to a variable with the loop, and append that variable to $message wherever you want it
Answer: To do this, simply append the data to the message variable within the while loop using the string concatenation operator.
For example:
$message = "Dear " . $fname . "
Manuscript and Other Documents :

Source File : " .$file1 . "
Source PDF File : ".$file2 . "

Cover Letter : " . $file3 . "
Supplementary Files : ";

while($row = mysql_fetch_array($supplementary)) {
    $message .= echo $row[0] . '
';
}

Answer: First, do this:
$suplArray = array();

while($row=mysql_fetch_array($supplementary)){
    $suplArray[] =  $row[0];
}

Now, you have the strings in an array. I don't know what format you want, but you can do something like
$suplStr = implode(',', $suplArray);

Then in your string, you can have:
... "Supplementary Files : " . $suplStr;

Comment: it gives last filename only.

Not getting desire output


Is it possible to create a generic method for adding items to a entity framework dbset?

Question: I have not worked with Entity Framework or generics before and am having some difficulty reducing my code.
I am parsing a text file to load 10 lookup tables with data that could possibly change nightly. The text files have a heading for the "type" followed by a list of key/value sets. I have this working perfectly, but I would like to refactor the code to clean it up and would like to use generic methods to accomplish this so I can reduce the duplicated code.
I have gotten the parsing down to a generic method, but I have not been able to figure out how to get the entities added to the context in a generic way. I have to loop over a list of the entities for each type and add them to the context:
void Main()
{
    switch (line.ToUpper())
    {
        case "AREA":
        {
            List<Area> areaList = this.GetItems<Area>(file);

            foreach (var element in areaList)
            {
                if (context.Area.Find(element.Id) == null)
                {
                    context.Area.Add(element);
                }
            }

            break;
        }
        case "CATEGORY":
        {
            List<Category> categoryList = this.GetItems<Category>(file);

            foreach (var element in categoryList)
            {
                if (context.Category.Find(element.Id) == null)
                {
                    context.Category.Add(element);
                }
            }

            break;
        }
    }
}

private List<T> GetItems<T>(StreamReader reader) where T : ILookupData, new()
{
    string line;
    List<T> list = new List<T>();

    while (reader.Peek() == ' ')
    {
        line = reader.ReadLine().TrimStart();
        string[] tokens = line.Split(new string[] { " - " }, 2, StringSplitOptions.None);

        T item = new T();
        item.Id = Convert.ToInt32(tokens[0]);
        item.Description = (string)tokens[1];

        list.Add(item);
    }

    return list;
}

Update: The above works fine, but cannot seem to get the context added.
I have tried a few different things, but seem to keep getting this error when I try to generic up the context:

The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type of method.

The last thing I tried was to add a generic GetDbSet to the context:
public DbSet<T> GetDbSet<T>() where T : class
{
    return this.Set<T>();
}

But I get the same error in my controller adding this code to the GetItems method:
using (MyContext context = new MyContext())
{
    var dbSet = context.GetDbSet<T>();
}

Comment: I did add the constraint to both and still get the reference type error. Should I perhaps be passing in a type different then the entity class?
Comment: Try to add "where T:class" constraint to your GetItems method
Comment: That does not help with adding the .Add functionality. The GetItems currently works, but I am not able to use the context such as `context.Set().Add(item);`
Comment: You need same constraint on both methods. If Add has "class" constraint  than the GetItems method that calls Add, should also have "class" constraint.
Comment: Problem solved by changing from ILookupData class constraint to a concrete class inherited by each lookup entity model. Thank you.
Answer: I have a generic repository in my current project. This is its add method:
public void Add<T>(T newItem) where T : class
{
    db.Set<T>().Add(newItem);
}

where db is the DbContext object itself. The where T : class fixes that error about reference types. Without it, you could pass any type in as T, including bool or struct, or any value type, which DbSet.Add() can't handle. The where specifies that T must be a class, which is a reference type, and therefore allowed.
Comment: Inheriting your objects from a base type is often a good idea; you can add things like an ID field that they all use as primary keys, or `DateTime` fields to record creation and last edit times.
Comment: That works for the repository, but I am still getting the error if I try to call it in GetItems like this: `context.Set().Add(item);` or `context.Add(item);`
Comment: Figured it out. It was an inheritance issue with using an interface instead of a concrete type. Now, I just need to modify my models a bit. Thank you.
Comment: @anaximander How about creating the Add method as extension, then will that be costlier since  instance of context has to be created ?


Comparing keywords from one file to another file containing different tweet

Question: I am currently doing a project for my Python course which is sentiment analysis for tweets. We have only just finished reading/writing files and stuff like split() and strip() using Python is class, so I am still a noob at programming.
The project involves two files, the keywords.txt file and tweets.txt file, sample of the files are:
sample of tweets.txt:

[41.298669629999999, -81.915329330000006] 6 2011-08-28 19:02:36 Work needs to fly by ... I'm so excited to see Spy Kids 4 with then love of my life ... ARREIC
[33.702900329999999, -117.95095704000001] 6 2011-08-28 19:03:13 Today
is going to be the greatest day of my life. Hired to take pictures at
my best friend's gparents 50th anniversary. 60 old people. Woo.

where the numbers in the brackets are coordinates, the numbers after that can be ignored, then the message/tweets comes after.
sample of keywords.txt:

alone,1
amazed,10
excited,10
love,10

where numbers represent the "sentimental value" of that keyword
What I am supposed to do is to read both files in Python, separate the words in each message/tweet and then check if any of the keywords is in each of the tweets, if the keywords are in the tweet, the add together the sentimental values. Finally, print the total of the sentiment values of each tweet, ignoring the tweets that does not contain any keywords.
So for example, the first tweet in the sample, two keywords are in the tweet (excited and love), so the total sentimental values would be 20.
however, in my code, it prints out the sentimental values separately as 10, 10, rather than printing out the total. And I also have no idea how to make it so that the function for checking keywords iterate over every tweet.
My code so far:
tweets = open("tweets.txt","r")
keywords = open("keywords.txt","r")

def tweetDataExtract (infile):
    line = infile.readline()
    if line == "":
        return []
    else:
        parts = line.split(" ",5)
        return parts

def keywordsDataExtract (infile):
    line = infile.readline()
    if line == "":
        return[]
    else:
        parts = line.split(",",1)
        return parts

tweetData = tweetDataExtract(tweets)
while len (tweetData) == 6:

    lat = float(tweetData[0].strip("[,"))
    long = float(tweetData[1].rstrip("]"))
    message = tweetData[5].split(" ")
    messageWords=[]
    #gets rid of all the punctuation in the strip() brackets
    for element in message:
        element = element.strip("!@.,?[]{}#-_-:)('=/%;&*+|<>`~\n")
        messageWords.append(element.lower())
    tweetData = tweetDataExtract(tweets)
    print(lat, long, messageWords)

    keywordsData = keywordsDataExtract(keywords)
    while len (keywordsData) == 2:

        words = keywordsData[0]
        happiness = int(keywordsData[1])
        keywordsData = keywordsDataExtract(keywords)

        count = 0
        sentiment = 0
        if words in messageWords:
            sentiment+=happiness
            count+=1
            print (lat, long, count, sentiment)

tweets.close()
keywords.close()

How can I fix the code?
PS I didn't know which part of the code would be essential to post, so I just posted the whole thing so far.
Answer: The problem was that you had initialised the variables count and sentiment inside the while loop itself. I hope you realise its consequences!!
Corrected code :
tweets = open("tweets.txt","r")
keywords = open("keywords.txt","r")

def tweetDataExtract (infile):
    line = infile.readline()
    if line == "\n":
        # print("hello")
        return tweetDataExtract(infile)

    else:
        parts = line.split(" ",5)
        return parts

keywordsData = [line.split(',') for line in keywords]

tweetData = tweetDataExtract(tweets)
while len(tweetData) == 6:
    lat = float(tweetData[0].strip("[,"))
    long = float(tweetData[1].rstrip("]"))
    message = tweetData[5].split(" ")
    messageWords=[]
    #gets rid of all the punctuation in the strip() brackets
    for element in message:
        element = element.strip("!@.,?[]{}#-_-:)('=/%;&*+|<>`~\n")
        messageWords.append(element.lower())
    tweetData = tweetDataExtract(tweets)
    count = 0
    sentiment = 0
    for i in range(0,len (keywordsData)):
        words = keywordsData[i][0]
        happiness = int(keywordsData[i][1].strip())
        if words in messageWords:
            sentiment+=happiness
            count+=1
    print (lat, long, count, sentiment)

tweets.close()
keywords.close()

See this new code (shorter and pythonic):
import string

dic = {}
tweets = []
with open("tweets.txt",'r') as f:
    tweets = [line.strip() for line in f if line.strip() != '']

with open("keywords.txt",'r') as f:
    dic = {line.strip().split(',')[0]:line.strip().split(',')[1] for line in f if line.strip()!=''}

for t in tweets:
    t = t.split(" ",5)
    lat = float(t[0].strip("[,"))
    lon = float(t[1].rstrip("]"))
    sentiment = 0
    for word in t[5].translate(str.maketrans("","", string.punctuation)).lower().split():
        if word in dic:
            sentiment+=int(dic[word])
    print(lat,lon,sentiment)

Output:
41.29866963 -81.91532933 20
33.70290033 -117.95095704 0

Comment: @Pengibaby Try now.
Comment: Omg! it works! Thank you so much for taking the time to help!  :)   So what was wrong with it? Was it my second while loop that was causing the problem?
Comment: @Pengibaby The thing is, you are reading the tweets one by one. Thats fine. But for the `keywords`, you need it again and again, right?! So I stored it in a separate list and used it again and again. Presently, after the first tweet, keywords will always be Null as reading has finished. Is it fine now?
Comment: Oh okay, That makes sense! Thank you for the help and for explaining to me what I did wrong!  :)
Comment: @Pengibaby Glad, I could help.


C# Visual Studio erro de compilação desconhecido

Question: Fui refatorar meu código em C# que estava funcionando perfeitamente, porém estava gigantesco, e ele parou de funcionar e o visual studio não descreve o erro em canto algum. Segue abaixo meu código e o Visual Studio.
PrintScreen do console do Visual Studio

TicketController - Minha controladora
using sgtalk.api.Helpers;
using sgtalk.api.Models;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace sgtalk.api.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class TicketController : ApiController
    {
        public HttpResponseMessage Get()
        {
            //TicketRepository.GetAll(lg)
            HttpResponseMessage resp = new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.BadRequest
            };

            if (LoginHelper.isLogged(Request, out LoginTransmit lg))
            {
                //    resp = new HttpResponseMessage()
                //    {
                //        StatusCode = HttpStatusCode.OK,
                //        Content = new StringContent(JsonConvert.SerializeObject(new { }))
                //    };
            }
            else
            {
                resp = new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.Unauthorized
                };
            }

            return resp;
        }
    }
}

Analisando um pouco o código, descobri que o erro está na linha
LoginHelper.isLogged(Request, out LoginTransmit lg)

Removendo está linha o programa compila.
LoginHelper -- O prorietário da linha acima
using sgtalk.api.Models;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;

namespace sgtalk.api.Helpers
{
    public static class LoginHelper
    {
        public static bool isLogged(HttpRequestMessage r, out LoginTransmit l)
        {
            l = null;
            var ret = false;
            if (r.Headers.TryGetValues("X-Access-Token", out IEnumerable<string> headerValues))
            {
                var s = headerValues.FirstOrDefault();
                l = TokenHelper.Decode(s);
                ret = true;
            }
            else
            {
                ret = false;
            }
            return ret;
        }
    }
}

O que está acontecendo? Estou a mais de 1 hora tentando resolver, mas não encontro onde exatamente esta o erro.
Update: com "parou de funcionar" quero dizer que não compila mais.
Update 2: No console ele lista os seguintes erros:

C:\Users\marcio.nicolau\documents\visual studio 2017\Projects\sgtalk\sgtalk.api\Controllers\TicketController.cs(51,61,51,63): error CS1003: Syntax error, ',' expected

Nestas linhas, tem estes códigos:
public HttpResponseMessage Get()
        {
            //TicketRepository.GetAll(lg)
            HttpResponseMessage resp = new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.BadRequest
            };
//linha 51
            if (LoginHelper.isLogged(Request, out LoginTransmit lg))
            {
                //    resp = new HttpResponseMessage()
                //    {
                //        StatusCode = HttpStatusCode.OK,
                //        Content = new StringContent(JsonConvert.SerializeObject(new { }))
                //    };
            }
            else
            {
                resp = new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.Unauthorized
                };
            }

            return resp;
        }

C:\Users\marcio.nicolau\documents\visual studio 2017\Projects\sgtalk\sgtalk.api\Helpers\LoginHelper.cs(14,74,14,80): error CS1525: Invalid expression term 'string'

public static bool isLogged(HttpRequestMessage r, out LoginTransmit l)
        {
            l = null;
            var ret = false;
            if (r.Headers.TryGetValues("X-Access-Token", out IEnumerable<string> headerValues)) //Linha 14
            {
                var s = headerValues.FirstOrDefault();
                l = TokenHelper.Decode(s);
                ret = true;
            }
            else
            {
                ret = false;
            }
            return ret;
        }

Update 3: Estou usando .NET Framework 4.6
Comment: Se não me engano, no console (log), descreve o erro quando é assim. Coloca pra compilar e fica prestando atenção lá, talvez você ache alguma coisa.
Comment: Elabore: "_parou de funcionar_".
Comment: @LINQ Dei um update no post
Answer: Qual versão de c# que está usando? Se for versões anterioes ou igual a 6.0, teste fazer isto:
LoginTransmit lg;
LoginHelper.isLogged(Request, out lg);


How do i run two rails projects on my machine simultaneously

Question: I want to be able to run two rails servers on one machine via vagrant and virtual box. I have the first set up and when i run
rails s

it returns the following with the site accessibly in my browser at http://localhost:3000/
=> Booting Thin
=> Rails 220.127.116.11 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
installing dummy notifier
Thin web server (v1.7.0 codename Dunder Mifflin)
Maximum connections set to 1024
Listening on 0.0.0.0:3000, CTRL+C to stop

Heres the vagrantfile for this instance:
Vagrant.configure("2") do |config|

  config.vm.box = "hashicorp/precise64"

  config.vm.network "forwarded_port", guest: 3000, host: 3000

end

I now have the second project in a different folder on my local machine. I have navigated to it initiated my vagrant box, completed all the set up steps and ran rails s again. Here I get:
=> Booting Puma
=> Rails 4.2.3 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
Puma 2.12.2 starting...
* Min threads: 0, max threads: 16
* Environment: development
* Listening on tcp://localhost:3000

Heres the vagrantfile for this instance:
Vagrant.configure("2") do |config|

  config.vm.box = "hashicorp/precise64"

  config.vm.network "forwarded_port", guest: 80, host: 8080

end

I have been trying to investigate the the fact that it says "listening on tcp://localhost:3000" but if anyone can give me some pointers as to how exactly I can run the two projects from the same machine it would be much appreciated.
Answer: You have to run them on different ports.  rails s takes a port argument.
rails s -p 3001

will give you a server at port 3001 and so on.
Comment: Thanks for the input but its still not returning the site. Is there any further information you need which might help. I'm a tad confused by the vagrant file's but then again this may have nothing to do with it.
Comment: Are both projects running on Vagrant?  Do the 2 projects talk to one another?
Comment: No they have no need to. Just updating my question with the vagrant files.
Comment: What behavior are you expecting that you are not seeing?
Comment: With the Thin instance when i type http://localhost:3000/ it loads a site but for the Puma instance when i try different variations of this including http://localhost:3001 and 127.0.0.1:3001 i get "site cannot be reached".
Comment: You need to use telnet to connect to TCP ports.  https://support.symantec.com/en_US/article.TECH107919.html
Answer: Perhaps try running the second server at port 8080, not 3001, since your second vagrant machine is set up like :
config.vm.network "forwarded_port", guest: 80, host: 8080
Answer: I ended up running
puma -b tcp://0.0.0.0:3001

and my vagrantfile had the following:
config.vm.network "forwarded_port", guest: 3001, host: 3001

Thanks for the pointers though as they helped me to better understand the problem and find the solution.


Solve $T(n) = T( \lfloor 2n / 10\rfloor ) + \Theta(n^3)$ recurrence

Question: I don't know how to solve the following recurrence. Particularly, I don't know how to cope with the $2n$ term:
$$T(n) = T( \lfloor 2n / 10\rfloor ) + \Theta(n^3)$$
Master theorem of recurrences doesn't really explains how to... I was thinking that this would solve it:
$$T(n) = 2T(\lfloor n / 10\rfloor) + \Theta(n^3)$$
But I'm not sure. How do I approach this?
Comment: Im doing that but i added just in case it was necessary. But thanks, i didnt know about that. I was doing it blindly.
Answer: \begin{align}T(n) &= T(\lfloor2n/10 \rfloor) + \Theta(n^3) \\
&= T(\lfloor n/5\rfloor) + \Theta(n^3) &(1)\\
&=T(n/5) + \Theta(n^3) & (2)\\
&= \Theta(n^3) & (3)\end{align}
I have applied:
$(1)$ Fraction simplification: $2n/10 = n/5$.
$(2)$ Removing floors. In general you can remove all floors and ceilings in recurrences that may be solved with the master theorem, that is, recurrences of the form $$T(n) = a T(n/b) + g(n)$$ (this is a proved fact).
$(3)$ Application of the master theorem.
Comment: I was confused here $=T(⌊n/5⌋)+Θ(n3)$ , so i just simplify ? Dividing by 2?
Comment: Hey, if you can just tell me.. What should i do if it would be a number that i cant simplify, like $T(N) = T(3n/10) + \Theta(n^3) $ ?
Comment: In general $$n\frac{a}{b} = \frac{n}{b/a},$$ so $3n/10 = n / (10/3)$. Just think it as "we divide our $n$ size problem into a $10/3$ size problem".
Comment: Thanks it helped me understand it! I voted UP but it wont compute until i  get enough reputation. I dont know why someone voted down.
Comment: Maybe he didn't want you to give the answer. However, You didnt do anything wrong because i do know how to calculate using the master theorem and as you helped me on the "edit" propostal, my problem was related to the "2n term".


ARIMA modeling: can seasonal data be seasonally stationary?

Question: I am new to ARIMA modeling and currently encountering a weird situation with time series of count data. The time plot shows clear seasonal patterns.ACF also hints on presence of seasonality. However, seasonal unit root test in R shows that series is seasonally stationary.
If I include seasonal differencing (D=1), I cannot find a single model where residuals  satisfy normality assumption, even if I perform log- or - square root- or Box-Cox transformations of original series. If I do not include seasonal differencing (keeping seasonal AR and MA parameters is in the model), I easily identify a model with great diagnostics (residuals are white noise and normally distributed).
Having hard time solving the puzzle whether seasonal-looking data can be seasonally stationary. Will appreciate any suggestion.
Comment: Hello Jane, may I ask you which test you applied? Was it 'nsdiffs' from 'forecast' package?
Answer: Well, it's simply that clear seasonal correlations don't always imply that you need seasonal differencing; the seasonal effect can be modelled fine with seasonal moving average & autoregressive terms.  It's the same in non-seasonal models; just because you see a strong autocorrelation doesn't necessarily mean you need to difference the series.  Sounds like you solved the 'puzzle' by fitting a good model to the undifferenced series that still incorporated seasonal effects.
Comment: Many thanks Scortchi for your help! Now I am not worried about differencing.


Share SPRING_SECURITY_CONTEXT between two applications

Question: I have two different Spring Boot Applications that run on localhost on different ports (8080, 8081) and different configs (application.yml). These apps use SSO with OAuth 2.0 to get authorization token from Authorization Server. I log in to my first application, get authorization and everything works great here. Now I need to share these authentication details with second Spring Boot App (on port 8081) to authorize second app in Authorization Server. Googled and found 2 aproaches: I can try to share HttpSession between two apps (but I think it's redundant) OR HttpSessionSecurityContextRepository as SecurityContextRepository which seems more convenient. The problem here is that I can't manage to do so and I'm still not sure that it's a good idea to share Security Context between 2 apps.
What I tried for now:

Share authorization token from first app via headers in GET request (custom-built in accordance with specification for requests for Authorization Server), but it didn't work - second app doesn't take in mind this token.
Share authorized cookie from first app to second, but it didn't work, too.

I can't do authorization through Authorization Server on second app because it may be not a Spring Boot App with @Controller but any other app without HTML forms, so I need to authorize on first app (with UI), get all the data which is needed to perform authorized requests and pass it to second app (third, fourth...) so they will be able to do authorized requests too.
Thanks in advance!
Comment: Your authorization/resource server is another application .right ?
Did you request same client_id and client_secret ?
Comment: Yes, resource server is another application. From second app I request different client_id and client_secret. Different from first app, of course.
Answer: I presume that your authorization/resource server is external application.And you can login successfully with your first application so flow is working.You have two client application with own client_id, client_secret and etc. parameters.If these parameters are different then authorization/resource server will return different bareer token and sessionid cookie for first and second client application.Otherwise you need to authorize both of them in authorization/resource server.
I would offer when user do login to first app then in background you do login also for second application.
For automatically authorizing second application you can try to do oauth2 login flow manually for second application with own parameters when after successful first application login and send cookies to frontend which you got from oauth2 login.
For manual oauth2 login you can try below code:
private Cookie oauth2Login(String username, String password, String clientId, String clientSecret) {
    try {
        String oauthHost = InetAddress.getByName(OAUTH_HOST).getHostAddress();
        HttpHeaders headers = new HttpHeaders();
        RestTemplate restTemplate = new RestTemplate();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();

        // Basic Auth
        String plainCreds = clientId + ":" + clientSecret;
        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = org.apache.commons.net.util.Base64.encodeBase64(plainCredsBytes);
        String base64Creds = new String(base64CredsBytes);
        headers.add("Authorization", "Basic " + base64Creds);
        // form param
        map.add("username", username);
        map.add("password", password);
        map.add("grant_type", GRANT_TYPE);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,
                headers);
        // CALLING TOKEN URL
        OauthTokenRespone res = null;
        try {
            res = restTemplate.postForObject(OAUTH_HOST, request,
                    OauthTokenRespone.class);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        Optional<OauthTokenRespone> optRes = Optional.ofNullable(res);
        String accessToken = optRes.orElseGet(() -> new OauthTokenRespone("", "", "", "", "", ""))
                .getAccess_token();
        // CALLING RESOURCE
        headers.clear();
        map.clear();
        headers.setContentType(MediaType.APPLICATION_JSON);
        map.add("access_token", accessToken);
        request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

        Cookie oauthCookie = null;
        if (accessToken.length() > 0) {
            HttpEntity<String> response = restTemplate.exchange(
                    OAUTH_RESOURCE_URL.replace(OAUTH_HOST, oauthHost) + "?access_token=" + accessToken,
                    HttpMethod.POST, request, String.class);
            String cookie = Optional.ofNullable(response.getHeaders().get("Set-Cookie"))
                    .orElseGet(() -> Arrays.asList(new String(""))).get(0);
            if (cookie.length() > 0) {
                String[] c = cookie.split(";")[0].split("=");
                oauthCookie = new Cookie(c[0], c[1]);
                oauthCookie.setHttpOnly(true);
            }
        }
        return Optional.ofNullable(oauthCookie).orElseGet(() -> new Cookie("Ops", ""));
    } catch (Throwable t) {
        return new Cookie("Ops", "");
    }
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class OauthTokenRespone {
    private String access_token;
    private String token_type;
    private String refresh_token;
    private String expires_in;
    private String scope;
    private String organization;
    // getter and setter
  }

And call this method after first  app login as follows :
Cookie oauthCookie = oauth2Login(authenticationRequest.getUsername(), authenticationRequest.getPassword(),
            CLIENT_ID, CLIENT_SECRET);

After getting cookie you need change its name (for example JSESSIONID-SECOND) because same cookies will override each other and also need to change  its domain path to second app domain.
response.addCookie(oauthCookie);

Last you need add cookie to response (it is HttpServletResponse reference).
Hope it helps!
Comment: Thanks for the reply, but we found another solution! In OAuth context we have another one entity which is called "resource server". You can access it via access_token obtained from Authentication Server. So, on second app I put @EnableResourceServer annotation, made GET request with access_token in header and got information I needed. Very simple and very sad that I spent 2 weeks finding out the best solution. But again, thank you for reply. I didn't answer fast on your response bc I was really busy at my work... \=


Singular solution of a differential equation

Question: I have been given the following differential equation:
$$y(y-2xy')^2=2y'$$
I was able to obtain a singular solution $4xy^2+1=0$. Now I need to verify that it is a solution of the differential equation.
I obtain this: $y^2=-\frac{1}{4x}$.
How do I proceed when there is a negative sign which would be inside of the square root?
Any help would be appreciated.
Comment: If $x$ was negative itself, this wouldn't be an issue, would it?
Comment: Noe that $y=0$ is also a solution
Comment: You can always verify an explicit solution by plugging it in to the differential equation and seeing if the two sides simplify to the same thing.  In this case, both $y = \sqrt{-1/(4x)}$ and $-\sqrt{-1/(4x)}$ qualify.  BTW, it's also easy to see that if $y$ is a solution, so is $-y$.
Answer: First take your solution $y^2=-1/(4x)$ and differentiate implicitly, thus
$2yy'=1/(4x^2)$
$y'=1/(8x^2y).$
We then have
$y[y-1/(4xy)]^2=1/(4x^2y)$
$y^3-y/(2x)+1/(16x^2y)=1/(4x^2y).$
Now divide by $y$, which is valid because $y^2=-1/(4x)$ forces $y\not=0$:
$y^2-1/(2x)+1/(16x^2y^2)=1/(4x^2y^2).$
Then you have only even powers of $y$ so you can exchange $y^2$ for $-1/4x$ in the last equation above.  You then have an equation with $x$ alone.  If this can be reduced algebraically to an identity, your solution is verified.


Modeling Time-Series with a lower bound

Question: I am trying to fit a model to a time series that has a lower bound (at around -150). Using an ARIMA model, running simulations often leads to the time series hitting (and going underneath) this lower bound. How can I avoid this? Is there a better model I can use?
Comment: Could you explain why that lower bound exists, how you know its value, and what it means? Such information often can suggest effective solutions, such as transformations of the variable or generalized linear modeling approaches.
Comment: For example, it would be helpful to plot a histogram of wind speed.  If wind speed appears to be log-normally distributed, then simply taking the log of wind speed will likely result in a close to normally distributed time series.  Log series are nice because they are simple and offer a clear interpretations in respect to growth and percentage changes over time.
Comment: Thank you for the reply. I am modelling the error in the weather forecast for wind speed. Since wind speed cannot be negative, there is a lower bound of the forecast error (the error cannot predict a wind speed less than zero).
Comment: Have you considered separately modeling the forecast and the wind speed? In fact, if the forecast itself is obtained with a statistical model, then it already models the difference between its predictions and the true wind speeds--so you might not have to do any additional analysis.
Comment: $logit(w)=\log(w/(1-w))$ where $0<w<1$.  So if you know a reasonable upper bound say 250, then $logit(w)=\log(w/(250-w))$ where $0<w<250$.  I agree that some transformation (not necessarily a logit transformation) is the simplest approach if you want to use an ARIMA model.  One thing to keep in mind is that the standard ARIMA assumes normally distributed innovations.  As the distribution of the innovations will be effected by the transformation you use, care should be taken in choosing the transformation and checking the residuals of the resulting ARIMA estimation.
Comment: Not sure exactly how to do this, but, essentially, you want your model to satisfy the property of _data admissibility_; the impossibility of producing impossible values. For example, a model that forecasts the unemployment rate to be negative or above 100 is not data admissible. To set a bound between, say, 0 and 1, you can model a logit transformation. This is the route you ought to take... you can't just ignore negative values. Well, you can, but I wouldn't.
Comment: Thank you for the answer Graeme! I am unfamiliar with the logit transform, how can use it on my data set if my bounds aren't [0,1]?
Answer: The only way I can think of is to ignore values under 150
Comment: What happens if the model produces values that are all under 150? In that situation, this approach would not work, I presume?!
Comment: i have seen sales data that can be small and the appropriate model might predict (slightly) negative numbers just because there is no restriction .Since negative sales numbers can't happen a logical override is to convert the negative number to 0 regardless of haw many periods you are forecasting. This is similar to modelling tire data as a result of mileage as negative tire wear is impossible,
Comment: That's fine, but the fact that the model produces numbers that are, in fact, impossible in reality is a defective property of the model. _I would never bet on a horse that doesn't run in the race. - Nobody would!_
Comment: The negative numbers are an artifact as was The Irish Derby . Up the Dubs !

Modeling Time-Series with a lower bound


Limit macro to set a range for textbox

Question: I am trying to link a range of cells to a text box, the only problem is if I edit the text box, it will write in any cell. I want to limit that ability to a specific range ("C4 to C11"). Here is my code:
Dim PreviousCell As Range

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

   If Target.Column = 3 Then ActiveSheet.TextBox1.Text = Target

       If Not PreviousCell Is Nothing Then
       Debug.Print PreviousCell.Address
       End If

       Set PreviousCell = Target ' This needs to be the last line of code.

End Sub

Private Sub TextBox1_Change()

ActiveCell.Value = TextBox1

End Sub

Comment: Sorry, my english may not be good, but I don't get what are you trying to accomplish. You mean that if you select a cell in Range `C4:C11` then you want the textbox show the value of selected cell?
Comment: It already does that, if I click on a random cell, not in column 3, I can edit that cell via the text box. I only want to be able to edit column 3 via the text box.
Answer: Private Sub TextBox1_Change()

If ActiveCell.Column = 3 Then ActiveCell.Value = TextBox1

End Sub

Limit macro to set a range for textbox


Como remover o atributo UNIQUE KEY de uma coluna no MySQL?

Question: Criei uma tabela no MySQl que utiliza uma coluna chamada loja_num com o atributo unique key
UNIQUE KEY loja_num (loja_num,

Mas agora, eu gostaria de retirar esse atributo dessa coluna. Já fiz umas pesquisas sem sucesso. Alguém sabe me informar qual comando utilizo no MySQL?
Utilizo XAMPP no Windows e o banco de dados é MySQL.
Obrigado.
Comment: Se você já achou a solução, poste uma resposta à sua própria pergunta.
Comment: Pessoal, esquece!!! Foi resolvido da seguinte maneira:

1) Pesquisei quais eram os INDEXES que existiam no banco:
'SHOW INDEXES FROM lojas_info;'

Depois deletei o INDEX que continha a UNIQUE KEY:
'ALTER TABLE lojas_info
  DROP INDEX loja_num;'
Comment: @IgorSantana seria legal você postar a solução na resposta, assim ajudaria futuros visitantes com a mesma dúvida.
Comment: Mas eu postei ali em cima ..... veja:

1) Pesquisei quais eram os INDEXES que existiam no banco: 'SHOW INDEXES FROM lojas_info;' Depois deletei o INDEX que continha a UNIQUE KEY: 'ALTER TABLE lojas_info DROP INDEX loja_num;'
Answer: O próprio @IgorSantana comentou a resolução da seguinte forma:

Pesquisou quais eram os indexes que existiam no banco.
SHOW INDEXES FROM lojas_info;

Deletou o index que continha a UNIQUE KEY:
ALTER TABLE lojas_info DROP INDEX loja_num;

Comment: Opa... foi isso mesmo! obrigado... eu ainda estou me acostumando a este forum! obrigado! :D


Is there a simple test in Bash to test if a logical path is a directory

Question: The question is best explained through a small example:
Create an infrastructure of directories as follows:
rm -rf /tmp/work
mkdir -p /tmp/work/a/b/c
cd /tmp/work
ln -s a/b/c s
mkdir t
tree

This results in the following infrastructure:

There is a very simple way to check for the existence of a directory:
cd /tmp/work
if test -d s/../t; then echo EXISTS; else echo DOES NOT EXIST; fi

However, it seems that the '-d' test only checks for the physical path (a/b/t); The following clearly shows that the logical path/directory does exist:
cd s/../t
pwd

I am hoping for a simple test to get this situation checked...
Checking for similar questions in StackOverflow, I haven't found an answer that differentiates logical paths from physical paths...
I did a brute force (silly) attempt to get some more insight:
for o in -b -c -d -e -f -g -G -k -h -L -O -p -r -S -s -t -u -w -x; do
  if test $o s/../t; then echo EXISTS; else echo DOES NOT EXIST; fi
done

As expected, all of the tests indicate failure...
Answer: The closest I get to a simple solution is the following test:
if (unset CDPATH; cd -L s/../t &>/dev/null); then echo EXISTS; else echo DOES NOT EXIST; fi

If using '-P' rather than '-L', then this syntax tests for physical paths (the equivalent of 'test -d').
Note that if we're sure that we're using builtins, then the syntax is just a bit simpler:
if (unset CDPATH; cd s/../t &>/dev/null); then echo EXISTS; else echo DOES NOT EXIST; fi

But there must be a better way...


Resolve "Maximum request length exceeded" and FileUpload single upload

Question: I basically had an ASP.NET FileUpload control, for which I needed to cater the exception thrown for the following message:

Maximum request length exceeded.

The limitations are that I need to just restrict the user to upload one file in all because I have save the other details from some text-boxes into DB.
The maximum file size setting is set in the web.config as follows:
<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="41943040" />
        </requestFiltering>
    </security>
</system.webServer>
<system.web>
    <httpRuntime maxRequestLength="40960" requestValidationMode="2.0" />
</system.web>

So therefore I searched many solutions, to name then as follows:

Usage Global.asax with validating file size in "Application_BeginRequest()", but it has not resolved my issue and it crashes at the Redirect when file size is greater and a redirect to Error Page is not working.
Usage of AjaxFileUpload instead of ASP.NET FileUpload control, this is again crashes at the checking of file size is greater than maximum size allowed in Web.config.
Secondly I have to restrict that in total the user can just upload one single file, not more than one file, so using the AjaxFileUpload it is not working in my condition, since I have to upload a single document and save the other details in some text-boxes related to that file.
Thirdly when the file size exceeds the limit, i.e. 40MB, then the AjaxFileUpload just gets red colour, no message is shown.

I want to find out that how can I accomplish my requirements, since I am stuck for this since a couple of days.
Update: Found few of them useful, but could not accomplish the requirements on their basis:

Display custom error page when file upload exceeds allowed size in ASP.NET MVC
Maximum request length exceeded
http://dotnetslackers.com/Community/blogs/haissam/archive/2008/09/12/upload-large-files-in-asp-net-using-httpmodule.aspx
http://geekswithblogs.net/sglima/archive/2011/09/20/how-to-handle-maximum-request-length-exceeded-exception.aspx
http://dotnetpools.com/Article/ArticleDetiail/?articleId=52&title=Ajax%20AsyncFileUpload%20Example%20In%20Asp.net%20To%20Upload%20Files%20To%20Server%20Using%20AjaxFileUpload%20Control

Following is markup:
<asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>
<asp:FileUpload ID="theFile" runat="server" />
<asp:Button ID="Button2" runat="server" Text="Upload 1"  onclick="Button2_Click" />
<asp:Button ID="Button1" runat="server" Text="Upload 1"  onclick="btnUpload1_Click" />
<asp:Button ID="btnUpload" runat="server" Text="btnUpload_Click" onclick="btnUpload_Click" />
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:AjaxFileUpload ID="AjaxFileUpload2" runat="server" ToolTip="Upload File" ThrobberID="MyThrobber" onclientuploaderror="IsFileSizeGreaterThanMax" onuploadcomplete="AjaxFileUpload1_UploadComplete" AllowedFileTypes="jpg,jpeg,gif,png,pjpeg,zip,rar,pdf,xls,xlsx,doc,docx" MaximumNumberOfFiles="1" Height="50px" Width="350px"/>
<asp:Image id="MyThrobber" ImageUrl="~/UploadedFiles/Penguins.jpg" AlternateText="Saving...."  Style="display:None"  Height="1px" Width="350px" runat="server" />

Following is C# code:
protected void Button2_Click(object sender, EventArgs e)
{
    if (theFile.HasFile)
    {
         HttpRuntimeSection runTime = (HttpRuntimeSection)System.Configuration.ConfigurationManager.GetSection("system.web/httpRuntime");
        double maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;
        double xxx = theFile.PostedFile.ContentLength;
        double ck = xxx / 1024 / 1024;
        bool f = false;
        if (ck > maxRequestLength)
        {
            f = true;
        }
        lblStatus.Text = xxx.ToString() + " " + (f ? "too big" : "size ok");
    }
 }

protected void btnUpload1_Click(object sender, EventArgs e)
{
     try
     {

        if ((theFile.PostedFile != null) && (theFile.PostedFile.FileName != ""))
         {
             if ((theFile.PostedFile != null) && (theFile.PostedFile.FileName != ""))
             {
                 fileName = theFile.PostedFile.FileName;
                 Session["FileAttached"] = fileName;
             }
             else
             {
                 Session["FileAttached"] = "";
                 lblStatus.Focus();
                 lblStatus.ForeColor = System.Drawing.Color.Red;
                 lblStatus.Text += "
Attachment file not found.";
                 return;
             }
             if (fileName != "")
             {
                 cFilePath = Path.GetFileName(fileName);

                /*UpPath = "../UploadedFiles";
                 fullPath = Server.MapPath(UpPath);
                 fileNpath = fullPath + "\\" + cFilePath;*/

                if (theFile.HasFile)
                 {
                     string CompletePath = "D:\\Visual Studio 2010\\DevLearnings\\FileAttachSizeMax\\UploadedFiles\\";
                     if (theFile.PostedFile.ContentLength > 10485760)
                     {
                         lblStatus.Focus();
                         lblStatus.ForeColor = System.Drawing.Color.Red;
                         lblStatus.Text += "File size is greater than the maximum limit.";
                     }
                     else
                     {
                         theFile.SaveAs(@CompletePath + theFile.FileName);
                         lblStatus.Text = "File Uploaded: " + theFile.FileName;
                     }
                 }
                 else
                 {
                     lblStatus.Text = "No File Uploaded.";
                 }
             }
        }
     }
     catch (Exception ex)
     {
         lblStatus.Focus();
         lblStatus.ForeColor = System.Drawing.Color.Red;
         lblStatus.Text += "Error occurred while saving Attachment.
Error: " + ex.Source.ToString() + "
Code:" + ex.Message.ToString();
     }
 }

protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
    HttpRuntimeSection runTime = (HttpRuntimeSection)System.Configuration.ConfigurationManager.GetSection("system.web/httpRuntime");
    int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;

    if (e.FileSize <= maxRequestLength)
    {
         string path = MapPath("~/UploadedFiles/");
         string fileName = e.FileName;
         AjaxFileUpload2.SaveAs(path + fileName);
     }
     else
     {
         lblStatus.Text = "File size exceeds the maximum limit. Please use file size not greater than 40MB. ";
         return;
     }
}

protected void btnUpload_Click(object sender, EventArgs e)
{
     //AsyncFileUpload.SaveAs();
     //AjaxFileUpload1.SaveAs();

    HttpContext context = ((HttpApplication)sender).Context;
     //HttpContext context2 = ((System.Web.UI.WebControls.Button)sender).Context;

    HttpRuntimeSection runTime = (HttpRuntimeSection)System.Configuration.ConfigurationManager.GetSection("system.web/httpRuntime");
    double maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;

    if (context.Request.ContentLength > maxRequestLength)
    {
         IServiceProvider provider = (IServiceProvider)context;
         HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
         FileStream fs = null;
         // Check if body contains data
         if (wr.HasEntityBody())
         {
             // get the total body length
             int requestLength = wr.GetTotalEntityBodyLength();
             // Get the initial bytes loaded
             int initialBytes = wr.GetPreloadedEntityBody().Length;

            if (!wr.IsEntireEntityBodyIsPreloaded())
            {
                 byte[] buffer = new byte[512000];
                 string[] fileName = context.Request.QueryString["fileName"].Split(new char[] { '\\' });
                 fs = new FileStream(context.Server.MapPath("~/UploadedFiles/" + fileName[fileName.Length - 1]), FileMode.CreateNew);
                 // Set the received bytes to initial bytes before start reading
                 int receivedBytes = initialBytes;
                 while (requestLength - receivedBytes >= initialBytes)
                 {
                     // Read another set of bytes
                     initialBytes = wr.ReadEntityBody(buffer, buffer.Length);
                     // Write the chunks to the physical file
                     fs.Write(buffer, 0, buffer.Length);
                     // Update the received bytes
                     receivedBytes += initialBytes;
                 }
                 initialBytes = wr.ReadEntityBody(buffer, requestLength - receivedBytes);
            }
         }
         fs.Flush();
         fs.Close();
         context.Response.Redirect("About.aspx");
     }
}

Apart from the above, I have come to a solution mentioned below.
I have used the following code, although it is now running the Application_Error() Code section, but the problem is that it is not redirecting to the About.aspx page.
I tried to redirect to Hotmail.com, but that too did not work, and no exception is thrown.
Please find the below code section:
private void Application_Error(object sender, EventArgs e)
{
    // Code that runs when an unhandled error occurs
    Exception exc = Server.GetLastError();
    try
    {
        if (exc.Message.Contains("Maximum request length exceeded"))
        {
            //Response.Redirect("~/About.aspx", false);
            Response.Redirect("http://www.example.com", false);
        }
        if (exc.InnerException.Message.Contains("Maximum request length exceeded"))
        {
            Response.Redirect("http://www.HOTMAIL.com", false);
        }
    }
    catch (Exception ex)
    {
    }
}

Answer: Try the following setting in the web config file.
<system.web>
<httpRuntime executionTimeout="9999" maxRequestLength="2097151"/>
</system.web>

httpRuntime - HTTP runtime settings.
executionTimeout - no. of seconds to time out.
maxRequestLength - maximum upload size of the file
For more details click the link


Sum of a sum: $\sum_{n=1}^{11}n\left[\frac{1^2}{1+n}+\frac{2^2}{2+n}+\cdots+\frac{11^2}{11+n}\right]$

Question: The given sum is:
$$\sum_{n=1}^{11}n\left[\frac{1^2}{1+n}+\frac{2^2}{2+n}+\cdots+\frac{11^2}{11+n}\right]$$
I tried simplyfing it as:
$$1^2\left[\frac{1}{2}+\frac{1}{3}+\cdots+\frac{1}{12}\right] + 2^2\left[\frac{1}{3}+\frac{1}{4}+\cdots+\frac{1}{13}\right] +\cdots +11^2\left[\frac{1}{12}+\frac{1}{13}+\cdots+\frac{1}{22}\right]$$
Finding the sum of each diverging series seems too lengthy for a problem with obvious symmetries, so I don't think this method is correct.
Comment: It is unlikely you will get a good simplification. Is there a reason to expect one?
Answer: $$\begin{align}S&=\sum_{n=1}^{N} \sum_{k=1}^{N} {nk^2 \over k+n}\\&=\sum_{n=1}^{N} \sum_{k=1}^{N} {nk^2 +kn^2 \over k+n}-\sum_{n=1}^{N} \sum_{k=1}^{N} {kn^2 \over k+n}\\&=
\left(\sum_{n=1}^{N} \sum_{k=1}^{N} nk\right)-S
\end{align}$$
Thus, $$\begin{align}S&=\frac{1}{2}\sum_{n=1}^N\sum_{k=1}^N nk\\&=\frac{1}{2}\left(\sum_{n=1}^N n\right)\left(\sum_{k=1}^N k\right)\\&=\frac{1}{2}\left(\sum_{n=1}^N n\right)^2\\&=\frac{1}{2}\left({N(N+1) \over 2}\right)^2.\end{align}$$
Comment: @algorhythm Just finding symmetries in the problem can help.  It also helps to get rid of denominator stuff where possible.
Comment: (+1) oh yes, I was being stupid. It is still a sum over all pairs $(n,k)$.
Comment: Understood, thank you.
Comment: @algorhythm no prob
Comment: how is $\sum_{n=1}^{N} \sum_{k=1}^{N} {kn^2 \over k+n}$ equal to $S$?
Comment: @DS Swap indices
Comment: is that allowed?
Comment: @DS Relabel $n$ as $k$ and $k$ as $n$
Comment: @DS since both the sums go from 1 to N, it wouldn't matter if we swapped it since the variables mean the same thing. But if we change one term from k to n, we would have to swap the other term from n to k so that there is no loss in generality.


Big-O notation always holds for this two functions?

Question: For two any functions $f(n)$ and $g(n)$ always holds:
$f(n) = O(g(n))$ or $g(n) = O(f(n))$
Right?
Thanks
Comment: It's false. Let $f(x)=\cos x$ and $g(x)=\sin x$. Neither is big-O of the other.
Comment: $\sin$ and $\cos$
Comment: I don't understand you, That affirmation always holds? True or False.
Comment: It is false even if you assume $f$ and $g$ are monotonic. On the other hand, there is a special class of functions, called exp-log functions, which can be ordered linearly with big O.
Answer: That's not right. Let $f(x)=\cos x$ and $g(x)=\sin x$.
If $f(x)=O(g(x))$, then there would be some constant $C>0$ so that for $x$ sufficiently large, we would have
$$\tag{1}
|f(x)|\le C|g(x)|.
$$
But for any positive integer $n$, we have  $f(2n\pi)=1$ and $g(2n\pi)=0$. Since we can make $2n\pi$ arbitrarily large, this shows that $(1)$ cannot hold.
I'll leave it to you to show that $g(x)\ne O(f(x))$.
Comment: I might be missing something... But simply setting $C=1$ suffices to show that $\sin x \in O(\cos x)$ and $\cos x \in O(\sin x)$, since both functions are bounded no matter how large $x$ grows. That said, if you look at $f(x) = x \cos x$ and $g(x) = x \sin x$ then your argument holds.
Comment: @Peter They are both $O(1)$. But it is not true that $|\cos x|\le |\sin x|$ for all $x$ sufficiently large. I'm using the definition [here](http://en.wikipedia.org/wiki/Big_O_notation) for $f(x)=O(g(x))$ as $x\rightarrow\infty$.
Comment: yes, you're right, I got confused.


Display another field as 'Node author' if node posted anonymously

Question: Currently on my D6 site registered as well as anonymous users can post articles. A custom text field has to be filled by unregistered users while creating an article. This text field's value is shown as Node author for anonymous posters.
Now I am all set to upgrade this site to D7. I tried using the following snippet to display custom text field value as the 'node author' if posted by Anonymous user, But it has some issues...

menu_get_object() works only for full node view and not for teasers etc.
It also changes $name every where on the page eg: for unregistered comments too.

function mytheme_username_alter(&$name, $account) {
  $node = menu_get_object();
    if($account->uid == "0") {
      $name = $node->field_custom_author['und'][0]['value'];
     }
}
Question: How can I tweak this function to display custom text field's value as 'Node Author' if the node is created by an anonymous user, without changing $name elsewhere on the page?
If there's a better function/solution than this, i am all open to try that too.
Answer: You have two viable options:

In theme system, use either node.tpl.php file to do it, or probably better template_preprocess_node(&$variables). I'll discuss function as that's what I prefer. When using function, copy it to your own template.php, renaming to mytheme_preprocess_node(&$variables). As a source, use parent theme if it implements it. If not, or if there is no parent theme, use link I provided above.
Then find a line like this:
$variables['node'] = $variables['elements']['#node'];

and after it modify $variables['node'] as you see fit.
Use Computed Field to create a field that shows author's name, and in case of anonymous authors displays arbitrary text. Turn off displaying author and use this field instead.


How to create an average out of 3 Fivestar Fields?

Question: I want to create a Fivestar-Field which shows the average of 3 other ones.
Something like:
(Field A + Field B + Field C):3 = Field D
A,B and C are Fivestar-Fields which rate something and Field D is the average value out of the three.
I want the average to be showed via the star-widget of fivestar.
Is there a way to do that?
(I use Drupal 7)
Comment: So fields A, B, and C are voting fields (from the Fivestar module) on separate content types?
Comment: They are voting fields
Answer: Yes, You can able to do that using hook_node_presave
You can read three field values rating using $node and set using below command
<code>$node->field_name_of_your_fourth_field[$node->language][0]['rating'] = $average_value;
</code>


What bizarrities lurk within the decimal expansion of an irrational number?

Question: i.e. can we write
$\pi = 3.14159\dots X\dots$
where $X$ consists of (say) $10^{100}$ consecutive zeroes?
[Originally asked on reddit without response :-( ]
Comment: If pi is normal, then yes.  But this is unknown!
Comment: That would be hard to memorize for the pi decimal-counting geeks isn't it. 3.1415926....0000000000000000000000000000 (twenty hours later) 0000... Damn it! I messed up my count.
Comment: Here is an amusing website that allows you to search for the first occurrence of a digit string in pi.  http://www.angio.net/pi/
Comment: The exact outcome of the 2016 US presidential election is coded in there somewhere. But there's no way for us to find it, or recognize it. Every possible *false* result is in there too! (assuming pi is normal)
Answer: To expand on Dan Brumleve's comment; it is widely believed, but not proved, that, given any finite string of digits, that finite string appears somewhere in the decimal for $\pi$, in fact, occurs infinitely often, in fact, occurs about once every $10^n$ digits, where $n$ is the length of the string. The same is believed to hold true for $e$, $\sqrt2$, in fact, for pretty much any number known to be irrational and not constructed specifically to falsify the belief, but, again, nothing has been proved. For all we know, all the digits of $\pi$ from some point on are sixes and sevens.
Comment: @Arturo, actually, if every finite string appears once, then every finite string appears infinitely often, since every finite string is a prefix to infinitely many different finite strings. But of course you are correct that there's no density implication.
Comment: Just to check: my gut says that "any finite string of digits appears somewhere in the decimal expansion of $x$" is weaker than "$x$ is normal (or 10-normal)."  Is that so?
Comment: @IAMBrian: Yes: "normal in base 10" implies that any finite string of $n$ digits appears with density $1/10^n$; in particular, it occurs infinitely many times. "Any finite string of digits appears somewhere" only guarantees at least one occurrence.
Comment: Yes. "Normal" means "appears with the right frequency" - that's the "once every $10^n$ digits" in my answer. It's easy to make a number which isn't normal even though every finite string appears; just start with a number that is normal, and then put really long strings of threes in it from time to time. Well, you do have to be a little careful where you put those strings, but it can be made to work.
Comment: D'oh. Good point.


Route, set meta title in controller

Question: I have a route that takes data from APIs, so I would like to set the title in the controller and not in the getTitle function because it would mean calling 2 or more times the same API
Comment: You can return a title by setting #title in the top-level render array that you return
Answer: I don't think you can, not out of the box at least, but there's no reason to. Just use a static var, it will mean the API is contacted only once per request:
<code>function getTitle() {
  static $title = '';

  if (!strlen($title)) {
    $title = $this->getTitleFromAPI();
  }

  return $title;
}
</code>

Route, set meta title in controller


ValueError: could not convert string to float: '2 952.62'

Question: I have a dataframe with data registered as string.
I tried to get them as floats with astype function but it just doesn't work and I am struggling to understand why.
I am getting the following error :

ValueError: could not convert string to float: '2 952.62'

My data are either XXX.XX when there are decimals and XXX when there are not.
Comment: Your string appears to have a space in it.
Comment: I thought that was just the display
Answer: try this, where columname is the name of your column:
df[columname].str.replace(' ', '').astype(float)


Como ocultar as imagens do sistema, de aplicativos de galeria firemonkey android?

Question: Preciso que as imagens usadas no sistema não apareçam no aplicativo de galeria do android, pois são imagens usadas apenas pelo sistema e ao visualiza-las alguns clientes as apagam.
Answer: Para ocultar as imagens do seu sistema, basta criar um novo arquivo na pasta onde você colocou suas imagens, com o nome:

.nomedia

achei a resposta
aqui
após isso as imagens não irão mais aparecer no aplicativo galeria.
Fica assim na prática
<code>procedure botao_qualquer;
var
  a: TStringList;
  pasta: string;
begin

  pasta:= "caminho da pasta onde estão os arquivos";

  a:= TStringList.Create;
  a.SaveToFile(pasta+'.nomedia');
  a.Free;

end;
</code>


Roblox Place-to-place teleport problems

Question: I am creating a script that due to a condition(if), it will teleport the player to another place.
The language is RBXLua.
Here is the script:
----------
tex = "rbxassetid://1655327330"
x = math.random(10)
lg = game.lighting
pitch = 1
negpos = 0
player = game.Players:GetChildren()
z = 0
ys = 0
w = 0

----------
if x < 1 then
lg.Sky.SkyboxBk = tex
lg.Sky.SkyboxDn = tex
lg.Sky.SkyboxFt = tex
lg.Sky.SkyboxUp = tex
lg.Sky.SkyboxLf = tex
lg.Sky.SkyboxRt = tex
while true do
lg.FogEnd = lg.FogEnd - 1
if lg.FogEnd < 2 then
    game:GetService("TeleportService"):Teleport(1825330145, { player })
end
end

Answer: game.Players:GetChildren() will give you a table of all players (Player-instances).
Your code actually looks like this:
game:GetService("TeleportService"):Teleport(1825330145, { Player })

If this is a LocalScript, you can simply do game.Players.LocalPlayer to access the player-instance. If it's a server script however, you need to either do game.Players:GetPlayers() and access the first index of that table, or you need to send all players to that place.
To loop through all players in a place, you can make use of the in-pairs loop.
for index, player in pairs(game.Players:GetPlayers()) do
   print("Player's name is", player.Name)
end

Answer: I am still obtaining the "Unable to cast value to Object" error even after doing so. I don't understand what the "Object" is, it may be helpfull knowing so.
Comment: Hi! Could you show us the current code? Update your original post with it, and I'll take a look.

Roblox Place-to-place teleport problems