PHP rounding function not working for rounding up

Question: For the code below, sometimes the value $endorsepoints is not a whole number.  I want it to be rounded off, up or down, depending on normal math rules.
Then, I want to input the rounded number into two MySQL tables, comment and submission.
I want the number rounded up or down per normal math rules.
When the number is supposed to be rounded down (i. e. 5203.25), the correct rounded number (i. e. 5203.00) gets added to both comment and submission.
When the number is supposed to be rounded up (i. e. 5151.74), the correct rounded number (i. e. 5152.00) gets added to submission.  However, in this situation, the rounded down number (i. e. 5151.00) is added to comment.  How can I make the rounded up number go into comment in this situation?
   $endorsepoints = $endorsepoints * .01;

    $endorsepoints2 = ( $endorsepoints <= 10 ) ? 10 : $endorsepoints;

    $endorsepoints2 = round($endorsepoints2);

    $query1 = sprintf("INSERT INTO comment VALUES (NULL, %d, %d, '%s', %d, NULL)", $uid, $submissionid, $comment, $endorsepoints2);

    mysql_query($query1) or die(mysql_error());

    $query2 = sprintf("UPDATE submission SET points = (points + '$endorsepoints2') WHERE submissionid = '$submissionid'");

    mysql_query($query2) or die(mysql_error());

EDIT:  I want the same number inserted into both tables at all times.  My question is: why is it not?
Comment: Why not use the 2nd and 3rd arguments to round()?
Comment: Sorry I can't get the question. As I see `$endorsepoints2` in both cases is same number?? So what do you mean by _However, in this situation, the rounded down number (i. e. 5151.00) is added to comment._
Answer: $endorsepoints3 = $endorsepoints2;
$endorsepoints2 = round($endorsepoints2);

if($endorsepoints3 > $endorsepoints2) {
    //rounded down
} else {
    //rounded uo
}

I'm not sure if you were asking this, anyway.
Answer: First of all, the round() function will always round correctly i.e. 2.4 becomes 2 and 2.6 becomes 3, are you perhaps looking for floor() and ceil() and number_format() to round to lowest or highest, get decimals "and know about it"?
thereafter its as simple as using an if/else to run a query based on the result matching <==>
Answer: use ceil() instead of round()
it rounds only up
Comment: I'm trying to round up or down.


How to extract the substring within the element of an array

Question: I am creating a photo and video viewer in which each one has an array with the elements that are going to be inserted and I want to filter its format to store them in a third list
I had a player where one had a array and an intercommunication for photos and videos, then only in the photo section you could only add photos and in the videos you could only add videos, then what I want to do is that in a third array I add either Photo or video and filtering them looking for the extension of the file to add them to their corresponding array.
insert files without a specific order:
string fileList = { "Animals.jpg", "cars.mp4", "planes.mp4", "landscape.jpg", "gameplay.mp4", "freind.mp4", "grildfriend.jpg", "travel.mp4", "school.jpg", "youtube.mp4", "asdada.jpg"};

and then it will be like that:
string PhotoList[] = { "Animals.jpg", "landscape.jpg", "grildfriend.jpg", "school.jpg","asdada.jpg" };
string VideoList[] = { "cars.mp4", "planes.mp4", "gameplay.mp4" "freind.mp4", "travel.mp4", "youtube.mp4" };

so far I can only concatenate the two array in a array but this keeps the order of the previous two
Comment: None of the code you posted compiles...
Comment: Your code does not compile (however the reason for this is obvious) and you don't post any attempt to solve the question. If you are developing a media player, sorting file name according their extensions is something incredibly simple.
Comment: First you need to use a `for` loop to iterate over the `fileList` array. Then you need to look at the documentation for `string` to find a function to get the characters at the end.
Comment: You probably want to use a List/ ArrayList since the array size would be dynamic.
I'd do something like this:
```
    string[] fileList = new string[]{"pic.jpg","pic2.jpg","movie.mp4"};
    string filter = ".jpg"
    List filteredList = new List();
    for(int j=0;j<fileList.Length;j++){
        if(fileList[j].Substring(fileList[j].LastIndexOf("."))==filter){
            filteredList.Add(fileList[j]);
        }
    }
```
filteredList will now contain all the file names that end in ".jpg". You can access the list the same way you can an array.
Answer: if your first line is an array of strings the following should work to query your array into two different arrays. You will need to add a using statement for System.Linq as well.
var pictures = fileList.Where(p => p.IndexOf(".jpg") > 0);
var videos = fileList.Where(v => v.IndexOf(".mp4") > 0);

Comment: Please use proper methods to deal with file names/extensions - `Path.GetExtension` in particular (https://stackoverflow.com/questions/13003555/c-sharp-how-to-extract-the-file-name-and-extension-from-a-path covers all of them if you need link)
Comment: What if you have file `File.jpg.mp4` :)
Answer: Something like this:
var photoExt = new HashSet<string>{".jpg"};
var videoExt = new HashSet<string>{".mp4"};

string[] fileList = new [] { "Animals.jpg", "cars.mp4",
        "planes.mp4", "landscape.jpg",
        "gameplay.mp4", "freind.mp4",
        "grildfriend.jpg", "travel.mp4",
        "school.jpg", "youtube.mp4", "asdada.jpg"};

string[] photos = fileList.Where(f => photoExt.Contains(Path.GetExtension(f))).ToArray();
string[] videos = fileList.Where(f => videoExt.Contains(Path.GetExtension(f))).ToArray();

Comment: Since code is essentially the same as [suggested duplicate](https://stackoverflow.com/a/36138402/477420) consider at least explaining why yours better (like "HashSet of one element is far superior to Contains on array of one element")
Comment: @AlexeiLevenkov Didn't check duplicates at all :). Of couse, it is not superior(for small num of element) it is just the first option always if you need the search O(1)...


Using DeviceIoControl from C# code always returns empty output buffer

Question: I have a driver, which I want to use from my C# client app. The issue here is that my output buffer is always empty (0). When I use this driver from C code - everything works like a charm, so I think the issue is in my client C# code.
Extern is defined as below:
<code>    [DllImport(kernel, EntryPoint = "DeviceIoControl", SetLastError = true, CharSet = CharSet.Auto)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool DeviceIoControl(
        SafeFileHandle hDevice,
        UInt32 dwIoControlCode,
        IntPtr lpInBuffer,
        UInt32 nInBufferSize,
        IntPtr lpOutBuffer,
        UInt32 nOutBufferSize,
        ref UInt32 lpBytesReturned,
        [In] ref NativeOverlapped lpOverlapped);
</code>
And I am using it as:
<code>    public static T ReadVirtualMemory<T>(SafeFileHandle driverHandle, int offset) where T : unmanaged
    {
        var inBuffer = (object)new T();
        var nInBufferSize = Marshal.SizeOf(typeof(T));

        var outBuffer = (object)new T();
        var nOutBufferSize = Marshal.SizeOf(typeof(T));

        var data = new KERNEL_READ_REQUEST
        {
            Address = (ulong)offset,
            Size = (ulong)nInBufferSize,
            pBuffer = (IntPtr)inBuffer
        };

        IntPtr lpInBuffer = IntPtr.Zero;
        IntPtr lpOutBuffer = IntPtr.Zero;

        nInBufferSize = Marshal.SizeOf(data);
        lpInBuffer = Marshal.AllocHGlobal(nInBufferSize);
        Marshal.StructureToPtr(data, lpInBuffer, true);

        lpOutBuffer = Marshal.AllocHGlobal(nOutBufferSize);
        Marshal.StructureToPtr(outBuffer, lpOutBuffer, true);

        UInt32 lpBytesReturned = 0;
        NativeOverlapped lpOverlapped = new NativeOverlapped();

        Kernel32.DeviceIoControl(
            driverHandle,
            (uint)DriverMethod.ReadMemory,
            lpInBuffer,
            (uint)nInBufferSize,
            lpOutBuffer,
            (uint)nOutBufferSize,
            ref lpBytesReturned,
            ref lpOverlapped);

        outBuffer = (T)Marshal.PtrToStructure(lpOutBuffer, typeof(T));

        return lpBytesReturned == nOutBufferSize ? (T)outBuffer : default;
    }
</code>
I am not sure why, bytes returned = 8, though it should be 4. And as I've said - out buffer is empty.
Drver's code:
<code>    PKERNEL_READ_REQUEST readRequest = (PKERNEL_READ_REQUEST)pIrp->AssociatedIrp.SystemBuffer;
    PEPROCESS process;

    if (NT_SUCCESS(PsLookupProcessByProcessId(ProcessId, &process)))
    {
        DebugMessage("ReadRequest requested\n");

        KernelReadVirtualMemory(process, readRequest->Address, readRequest->pBuffer, readRequest->Size);

        byteIo = sizeof(PKERNEL_READ_REQUEST);
        status = STATUS_SUCCESS;
    }
</code>
and
<code>    NTSTATUS NTAPI MmCopyVirtualMemory
    (
        PEPROCESS SourceProcess,
        PVOID SourceAddress,
        PEPROCESS TargetProcess,
        PVOID TargetAddress,
        SIZE_T BufferSize,
        KPROCESSOR_MODE PreviousMode,
        PSIZE_T ReturnSize
    );

    NTSTATUS KernelReadVirtualMemory(PEPROCESS process, PVOID sourceAddress, PVOID targetAddress, SIZE_T size)
    {
        PSIZE_T bytes;

        return MmCopyVirtualMemory(process, sourceAddress, PsGetCurrentProcess(), targetAddress, size, KernelMode, &bytes);
    }
</code>
Probably this is smth about structure alignment, but I am not sure (In C client app sizeof structure is 18 bytes, in C# 32 bytes).
Please advise
Answer: First - I had to compile in x64.
Second - had to allocate memory for pBuffer
Below is a working example
<code>        var nInBufferSize = Marshal.SizeOf(typeof(T));
        var inBuffer = Marshal.AllocHGlobal(nInBufferSize);

        var data = new KERNEL_READ_REQUEST
        {
            Address = offset,
            Size = nInBufferSize,
            pBuffer = inBuffer
        };

        var requestSize = Marshal.SizeOf(data);
        var requestBuffer = Marshal.AllocHGlobal(requestSize);
        Marshal.StructureToPtr(data, requestBuffer, true);

        uint bytesReturned = 0;
        var overlapped = new NativeOverlapped();

        Kernel32.DeviceIoControl(
            driverHandle,
            (uint)DriverMethod.ReadMemory,
            requestBuffer,
            (uint)requestSize,
            requestBuffer,
            (uint)requestSize,
            ref bytesReturned,
            ref overlapped);

        var result = Marshal.PtrToStructure(data.pBuffer, typeof(T));

        return (T?)result ?? default;
</code>


How to add /admin/people as a tab to a custom menu?

Question: In a custom module (association), I ceated views that are accessible thru tabs:

The paths are defined in the views;

Adhérents et personnes -> /association (this one is also defined as a
menu item)
Adhérents -> /association/members
Personnes -> /association/persons

I'd like to add /admin/people as a fourth tab.
How can I do that?
Answer: In a custom module (mymodule), create a mymodule.links.task.yml file, and add the following:
mymodule.admin_people:
  route_name: entity.user.collection
  base_route: route.of.your.custom.menu
  title: 'Tab text goes here'
Here's what each part does:
mymodule.admin_people Is the identifier of your menu tab item (the file being *.links.task.yml means its the menutab file)
route_name  is the route the tab points to, and entity.user.collection is the route that corresponds to /admin/people .
base route displays your tab on the specified route. To find the route for your view, download the Devel module, turn it on, and go to "Routes info" to get your route. Usually a view is of the format view.[view_machine_name].[view_display_id], i.e. view.myview.page_1 . Check the "advanced" section of your view's management page for the display ID.
title is the text that will go into the tab.
Comment: also note, *.links.action.yml specifies action links i.e. add buttons you tend to see of some admin pages, and *.links.menu.yml creates menu items. Each one uses slightly different YAML, so look at other modules for clues.
Comment: It works!
[capture1](https://i.stack.imgur.com/xDqyV.png)
but when I go to `/admin/people`, I get my custom tabs miwed with standard Drupal tabs:
[capture2](https://i.stack.imgur.com/bmQCi.png)
How to avoid this?
Comment: And, by the way, how can I get the weight of each tab?
Comment: For your own tabs, you can set a 'weight' property. For seeing other tabs, take a look at https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-local-tasks , which explains how to set up derivers, among other interesting tricks.
Answer: Finally and because of the side effect of the solution proposed by Mike Nolan (see capture2 in my comment), I made it that way:
function association_menu_local_tasks_alter(&$data, $route_name) {

  $oCurrentUser = \Drupal::currentUser();
  switch ($route_name) {
    case 'view.association_members_and_persons.page_1':
    case 'view.association_members.page_1':
    case 'view.association_persons.page_1':
      if ($oCurrentUser->hasPermission('administer users')) {
        $data['tabs'][0]['association.people'] = [
          '#theme' => 'menu_local_task',
          '#link' => [
            'title' => t('Users'),
            'url' => Url::fromRoute('entity.user.collection'),
          ],
          '#weight' => 4,
        ];
      }
      break;
    default:
  }


Verificar conexão fechada

Question: Como posso verificar se uma conexão foi fechada de fato?
    $con = new Conexao();
    $con->abrirConexao();
    ...
    $con->fecharConexao();

Eu utilizo uma variável para instanciar a classe Conexao que está em outro arquivo. Gostaria apenas de saber como posso verificar se o método fecharConexão() de fato fechou a conexão anteriormente aberta.
Meu método para fechar a conexão é esse:
public function fecharConexao(){
    return mysqli_close($this->conexao);
}

Só gostaria de uma notificação (só para eu saber) de que a conexão encerrou. Como faço isso?
Answer: A função mysqli_close() retorna valor booleano
true: indica que executou com sucesso
false: indica que houve algum erro.
Basicamente, apenas verifique o valor de retorno.
Se retornar true, a conexão foi fechada.
Comment: só completando, se você quer poder recuperar isso a hora que quiser, guarde o retorno em um atributo da classe. Exemplo: A conexão iniciou `$this->aberta = true` a conexão terminou `$this->aberta = false` isso possibilitará criar um método como `public function estaAberta()` e essa função retorna o valor de `$this->aberta`.

Verificar conexão fechada


Intent - Not connection to the URL - No known activity to handle intent

Question: I am attempting to connect my emulator to a webpage using the eclipse android editor. I have been following some online tutorials from android and thought I had solved my problem, but I get an error that there is no action available to handle my intent when trying to redirect to google.com. Does anybody have any idea what I did wrong? I added the intent filler to my manifest and used the proper syntax, but I am unsure why I cannot get the emulator to redirect. Any help/advice would be appreciated, thanks!
MainActivity
package com.example.webpage;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
           Button mButton = (Button) findViewById(R.id.button1);
            mButton.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    Uri uri = Uri.parse("http://www.google.com");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);

                }

            });

    }
}

Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.webpage"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.webpage.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
        </activity>
        <activity android:name="webpage"></activity>
    </application>

Logcat
06-06 16:39:37.090: E/AndroidRuntime(939): FATAL EXCEPTION: main
06-06 16:39:37.090: E/AndroidRuntime(939): Process: com.example.webpage, PID: 939
06-06 16:39:37.090: E/AndroidRuntime(939): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=http://www.google.com }
06-06 16:39:37.090: E/AndroidRuntime(939):  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1632)
06-06 16:39:37.090: E/AndroidRuntime(939):  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
06-06 16:39:37.090: E/AndroidRuntime(939):  at android.app.Activity.startActivityForResult(Activity.java:3424)
06-06 16:39:37.090: E/AndroidRuntime(939):  at android.app.Activity.startActivityForResult(Activity.java:3385)
06-06 16:39:37.090: E/AndroidRuntime(939):  at android.app.Activity.startActivity(Activity.java:3627)
06-06 16:39:37.090: E/AndroidRuntime(939):  at android.app.Activity.startActivity(Activity.java:3595)
06-06 16:39:37.090: E/AndroidRuntime(939):  at com.example.webpage.MainActivity$1.onClick(MainActivity.java:23)
06-06 16:39:37.090: E/AndroidRuntime(939):  at android.view.View.performClick(View.java:4438)
06-06 16:39:37.090: E/AndroidRuntime(939):  at android.view.View$PerformClick.run(View.java:18422)
06-06 16:39:37.090: E/AndroidRuntime(939):  at android.os.Handler.handleCallback(Handler.java:733)
06-06 16:39:37.090: E/AndroidRuntime(939):  at android.os.Handler.dispatchMessage(Handler.java:95)
06-06 16:39:37.090: E/AndroidRuntime(939):  at android.os.Looper.loop(Looper.java:136)
06-06 16:39:37.090: E/AndroidRuntime(939):  at android.app.ActivityThread.main(ActivityThread.java:5042)
06-06 16:39:37.090: E/AndroidRuntime(939):  at java.lang.reflect.Method.invokeNative(Native Method)
06-06 16:39:37.090: E/AndroidRuntime(939):  at java.lang.reflect.Method.invoke(Method.java:515)
06-06 16:39:37.090: E/AndroidRuntime(939):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:776)
06-06 16:39:37.090: E/AndroidRuntime(939):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
06-06 16:39:37.090: E/AndroidRuntime(939):  at dalvik.system.NativeStart.main(Native Method)

Answer: You must start the Url with either http:// or https:// in order to avoid ActivityNotFoundException
so you should check for the condition like this:
if (!url.startsWith("https://") && !url.startsWith("http://")){
    url = "http://" + url;
}
Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(it);

Comment: Look at this post. May be your emulator is missing the browser app? http://stackoverflow.com/questions/14596227/activitynotfoundexception-no-activity-found-to-handle-intent-act-android-inte One thing you can do is try creating a new VD and see if that helps. Also, did you try on a real device yet?
Comment: I agree we should ehck to make sure it conforms to the scheme. But his example clearly has a URL starting with http://
Comment: I have my URL starting with http:// but I will add the code and see if it changes anything real quick. UPDATE - still nothing, I don't know why this isn't working.
Comment: @Raghu Is it possible that there could be some kind of connection blockage between a firewall and the emulator? I enabled IIS and allowed the adk mime type to go through, but I can't even get a response from a post on a localhost machine that I am running this on.
Comment: can you open any web page in your emulator web browser??
Comment: @Pankaj No. The emulator returns an error when I try to redirect to a webpage. I assume I can connect to my localhost using post because I am able to grab a response and log it, but it is always unintelligible. I know my php script is okay because it works if I access the localhost and use another script. It has to be some sort of configuration error with my emulator.


Azure ServiceBus message from .net core does not parse in .net 4.6.1

Question: I have a ServiceBus in Azure and a number of queues.
I have one service written in .net core which sends data into the queue like so:
queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
string example = "Hello World!";
var message = new Message(Encoding.UTF8.GetBytes(example));
await queueClient.SendAsync(message);

Other service, written in .net framework 4.6.1 is listening on that same queue like so:
queueClient.OnMessage(ProcessQMessage);
private void ProcessQMessage (BrokeredMessage receivedMessage) {
    var tmpBytes = receivedMessage.GetBody<byte[]>();
    ...
}

For some reason i get an exception from receivedMessage.GetBody(). I get the same exception trying to parse it to string and object as well:

There was an error deserializing the object of type System.Byte[]. The input source is not correctly formatted.

I understand that the problem comes from the fact that core and framework work a little differently. Didn't expect this to be a problem though.
Comment: Any process now? If you still have any problem, please feel free to let me know.
Comment: Thanks for the answer, but I decided to move away from .net core, so it is no longer relevant
Answer:
If the systems are running with old client, you will be likely stuck with XmlObjectSerializer (data contract serializer) like our .netfull client. But things will not be broken. Sample code is like below which is exactly what happens underneath in the .netfull client.
var bytes = your bytes;
var serializer = DataContractBinarySerializer<byte[]>.Instance;
using (MemoryStream stream = new MemoryStream())
{
    serializer.WriteObject(stream, bytes);
    var msg = new Message(stream.ToArray());
    var client = new Microsoft.Azure.ServiceBus.QueueClient(ConnectionString, Queue);
    await client.SendAsync(msg);
    await client.CloseAsync();
}

For more details, you could refer to this article and this issue.
Comment: You demonstrate how to send data into the queue, this part works fine. I can also recive these messages justfine as long as I send and receive it from the same framework. My question is how to send it from .net Core and receive it correctly in .net Framework 4.6.1


Usar/Escapar @ em view CSHTML

Question: Estou com um código jQuery na pagina CSHTML e estou com problema para validar o email com uma expressão regular, pois o @ é um comando Razor em .NET. Como proceder para resolver este problema?
Segue o script:
$("#formEsqueceuSenha").submit(function(event) {
        $(".message").hide();
        $(".Error").hide();
        var sEmail = $("#email").val();
        if ((sEmail == '') || (sEmail == null)) {
            $("#email").focus();
            $(".message")
                .text('Por favor, informe um email válido.')
                .show();
            event.preventDefault();
        } else {
            var filtro = "/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i";
            if (!filtro.test(sEmail)) {
                $("#email").focus();
                $(".message")
                    .text('E-mail digitado esta invalido. Por favor corrigir.')
                    .show();
                event.preventDefault();
            } else {
                return;
            }
        }
    });

E o erro que ocorre:

Comment: Como a pesquisa não ajuda eu não achei mas tenho certeza que isto foi perguntado recentemente. Se não me engano foi o @Cigano que respondeu, mas posso estar enganado.
Comment: @bigown A meu ver, essa pergunta já está respondida.
Answer: Para escapar, onde tem @ coloca @@.
Ficando assim:
 var filtro = "/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i";

Usar/Escapar @ em view CSHTML


Symantec network intrusion protection slowing backups to a crawl

Question: We recently went to a disk-based appliance solution for our company's backups.
I've set everything up and monitoring the backups shows that they are crawling.  Like 64 MB/min on a 1 GB ethernet network.
We're also running Symantec Endpoint Protection on all servers and clients.
I've found that if I disable network intrusion prevention on a server, the speed of the backup jumps to 1GB/min.  That is very significant.
Question is, what does network intrusion prevention do for servers?  From what I can tell it's there to block malware from websites and since no one really browses the web from these servers can I just disable it for servers?
Answer: I would recommend that you turn Network Intrusion Prevention off on all of your systems.
http://www.symantec.com/business/support/index?page=content&id=TECH104434
http://www.symantec.com/business/support/index?page=content&id=HOWTO80870
Comment: Personally I would turn it off on all systems and make sure the Windows Firewall is turned on. That in combination with the real time Symantec AV engine should provide sufficient protection. I haven't seen any Symantec installation where Network Intrusion Prevention is enabled that hasn't had the same issue you're having.
Comment: I was thinking about turning it off for servers and leaving it on for clients.  Would that work?


How can I render databound values inside of a custom control?

Question: I'm placing a custom control inside of an existing repeater template.
<ItemTemplate>
  <custom:MyControl>
    <something>
      <%# Eval("Firstname") %>
    </something>
  </custom:MyControl>
</ItemTemplate>

Is there any way that I can somehow get the value of <%# Eval("Firstname") %> without adding it as a property to my custom control?
<custom:MyControl Firstname='<%# Eval("Firstname") %>' />

I have a bigger need, as in I want to define an entire html structured inner property inside of <something> and it will be a disaster to do this inside of a property.
So, my repeater is databound, and apparently the control I'm placing within it is not databound, yet the values can be passed through via the property tags...
I found another answer stating it wasn't possible, but it's also 5 year old question. Eval inside an ASP.net repeater doesn't work inside another control
Grasping at straws, hoping for a solution.
Answer: You have to create a templated User Control with properties having TemplateContainer attribute. See following article for an example.
Creating a Templated User Control
Comment: I could be immediately misunderstanding, but it still looks like the only data-bound available values are going to come from within that templated controls own data source. But I'm going to give this a good read. Thank you for your fast reply. This has become very frustrating.
Comment: The thing is without having properties you can't pass values into a user control. Unless you use session or query string, which are not ideal in this case. If you have lots of properties to bind I'd suggest using this method rather than passing the values through properties.
Comment: Otherwise, if you have lots of properties to bind how about creating a class with those properties and create just one property of that class within your user control. The data source for your repeater should be a collection of that class. https://derekreynolds.wordpress.com/2010/08/18/how-to-embed-a-usercontrol-in-a-repeater/
Comment: Interesting. One issue here is I can only go one way. I can't access the code from the repeater. I can only place a custom control within it. Here's a thought. What if I could implement some type of databound interface on my control, and climb the control tree to get the data from the `` that it's sitting in? If I had some way of creating a list(of string, string) on names and values for dataitems I think that would work.
Comment: You don't need to have access to code behind code if you need to bind data objects. You can do it within the markup. You can use  MyProperty='<%# ((MyObjects.SomeBusinessObj)Container.DataItem).CustomProperty %>'. See detailed answer here http://stackoverflow.com/questions/4246725/repeater-control-with-objects
Comment: By the way, why don't you have access to code behind?
Comment: I meant I don't have access to the source code of the parent repeater. I created a templated control based on that tutorial, but still no way to grab the values from the parent ``. It drives me crazy that I can pass these values in via property tags, but not use them within the control. So my control isn't databound but the parent obviously is.
Comment: I think I may have figured this out. Will let you know.
Comment: take a look at my answer. So far so good. Would love to hear your thoughts.
Answer: I was able to figure this out, and I'd say the only reason I didn't figure it out sooner is due to testing every combination of methods, but missing a vital element in each one.
<ParseChildren(False)>
Public Class Something
    Inherits Button ' Just picked something

    Public Property InnerStuff() AS String

    Protected Overrides Sub OnLoad(e As EventArgs)

        EnsureChildControls()

        If HasControls() Then

            ' Interesting, if Eval() has taken place, a
            ' DataBoundLiteralControl is created as a child
            ' control.
            If TypeOf Controls(0) Is DataBoundLiteralControl Then
                Dim instance As DataBoundLiteralControl = CType(Controls(0), DataBoundLiteralControl)
                ' I can push the text into a property
                InnerStuff = instance.Text

            ' If no databinding occurred, it creates LiteralControl
            ElseIf TypeOf Controls(0) Is LiteralControl Then
                Dim instance As LiteralControl = CType(Controls(0), LiteralControl)
                InnerStuff = instance.Text
            End If

        MyBase.OnLoad(e)

    End Sub
End Class

Maybe there's a cleaner way, but this appears to be working, and my markup now looks like this:
<custom:MyControl>
    Inner text, with or without <%#Eval("...")%>
</custom:MyControl>


Boundedness of almost sure convergence random sequences

Question: Suppose $\{X_n\}$ is a sequence of random variables with $0<X_n\leq n$ and $X_n\rightarrow c$, almost surely. Form the definition of almost sure convergence, we obtain
$$P(\cap_{n=1}^\infty\cup_{m=1}^\infty |X_{n+m}-c|\geq\epsilon)=0,\ for\ all\ \epsilon>0.$$
Thus, defining $A=\{\cup_{n=1}^\infty\cap_{m=1}^\infty |X_{n+m}-c|\leq\epsilon\}$, we know that $P(A)=1.$
On the set $A$, there exists a constant $N(\epsilon)$ such that for all $n\geq N(\epsilon)$, $$c-\epsilon\leq X_{n+m}\leq c+\epsilon.$$
For $n<N(\epsilon)$, we know that $$0<X_n\leq N(\epsilon),\ a.s.$$
Therefore, for any $\epsilon>0$, there exists a constant $K(\epsilon)$ such that $$P(\sup_n|X_n|\leq K(\epsilon))=1.$$
Is the above proof correct?
Answer: What are you trying to prove?  The fact that a sequence of random variables that converges almost surely is almost surely bounded is obvious: any sequence that converges is bounded.  But your last statement appears to say that there is some uniform bound $K$ such that all $|X_n| \le K$ almost surely, and that is false.  For example, consider $X_n$ defined on the probability space $[0,1]$ with Lebesgue measure, with $X_n(t) = n$ for $0 < t < 1/n$ and $0$ otherwise.
Comment: Sorry for the confusion. I want to study the following question. For the above sequence $\{X_n\}$, for some constant $k$, which of the following statements are true:$$\lim_nP(X_n>k)\rightarrow0,$$ $$P(\lim_nX_n>k)=0,$$ $$\lim_nP(\sup_nX_n>k)\rightarrow0,$$ $$P(\lim_n\sup_nX_n>k)=0?$$


Fibonacci algorithm in C — why does this work as a return value?

Question: I came up with the following code to work out Fibonacci sequence.
My main question is, why does it return the correct value? If I added a line telling it to return a result when a==1, I'd understand getting the correct return value, but as it is, I can't work it out.
I'd also like to know if there are any advantages in using the normal recursive algorithm over this one?
int calculate(int a,int result,int old)
{

    if (a>0)
    {
        printf("%d ",result);
        return calculate (a-1,result+old,result);
    }

}

int main()
{
    int number,choice;
    printf("To start from 0 enter 0. To start from one enter any other number.\n");
    scanf("%d",&choice);
    printf ("Choose the number of times you wish to go for.\n");
    scanf("%d",&number);
    if (choice==0)
    {
        printf("Result= %d",calculate(number,0,1));
        return 0;
    }
    printf("Result= %d",calculate(number,1,0));

    return 0;

}

Comment: You mean, in the `a==0` case, where you forgot to have it return anything, how does it magically work?  You didn't tell it what to return, so it returned something random (this is what's called *undefined behavior*), but by good luck (or, actually, bad luck) it happened to return what you wanted.  Obviously you wouldn't want to depend on it, though.  Good compilers will warn you about this.
Comment: Since `calculate` does not always return a value, your code is malformed.  You should have `return 0;` or something to handle the case when `a` is zero or negative.
Comment: Wouldn't a decent compiler at least generate a warning about the calculate function - along the lines of not all code paths return a value?
Comment: I assume it would be very bad practice to say 'it works, so leave it like that', and that it's better to add it explicitly?
Comment: @Skizz Yes.  (From this we can conclude that Orangesandlemons was probably not using what we would consider a decent compiler.)
Comment: @Orangesandlemons Yes, yes, 1000% yes.  Code like this magically "works" for just as long as you're looking at it, and then it starts failing precisely when you ship it to a customer.
Comment: @ steve, yes. Although to get the correct result I'd actually need to return a==1, so would adapt my code to 'if a==1' return result, else...'
Comment: Using codeblocks, so I assume the default would be GCC?
Comment: Actually, looking at the code, the printf's in main won't print the right result will they? The printf in calculate probably does though.
Comment: Probably Code::Blocks uses GCC, but which version of GCC, and which compilation options (and which default version of the standard).  GCC 4.x uses the very old C90 (C89) standard by default; GCC 5.x uses the C11 standard (and no version of GCC uses the C99 standard by default, AFAIK).  You need to compile with `-Wall` and maybe `-Wextra` and preferably `-std=c11` or `-std=gnu11` if you're using a 4.x version of GCC.  I add more warnings, and `-Werror` so warnings are treated as errors.
Comment: @ skizz, no; the printf in main prints the right result, at least when I compile with codeblocks.
Comment: Note that you should probably end the `printf()` format strings with `\n` so that each number is printed on its own line.  Output will be buffered until a newline is printed or the buffer fills.
Comment: All recursive functions should have code to handle one or more base cases (which evaluate the result without further recursion), and one or more recursive cases where the final result is calculated in terms of a slightly different invocation of the recursive function for which the result is, presumably, easier to calculate.  Your function does not handle the base case explicitly.  You are unlucky that you're getting a useful answer from it.
Comment: @ Jonathan, good to know. To be honest, it's quite rudimentary- I'd also want to replace int with at least a double etc. etc. It was mainly thinking about the differences between this and the classic recursive algorithm that made me even bother to see what the return value was (the original version had an 'else return 0' and relied solely on the print in calculate();)
Comment: My guess that you need a `return 0;` is wrong — you need an 'or something' and I think the 'or something' that you need is `return old;`.  You might consider allowing the user to enter the two starting numbers, so you can generate arbitrary Fibonacci sequences, rather than restricting them to 0 and 1.
Comment: @Jonathan-   Thanks, your suggestion 'if a==0 return old' does save me a line of code if I want to keep printing out the sequence as well as having a return value. I did already have working code, using 'if a==1, return result' as the other case (and converting the current if to an else) (the return 0 was when I didn't need a return value.)
Comment: I'd just add a single line `return old;` after the close brace of your `if (a > 0) { … }` code — actually, that's what I did.  That then handles obstreperous users entering -99 when you expect them to enter something sane like 12.  Note that you should really check that the `scanf()` operations succeed: `if (scanf("%d", &number) != 1) { …report error and exit… }` or something similar.
Answer: It is recommended for this case to receive a value and return one too. You could simplify the code as follows:
/*Recursive fibonacci function*/
#include <stdio.h>

long fibonacci(int);

int main()
{

    long result;
    int number;

    printf("Enter an interger: ");
    scanf("%d", &number);
    result = fibonacci(number);
    printf("Fibonacci(%d) = %ld\n", number, result);

    getchar();
    return 0;

}

//Recursive definition of function fibonacci
long fibonacci(int n)
{
   if( n == 0 || n == 1)
       return ((long) n);
   else
       return fibonacci(n - 1) + fibonacci(n - 2);
}

Recursive methods are great but it consumes a lot of memory and iterative option seems so inefficient to solve a fibonacci series.
based in "c/c++". Deitel & Deitel


Parse Error. unexpected end of file. (PHP)

Question: Here is my code:

        <title>
        </title>

        <?php
            $username = $_POST['username'];
            $password = $_POST['password'];

            if (($username=="x")AND($password=="y"))
            {
                echo "You are logged in as".$username.";
            }
        ?>

I get a parse error:

Parse error: syntax error, unexpected end of file, expecting variable
  (T_VARIABLE) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN)
  on line 17
Comment: I suggest using an IDE such as [Netbeans](http://netbeans.org) - this will make simple errors like this much easier to spot
Answer: Your echo use is incorrect, you have double quote " problem :
echo "You are logged in as " . $username;

See echo examples for better understanding.
Answer: You are either missin " or you have one more "
echo "You are logged in as".$username.";

Can become
echo "You are logged in as".$username."";

or
echo "You are logged in as".$username;

Or even better solution:
echo "You are logged in as {$username}";

And for better readibility of your code, dont use AND, use &&
Answer: Here is the completely fixed code.

        <title>
        </title>

        <?php
            $username = $_POST['username'];
        $password = $_POST['password'];

            if (($username=="x")AND($password=="y"))
            {
                echo "You are logged in as".$username;
            }
        ?>

Answer: Double quote (") problem :
echo "You are logged in as".$username.";

You can do like this :
echo "You are logged in as {$username}";


controlling what user sendmail runs scripts in aliases

Question: Suppose I have a line like this in my /etc/aliases:

foo-bar: "|/etc/smrsh/some_script"

some_script is being run as user mail, but I need it to be running as user nobody.
I'm using procmail as the local delivery agent, and the system is some bastardized RHEL.
How can I configure sendmail or procmail to do what I want?
Answer: You can do this with sudo and another script.  In /etc/sudoers, allow user mail to run commands as user nobody (and only user nobody) without a password, something like this:
mail  ALL = (nobody) NOPASSWD: /usr/bin/script2

then the contents of some_script will be a wrapper for script2:
sudo -u nobody /usr/bin/script2

script2 will then execute as user nobody.
Note I make no guarantees that there aren't huge security holes in this.


Como guardar retorno em requisição Ajax em uma variável

Question:
Tentei o código seguinte, mas não funciona

    function getCategoria(id){
        var categoria;

        $.ajax({
            url: "../control/anuncio/index.php",
            data:{
                 method: 'get_categoria',
                 id_categoria: id
            },
            method: "post",
            dataType: "json",
            success: function(retorno){
                 categoria = retorno.categoria;
            }
        });

       return categoria;
    }

Comment: da um console.log(retorno), e nos mostrá o resultado.
Answer: O Ajax funciona de forma assíncrona, ou seja, a requisição é enviada e o restante do código continua a ser executado.
Para capturar e exibir o valor do retorno da requisição, é necessário adicionar essas funções dentro do callback de sucesso.
function getCategoria(id){
    $.ajax({
        url: "../control/anuncio/index.php",
        data:{
             method: 'get_categoria',
             id_categoria: id
        },
        method: "post",
        dataType: "json",
        success: function(retorno){
             exibeMensagem(retorno.categoria);
        }
    });
}

function exibeMensagem(msg) {
    alert(msg);
}

Uma outra forma é adicionando a opção async:false,. Ex:
$.ajax({
        url: "../control/anuncio/index.php",
        async: false,
        data:{
             method: 'get_categoria',
             id_categoria: id
        },

Porém há um problema. Os navegadores atuais exibem o alerta:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

O motivo? Em breve isso será removido e você não poderá utiliza-lo. Segundo a própria especificação da API...

Requisições síncrona está em processo de remoção da plataforma web, pois tem efeitos prejudiciais para a experiência do usuário final.
Os desenvolvedores não devem passar falso para o argumento assíncrono quando o objeto global atual é um Window. Os usuário são fortemente encorajados a avisar sobre tal uso em ferramentas de desenvolvimento e pode gerar a exceção InvalidAccessError

Claro que não irão remover de uma outra para outra, porém o ideal é se adequar o quanto antes. Então o recomendado é você criar uma outra função para tratar o retorno da requisição (como mostrado no primeiro exemplo).
Answer: Ajax é uma função assíncrona, portanto o programa não irá esperar executar o ajax para depois dar o retorno da sua variável categoria. Mas para nossa sorte, podemos fazer a função ajax ser síncrona adicionando a propriedade async como false:
function getCategoria(id){
    var categoria;

    $.ajax({
        url: "../control/anuncio/index.php",
        data:{
             method: 'get_categoria',
             id_categoria: id
        },
        method: "post",
        dataType: "json",
        async: false,
        success: function(retorno){
             categoria = retorno.categoria;
        }
    });

   return categoria;
}

Dessa forma, a linha return categoria; só será executada após finalizar a requisição.


Rails - link_to helper with data-* attribute

Question:
Possible Duplicate:
Best way to use html5 data attributes with rails content_tag helper?

How can I use html5 data-* attrubute in my link_to helper (Rails)
The API says that I have to use this format link_to(body, url, html_options = {}) but I have an error when I put it in html_options
Ex:
link_to "whatever", @whatever_path, { class: 'my_class', data-tooltip: 'what I want' }

Comment: what does your current attempt look like?
Answer: Just pass them in... Rails has a default :data hash
= link_to body, url, :data => { :foo => 'bar', :this => 'that' }

One gotcha - you must surround symbols with quotes if they include a dash:
:data => { :'foo-bar' => 'that' }

Update: In Rails 4, underscores are automatically converted to dashes, so you can do this:
:data => { :foo_bar => 'that' }

Alternatively you can just write it directly:
= link_to body, url, :'data-foo' => 'bar', :'data-this' => 'that'

Update 2: As pointed out in the comments, Ruby 1.9+ allows this syntax, which is now the preferred formatting:
{ data: { foo: "bar" } }

Comment: I'd like to point here for future visitors that with the new Ruby 1.9 syntax, only the first method works. So, you can do this: data: { type: 'remote' } but not this: 'data-type': 'remote'
Comment: For Rails 3.0.9 specifically, you have to use the direct route with `:'data-foo'`. I might be doing something wrong, but using the `:data => {}` method was putting the hash directly into the HTML.
Comment: I think it was in a [Railscast](http://railscasts.com)? I'm not sure. I've been using it for awhile. It's defined in the Rails source if you want to poke around.
Comment: It works perfectly, May I ask => where did you notice of that :data syntax?
Comment: data: { foo: {bar: 'that' }
Comment: The gotcha is actually that underscored entities are dasherized automatically. :data => { :foo_bar => 'that' } becomes data-foo-bar="that". No need to quote the symbols.
Answer: Add a data- attribute by doing the following:
link_to "Hello", hello_path, :"data-attribute" => "yeah!"


How to solve in a correct algebraic form

Question: $$0.45(x-2) - 0.35x = 4.40$$
I know the answer is $x=53$.
Can someone please help by showing me how to write out the solution in the correct algebraic form (get to "x" by doing the same thing to one side of the = as you do the other side).
Comment: Expand the expression on the left. Regroup the terms with $x$. Move the constant term to the right. Divide to isolate $x$.
Answer: $$0.45(x-2)-0.35x=4.40$$
$$\implies0.45x-0.9-0.35x=4.40$$
$$\implies 0.1x=5.3$$
$$\implies1x=53$$
or $$x=53.$$
Comment: I sincerely appreciate your reply & solution!! Trying to re-learn algebra to help my child.
Answer: We expand the left hand side,
$$
  0.45x - 2\times 0.45 - 0.35x = 4.40,
$$
that is
$$
  0.10 x - 0.90 = 4.40.
$$
Now, we add $0.90$ to each side,
$$
  0.10 x = 5.30,
$$
then we divide the two sides by $0.10$. The solution is
$$
  x = 53.
$$
Comment: Big mahalo Eric!
Answer: $0.45(x-2) - 0.35x = 4.40$
Leftmost number is the step number for Steps $1$ to $5$

$45(x-2) - 35x = 440$ (multiplying all terms on both the sides by $100$)
$9(x-2)-7x=88$ (dividing all terms on both the sides by $5$)
$9x-18-7x=88$ (opening the bracket)
$2x=106$ (adding $18$ to both the sides)
$x=\frac{106}{2}=53$ (dividing both the sides by $2$)
Comment: I appreciate your help Vikram!


Lost DataContext when navigating back in Frame (SplitView) in UWP

Question: I'm writing an Universal App in C# for Windows 10 using the SplitView with a frame for navigation.
I have a sidebar with a list that I load dynamically and, when I click on one of the items, I navigate to a page using the model from the menu to indicate which item I should load in the Frame.
I followed this sample: Windows-universal-samples/Samples/XamlNavigation/
The only difference is, instead of having multiple pages, I have only one page that is loaded every time I select a different item with its specific ViewModel. I use Autofac to load the ViewModels and MyFrame.Navigate(typeof(DetailsPage), idOfItem);to load the page.
The problem is, every time I navigate to the next page, it seems that the instance of the previous one is lost and when I navigate back, it loads a new instance. This kind of thing doesn't seem to happen when I'm navigating in the RootFrame and it didn't happen in Windows Phone 8.1.
I've been searching for a solution on the Web for hours, but I can't find anything relevant.
Does anyone know why this could be happening?
I hope I was clear enough with my question.
Thank you in advance for the answer.
Answer: The behavior you observe is correct and as expected. You have two options:
You can use Page.NavigationCacheMode, set it to Required. This is easy, but may consume a lot of memory.
Or you can save page state in OnNavigatedFrom and restore it in OnNavigatedTo. In fact, depending on your scenario, it may not even be necessary to save state in OnNavigatedFrom, assuming the state (your DataContext) can be constructed when returning to the page in the same way that you constructed it when first comming to the page.
Comment: I've tried the NavigationCacheMode, didn't work, when a navigate for the second time and go back, the instance stays the same, not the previous one.
You mean by tombstoning the page everytime I navigate away? I don't know, reloading the DataContext again seems a bit too painful, but if that's the only way...
Comment: If reloading your DataContext is "too painfull", you may have to look into caching it. But of course your cache should be independent of the page instance, or it will disappear with the page. But be careful, a cache without a policy (or a bad one) is another name for a memory leak.
Comment: BTW, "thombstoning' is Windows Phone 7 terminology, and not regularly used any more. But yes, that is basically what I am suggesting.
Comment: Okay, I'm just not sure of how to save the page's state on W10, is it the same as WP8?


Cordova Application size huge increase after adding Crosswalk web View plugin [VS 2015]

Question: I am building a simple cordova app using framework7 in vs community edition 2015, the default app build apk size is around ~ 3 mb, as for using smooth transitions etc. I ended up using crosswalk web view embed, but after embedding the apk size have jumped to ~29 mb in size and no matter i tried  cannot find any solution to it. the official crosswalk library claims a increase of only 15 mb in current size of application, while what i am getting is too much.
Target Device is android. Cordova CLR version is 6.0.0 , target andorid is 4.0+
any help would be much appreciated.
thanks
Comment: If your app doesn't need all of Crosswalk features, you might use the Crosswalk Lite version and get about 12-14MB increase in the APK size.
Comment: hi, i think crosswalk lite is dead and not supported anymore.
Comment: Yes, both Crosswalk and Crosswalk Lite have been discontinued, but they still work well enough to support Android 4.x.
Answer: I created a blank cordova project and added cordova-plugin-crosswalk-webview. Then build it into apk files. I got two output files with plugin: android-armv7-release-unsigned.apk : 22.7 mb and android-x86-release-unsigned.apk: 26.2 mb. Without plugin : android-release-unsigned.apk : 261 kb.
I uncompressed android-x86-release-unsigned.apk file and found out that the file libxwalkcore.so is significantly huge, almost 50 mb:
ScreenShot:

So I think you are having the correct output. The downloaded library will give an increase of 22 to 26 mb in size.

the official crosswalk library claims a increase of only 15 mb in current size of application

It could probably be the result of documentation update's delay. You can report this issue to the CrossWalk official website.


Inconsistent Empirical Risk Minimization procedure, but why?

Question: Given a random variable $Y$ and the typical squared loss function:
$$L(Y,\hat{Y}) = (Y-\hat{Y})^2$$
the minimizer for expected loss $E[L(Y,\hat{Y})]$ is know to be the mean, $\hat{Y} = E[Y] = \mu$.
If we take $n$ $IID$ samples from the distribution of $Y$, we can describe an Empirical Risk Minimization(ERM) procedure:
$$\hat{Y} = \arg\min_{Y^*} \sum_{i=1}^n (Y_i - Y^*)^2$$
$$\implies \hat{Y} = \frac{1}{n}\sum_{i=1}^nY_i$$
$$E[\hat{Y}] = \mu$$
hence, it is consistent.
Now let's assume that $Y \sim N(0,\sigma^2)$ and our loss function is as follows:
$$L(Y,\hat{Y}) = e^{2(Y-\hat{Y})} - 2(Y-\hat{Y}) - 1$$
The mimizer for expected loss $E[L(Y,\hat{Y})]$ can be shown to be $\hat{Y} = \sigma^2$ using the fact that $e^{2Y}$ is lognormal with $E[e^{2Y}] = e^{2\sigma^2}$.
If we again apply ERM procedure:
$$\hat{Y} = \arg\min_{Y^*} \sum_{i=1}^n L(Y_i,Y^*)$$
$$\implies \hat{Y} = \frac{1}{2} \, \ln \left( \frac{1}{n} \sum_{i=1}^n e^{2Y_i} \right)$$
$$E[\hat{Y}] \not\rightarrow \sigma^2$$
I would like to understand why the procedure is not consistent in this case. Which assumptions of ERM am I violating?
Comment: By the strong law, $(1/n)\sum_{i=1}^n e^{2Y_i}$ converges a.s. to $\mathbb{E}[e^{2Y}]=e^{2\sigma^2}$. Hence, $(-1/2) \ln \left(n/\sum_{i=1}^n e^{2Y_i}\right)$ converges a.s. to $\sigma^2$, by continuity.
Comment: @Zen I ran your code. true_var <- 100; N <- 10^8; y <- rnorm(N, mean = 0, sd = sqrt(true_var)); (-0.5 * log(1 / mean(exp(2*y))))
[1] 47.79222
Comment: @Zen maybe it is overflowing?
Comment: Doesn't look like it's overflowing.
Answer: The estimator is strongly consistent, since
$$
  \hat{\theta}_n = \frac{1}{2} \, \ln \left( \frac{1}{n} \sum_{i=1}^n e^{2Y_i} \right) \to \frac{1}{2} \, \ln \left( \mathbb{E}[e^{2Y}]\right) = \sigma^2,
$$
almost surely.
Continuing the discussion started in the comments about the distribution of the estimator.
sim <- function(true_var, n, N) {
    y <- matrix(rnorm(N * n, mean = 0, sd = sqrt(true_var)), ncol = n)
    M <- apply(y, 1, max)
    dy <- sweep(y, 1, M, "-")
    est <- M + apply(dy, 1, function(row) 0.5 * log(mean(exp(2 * row))))
    hist(est, freq = TRUE, breaks = "FD", col = "cyan")
    abline(v = true_var, col = "red", lwd = 2)
}

set.seed(1234)

sim(true_var = 2, n = 10^4, N = 10^3)

sim(true_var = 10, n = 10^4, N = 10^3)

Note: in the function, I subtracted the maximum to prevent overflows:
$$
  \hat{\theta}_n = M + \frac{1}{2} \, \ln \left( \frac{1}{n} \sum_{i=1}^n e^{2(Y_i-M)}\right),
$$
in which $M = \max_{1\leq i\leq n} Y_i$.
Comment: It's possible for an estimator to be strongly consistent, but still be rubbish. See this for example: https://radfordneal.wordpress.com/2008/08/17/the-harmonic-mean-of-the-likelihood-worst-monte-carlo-method-ever/
Comment: Billions isn't going to cut it for true_var = 10; the variance is on the order of $\exp\{20\}$, which is roughly $10^{8.7}$.  You would need your actual sample size, not just the # of samples drawn, to be on the order of a billion to get the s.e. of the mean down below 1.
Comment: The strong law says that the estimator is consistent, but the sampling distribution of the estimator gets weird when we increase the value of the true variance.
Comment: I don't know much theory but isn't $E[ln f(x)] \neq ln E[f(x)]$, how does that continuity thing work?
Comment: if $X_n$ converges a.s. to $X$, and $g$ is a continuous function, then $g(X_n)$ converges a.s. to $g(X)$.
Comment: There is a long discussion in the comments here: https://stats.stackexchange.com/a/31038/20980. Is this one of those cases where a.s. convergence doesn't imply we are actually converging in the mean?
Comment: If you want to investigate this, check the simulation first. It looks like the bias isn't going to zero, and the variance is increasing. It may be an interesting pathological example. Then, you may try to find approximate expressions for the bias and the variance of the estimator using Taylor expansions. It may reveal something. Why did you consider this particular loss function?
Comment: Even with `true_var = 2`, the variance of a single $\exp(2*Y)$ is going to be very large relative to the mean:  about 8.9 million, if my calculations are correct.   This may hinder your ability to learn about the asymptotics through simulation.
Comment: Basically, you are taking the log of the sample mean from a lognormal distribution, and I can't see any reason why eventually the asymptotics won't take over and give you a nicely-behaved close-to-Normal distribution with bias going to zero.  The question is when "eventually" kicks in.
Comment: @jbowman I used billions of samples for true_var = 10. Didn't cut it. It seems infinity is not just a big number, and non-linear biases are very dangerous.


How is the mordent played in the given piece from Petzold

Question: Here is an excerpt of Petzold's Menuett in G major and I stumbled upon a mordent which I don't know how to play. The fun fact is: The excerpt is from a beginner book where there is an explanation of how to play the mordent :)

Regarding the right hand the mordent is placed on b, so I play the c and then the mordent. The mordent is explaint at the bottom of the book but beside the fact that it is awkward to play (first note of given bar is a c and the first "mordent" is also a c) it also looks wrong.
When I look the mordent up on wiki http://en.wikipedia.org/wiki/Mordent I see the upper mordent here. Both the upper and lower mordent are however played with the original note first. In my case it would be h-c-h, which flows much better.
Now the gotcha is that the menuett was written somewhere in the lifetime of Petzold :), between 1677-1733 which was in the Baroque period.
The same article above says that in this time a mordent was a lower mordent instead of an upper mordent.
So I would play the h as h-a-h.
I'm fine with both however as I am a novice I cannot explain why the editor of the book "helped" me by showing something that rather looks like a trill and in my opinion is a tone higher as expected.
There is a german chart of Bach's ornaments (http://de.wikipedia.org/w/index.php?title=Datei:Manieren.png&filetimestamp=20090112055252&) which confused me even more as I am unsure what the heck is what :)
Answer: As you say, a Baroque mordent is played H-A-H as you have it (for non-Germans among us, that is B-A-B) during the Baroque period.  However, that isn't a mordent in your music, it's a short trill.  A mordent has a vertical line through the mark, as both of your links show, and also as both of your links show, the trill begins a step up from the main note.  It can be played as written in the note c) in your music.
Now, you will notice that the trill in your first link begins on the main note.  This is typical of music from Beethoven's time onward, with some discussion about what was customary after 1750 or so.  (Mordents began using the main-upper auxiliary-main format after 1700 or so, called sometimes "inverted mordents" for this reason.)  In the Baroque period, the trill generally began on the auxiliary note, except when the previous note was the same as the auxiliary (which is the case in your music).  Then you would sometimes see performers begin the trill on the main note, because as you say it flows better by avoiding a repeated note.  You can leave out the first C in the trill if you like.  Personally, I like to leave it in when I want to add a bit of an edge to the trill.
Comment: Yes, I can see why that's confusing. In Baroque usage, the squiggly line is played as written in your Petzold example, and the one with the line through it is played as in your Wikipedia article. The Wikipedia article is addressing 19th-century usage, which was different. See [this](http://www.musicofyesterday.com/history/execute-mordents-trills-appoggiaturas/) for a 19th-century essay on the subject, which should prove enlightening.
Comment: You're right. Play c-h-c-h if you want more tension (it's a bit like a suspended chord) and h-c-h or just h if you want a better flow. However I think the trill in the pic doesn't sound as good and is a bit too fast especially for a beginner.
Comment: Sorry for the h, I mixed it up in the second run :). How ever when I check the mordent wiki link, it states that "The upper mordent is indicated by a short squiggle;
the lower mordent is the same with a short vertical line through it". This is the source of my confusion as for me this looks like the upper mordent and not a short trill
Comment: I myself played this as a quaver triplet h-c-h because if flows better. However, you might want to try a more baroque way could be playing semiquavers c-h-c-h. Actually I think that would be the correct way, the trill in your note example looks impractically fast and a bit awkward rhythmically. Of course it depends on your tempo - I liked to play this pretty fast.
Comment: @traitor: if the previous note to the one with the trill is a step above, it was perfectly common Baroque practice to begin on the main note. This is such a situation, so neither way is "more Baroque" to a 1720 ear.  As far as we all know, of course.  On the other hand, it may well sound "more Baroque" to a 2014 ear to start on the upper note.
Comment: My take interpretatively is that you get a more legato sound by starting on the main note.  If you want the notes to sound a bit more detached, then leaving the extra note in will help make that happen. This will have a more lively feeling, while the more legato will be more languid and lyrical.  One of the interesting things about playing Baroque keyboard music on the piano is that there is a much wider range of tonal effects available than on the harpsichord, and the performer has to make (or is free to make) decisions about how to use them.


How to parallelize my file-processing program using PySpark

Question: I have a large python project right now, in which the driver program has a function that uses a for loop to traverse each file on my GCP (google cloud platform) bucket. I'm using CLI to submit the job to GCP and let the job run there on GCP.
For each file being traversed in this for loop, I'm invoking a function parse_file(...) that parses the file and invokes serials of other functions that deal with this file.
The whole project runs and takes a few minutes, which is slow, and the driver program hasn't used much PySpark yet. The issue is each parse_file(...) in that file-level for loop is executed in sequential order. Is it possible to use PySpark to parallelize that file-level for loop to run the parse_file(...) function in parallel for all these files to reduce program execution time and improve efficiency? If so, since the program isn't using PySpark, is there a lot of code modification needed to be done to make it parallelized?
So the function of the program looks like this
# ... some other codes
attributes_table = ....
for obj in gcp_bucket.objects(path):
    if obj.key.endswith('sys_data.txt'):
        #....some other codes
        file_data = (d for d in obj.download().decode('utf-8').split('\n'))
        parse_file(file_data, attributes_table)
        #....some other codes ....

How do I use PySpark to parallelize this part instead of using for loop traverse file one at a time?
Answer: Thank you for asking your question.
I would recommend creating a RDD based on your gcp_bucket.objects(path).
You have your SparkContext so creating the RDD should be as simple as:
my_rdd = sc.parallelize(gcp_bucket.objects(path).
To the uninitiated the convention is to assign the SparkContext is assigned to the variable sc. The contents of your for loop will have to be put into a function, let's call it my_function.  You now have all your pieces.
Your next step will be mapping your function as such:
results_dag = my_rdd.map(my_function)
results = results_dag.collect()

Recall that Spark performs lazy evaluation.  This is why we need to perform the collect operation at the end.
A few other recommendations.  The first is run your code on a small set of objects from your GCP bucket.  Get a sense of the timings.  The other recommendation, to facilitate good coding practices, is to consider breaking the operations inside your for loop down even further into additional RDDs.  You can always chain them together...
my_rdd = sc.parallelize(gcp_bucket.objects(path)
dag1 = my_rdd.map(function1)
dag2 = dag1.map(function2)
dag3 = dag2.map(function3)
results = dag3.collect()

Comment: Thanks so much for the advice and your recommendations.

I've been trying with your approach, I did use collect() but the program yelled with some errors, especially with the one at the line where I have collect():
`PicklingError: Could not serialize object: TypeError: can't pickle _thead.lock objects`
I'm not sure how this error is generated.
If I remove collect(), the program ran, but when I did dag1 = my_rdd.map(function1), function1 wasn't executed, is this because transformation is lazy and it just tells Spark this will be actually taken place once an action collect() is performed?
Comment: Also, does it matter whether "myfunction" returns anything to the driver program? What my "myfunction" in your example does is to do a series of stuffs on the passed in file data, so I don't see these series of stuffs necessarily return anything back to the Driver node on Spark. Does this invalidate the point of using collect()?
Comment: Thanks so much @VanBantam. I boiler down my problem to small pieces. I ran into a major issue now. I tried:
`dag1 = my_rdd.map(lambda file: function1(file))`
```
def function1(file):
      my_publisher = MyPublisher(attrs)
      result = function2(my_publisher)
```
Here `my_publisher` calls the MyPublisher constructor, but the program reports error `Could not serialize object: TypeError: can't pickle _thread.lock objects`. The issue comes from that `my_publisher` isn't serializable to be pickled. But my program has to use `my_publisher`. Is there anyway to fix this?
Comment: Thanks so much! I will try this now.
Comment: Troubleshooting thread locks is complicated. I would recommend breaking your problem down and isolating the portion of the code you want to parallelize.  I would test your parallelization code on a small subset of paths to ensure your code is functioning properly.  What you're specifically trying to do I've done before without having any issues.  You will have to call collect otherwise the DAG will not be evaluated.  I recommend looking at a few spark tutorials.
Comment: I would search SO for this specific issue.  You should not be encountering thread lock issues.  I would say you still haven't sufficiently simplified your problem.  Consider this approach.  Make a small list of directories you wish to process.  Write your function to work on the items in the list. Run that in python. Then build your rdd from your list. Map your function and run collect.  Once this works then try putting that code inside your loop.


converting INT to DATE / TIME

Question: I have a table that holds date and time values as INT data type. eg a date is stored as YYYYMMDD, like 20110901 and a time is stored as HHMMSS, like 21826.
The date is close to ISO standard so its not too big an issue however can anyone suggest a simple way to convert to a TIME type please? I have come up with a hideous combination of concatenation, reversing, substring, convert that I am worried will be difficult to read by other staff.
Comment: Your solution is the correct solution.
Answer: What you want to do is take your "hideous combination" and adapt it to convert these integer pairs to datetime values. Then test the heck out of it with as many edge cases as you can come up with, perhaps even verify it by hand against a random subset of your actual data.  If you're very lucky, you'll be able to use existing code that displays your data as a string and write a script that compares your conversion code output with actual output to make sure every instance lines up and guarantee perfection.
When the code is ready, use it exactly one time to copy the data to a new datetime column that you will add to the table for this purpose. After that is done, remove the old column and rename the new one to match the old name.  Now update any code that inserts/updates/reads from the original column to use a datetime data type. Then never speak of this again.
To make all this happen smoothly you'll need to coordinate running your table adjustment scripts with deploying new application code. If this is a 24/7 app that can be tricky, but the result should be worth it.
Answer: This is about the best I can come up with.
<code>select
-- convert string to time value
CONVERT(time
    -- insert a colon between hours and minutes (position 3)
    , STUFF(
        -- insert a colon between minutes and seconds (position 5)
        STUFF(
            -- convert to string, pad left with zeroes to 6 characters
            RIGHT('000000' + CONVERT(varchar(6), @time_value_int), 6)
        , 5, 0, ':')
    , 3, 0, ':')
) as time_converted
</code>
I initially started down the math route by taking the integer time value and using integer division and modulus to get the hours, minutes and seconds parts, and multiplying by the float equivalent of that time part (hours = 1 / 24.0, minutes = ( 1 / 24.0 / 60.0 ), seconds = ( 1 / 24.0 / 3600.0 ) then adding those together, only to find that you can't convert a float to the TIME data type. It does covert to DATETIME, which you can then convert to TIME, but it seems there is a loss in precision, so the result may be a few milliseconds off.
So the text-munging approach seems cleaner.

converting INT to DATE / TIME


Determining transformation sending $|z|=2$ to $|z+1|=1$.

Question: I'm trying to teach myself complex analysis, and am reading about linear fractional transformations.

I want to find the transformation carrying the circle $|z|=2$ into $|z+1|=1$, $-2$ into the origin, and the origin into $i$.

My text states that the transformation is determined by prescribing a point $z_1$ on circle $C$ to correspond to a point $w_1$ on $C'$, and a point $z_2$ not on $C$ to correspond to $w_2$ not on $C'$. Then $z^\ast_2$ corresponds to $w^\ast_2$, the symmetric points of $z_2$ and $w_2$ in $C$ and $C'$, respectively. Then the transformation is obtained from the relation $(w,w_1,w_2,w^\ast_2)=(z,z_1,z_2,z^\ast_2)$ (those are cross-ratios).
I let $C$ be the circle $|z|=1$, and $C'$ be $|z+1|=1$. Then by the notions above $z_1=-2$, $w_1=0$, $z_2=0$, $w_2=i$. I calculate $z^\ast_2=\infty$ and $w^\ast_2=\frac{-1+i}{2}$.
So following what I've read, I have $(w,0,i,(-1+i)/2)=(z,-2,0,\infty)$. I don't understand how to gather the explicit form of the desired linear fractional transformation is from this, since $w$ and $z$ seem unknown to me. Could someone please explain what the transformation is now? Thank you.
Answer: Linear fractional transformations preserve cross-ratios, so if $w$ is an LFT we have
$$(a,b,c,d)=(w(a),w(b),w(c),w(d)) \text{ for all }a,b,c,d\in\hat{\mathbb{C}}.$$
The utility of this is that if you know $w(b),w(c),w(d)$ for three known arguments $b,c,d$ as you do, then we can let $a$ be the independent variable $z$ and $w$ the dependent variable $w=w(z)$; solving for the variable $w$ in terms of $z$ will give us the desired transformation in the appropriate form,
$$w=\frac{\square\, z+\square}{\square\, z+\square}.$$
In particular, $(z,-2;0,\infty)=(w,0;i,\frac{-1+i}{2})$ says
$$\frac{(z-0)(-2-\infty)}{(-2-0)(z-\infty)} = \frac{(w-i)\left(0-\frac{-1+i}{2}\right)}{(0-i)\left(w-\frac{-1+i}{2}\right)}$$
$$-\frac{z}{2}=\frac{1+i}{2}\frac{w-i}{w-\frac{-1+i}{2}}.$$
Multiply by the righthand denominator, collect terms and solve for $w$ in a linear equation.
Comment: That's the crucial idea I was missing. Thank again anon. I find $$w=\frac{\frac{-1+i}{2}z+i-1}{z+1+i}.$$
Comment: Why $\infty$ is mapped to $\dfrac{-1+i}{2}$? I am confusing about this question. Since $-2$ and $0$ are mapped to $0$ and $i$, so the real axis is mapped to imaginary axis. And the circle $|z|=2$ cuts the  real axis at angle $\pi/2$ but the circle $|z+1|=1$ cuts the imaginary axis at $\pi$. I am expected that linear fractional transformation is comformal and preserves the angles.
Comment: @mnmn1993 Look at Dedede's comment above yours and plug in $z=\infty$. (Note that $\frac{az+b}{cz+d}$ at $z=\infty$ is just $a/c$.)


Can't remove item from ObservableCollection through ContextMenu

Question: I have a program with a class called MyClass and Location. MyClass contains an ObservableCollection of Location items and Location contains a string property called Name. In MainPage.xaml I have a LongListSelector (with a ContextMenu for each item) populated with grids representing a Location.
When I click the 'remove' menu item from the context control, it will usually remove the underlying Location object and update the view. After a few cycles of populating the LongListSelector and removing all its items, some new items that are added can't be removed anymore.
Here's an example of what I mean: The LLS originally contains 2 items. Then I delete those 2 items and add 3 more. However, I can only remove the third one, in this case, but not the first 2.
Here's the ContextMenu MenuItem click event from MainPage.xaml.cs:
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    var selectedItem = (sender as MenuItem).DataContext as Location;

    for (int i = 0; i < MyClass.Locations.Count; i++)
    {
        if (MyClass.Locations[i].Name == selectedItem.Name)
        {
            MyClass.Locations.Remove(MyClass.Locations[i]);
            break;
        }
    }
}

Prior to using a for loop, I used this LINQ code and still had the same problem:
var toRemove = MyClass.Locations.Where(x => x.Name == selectedItem.Name).SingleOrDefault();
MyClass.Locations.Remove(toRemove);

Any suggestions to fix this problem?
Comment: @pcnThird - can you try to replace LLS with ListBox and check if you have the same problems?
Comment: I assume the DataContext is actually an Item from the Locations? In that case you should be able to remove the Items from the Collection with something like `MyClass.Locations.Remove(selectedItem)` instead of the for loop.
Comment: I have tried that, but I still had the same problem, unfortunately.
Comment: Can you elaborate the `can't be removed anymore` a bit better? Are you still able to open the context menu? Have you tried to set a breakpoint at the condition to see if the Name's aren't matching for whatever reason?
Comment: The ContextMenu still shows up. I set a breakpoint and it turns out `selectedItem` is null.
Comment: `var selectedItem = (sender as MenuItem).DataContext as Location;` will be null if either sender is not A Menu Item (but you should get a NullReferenceException in that case) or DataContext is not a Location. What is the DataContext for an Item where the selectedItem is null?
Comment: My bad, `selectedItem` is not null. It has the same name as the item that was deleted before the new item was added.
Comment: `

`
Comment: Wow, I'm actually surprised using a ListBox worked! Thanks, Romasz. Feel free to post it as an answer.
Answer: I suggest you to use a ListBox instead of LLS - if you are not using grouping option. It works much better and causes less problems.
By the way I've also encountered some problems with this Control - maybe similar to yours. Weird is also that LLS.UpdateLayout() doesn't work while in ListBox works perfect.


How to get Virtual Server Temperature via PowerShell?

Question: I can get the Physical Server temperature by using the
<code>Win32_PerfFormattedData_Counters_ThermalZoneInformation (temperature)
</code>
command in PowerShell.
However, the same command is not possible in the virtual machine.
Can I know how to get server temperature in a virtual machine?
Comment: It's not possible, because `VM's have no temperature or other stuff related to that class` ; as ***there are no physical components of VMs (aka CPU, HD, MB, etc.) to generate any)***. Thus you can only do this on the VMHost/local machine. All VM's on that VMHost would report the same as the VMHost itself, so no real point in doing that. What/who lead you to believe that VM's had all the attributes of a physical box? Just curious. Note: Vendor hardware sensors and Windows can/will report different things. Just saying.
Comment: Look at [this](https://stackoverflow.com/a/41792575/934946). It might be worth a try.
Answer: A virtual server (VM) as the name suggests is virtual and has no physical presence. So it cannot have a temperature.
You can only get the temperature of the physical host on which the VM resides.
You will need to query the temp of the physical host.


How do I get the content type name using code?

Question: I'm working on Drupal 8 and I want to get content type machine name and label. Here is my code:
$cont_type = node_type_get_types();
foreach ($cont_type as $key => $value) {
  $label = $value->name;
  $machine_name = $key;
}

I get the following error message:

Cannot access protected property Drupal\node\Entity\NodeType::$name

Hoe can I get the content type name?
Answer: To get a property, there is ConfigEntityBase::get(). Since ConfigEntityBase is a base class for NodeType, you can always use $value->get('name') to get the value of the name property.
Answer: name is the label of the node type entity, so you can get that with $node_type->label(). That works for any entity type, if what you want is specified as the label key in the entity type annotation.
Answer: To get names of content type you can use below function
node_type_get_names();

Answer: $cont_type = node_type_get_types();
foreach ($cont_type as $key => $value) {
  $label = $value->get('name');
  $machine_name = $key;
}


SESSION_COOKIE_SECURE does not encrypt session

Question: I'm trying to put some security on my Flask web app. As a first step I'm going to make my session cookie secure by setting SESSION_COOKIE_SECURE to true.
But after I get my session cookie from "inspect element" I can decode session cookie easily and there is no difference whether I add SESSION_COOKIE_SECURE or not.
Here is my code:
from flask import Flask, request, app, render_template, session, send_file, redirect

MyApp = Flask(__name__)
MyApp.secret_key = "something"
application = MyApp
if __name__ == "__main__":
    MyApp.debug = False
    MyApp.config.update(
        SESSION_COOKIE_SECURE=True,
        SESSION_COOKIE_HTTPONLY=True,
        SESSION_COOKIE_SAMESITE='Lax',
    )
    MyApp.config["SESSION_PERMANENT"] = True
    MyApp.run()

I also tried to add this attribute using the following syntax but this made no difference:
    MyApp.config['SESSION_COOKIE_SECURE'] = True

When I try to print SESSION_COOKIE_SECURE I get this error
Traceback (most recent call last):
  File "...", line ..., in <module>
    print(MyApp.session_cookie_secure)
 AttributeError: 'Flask' object has no attribute 'session_cookie_secure'

My Flask version is 1.0.2, and I'm on HTTPS.
Answer: Setting SESSION_COOKIE_SECURE does not encrypt the cookie value, no. When set, this causes Flask to create cookies with the "Secure" flag set.  This means that a browser can only return the cookie to the server over an encrypted connection, nothing more. The setting doesn't change anything about the cookie value itself.
Flask produces cookies that are cryptographically signed, by default. That means that the cookie contents can be decoded but not altered, because a third party without access to the server secret can't create a valid signature for the cookie.
You generally don't need to encrypt your session cookie if you a) use HTTPS (which encrypts the data from outsiders) and b) protect your web app from XSS attacks. Without an XSS attack vector, attackers can't get access to your cookie contents at all anyway.
You certainly don't need to do so here, as SESSION_COOKIE_HTTPONLY means that the browser will never expose the cookie to JavaScript, and only someone with full access to the browser can see the cookie value.
Flask doesn't have a 'encrypt cookie' setting, because it is not deemed necessary when you can secure the cookie in other ways. You should not store information in a session cookie so sensitive that it should be protected from the end-user with access to the browser storage; keep such data on the server and only store a unique identifier in the session to retrieve that secret data later on.
If for some reason you can't keep such secrets out of the session cookie and are unwilling to accept that the end-user can read this data, then you'll have to encrypt the cookie yourself or use an alternative session provider for Flask, such as EncryptedSession.

As for the attribute error: only a few configuration settings are accessible as attributes on the Flask object. To print arbitrary configuration settings, use the app.config object:
print(MyApp.config['SESSION_COOKIE_SECURE'])

Comment: and how can i encrypt my session ?
Comment: @K327: why do you think you need to?
Comment: preventing user to see cookie content
Comment: @K327: sure, but why is there data in the cookie the user must not see?
Comment: i have put user role in session but as you said user cant change it . i get my answer thanks man


Google web font imports breaking with advagg

Question: I'm trying to pass Google Page Insights, and they keep saying we have render blocking CSS.  When I try and inline the CSS, it breaks my fonts I'm importing from Google Fonts.  I've tried a million combinations, but the inline is the culprit for some reason.
Here is the CSS code from one of the aggregated files:
<code>@import url("http://fonts.googleapis.com/css?family=Pontano+Sans");@import url("http://fonts.googleapis.com/css?family=Roboto");
</code>
I tried it with and without quotes.
For the time being, to keep my client happy, I moved the $styles variable below in my html.tpl.php template, right before the close of the body.  It works fine, but there is a nasty flicker on the page load before the CSS loads, so inlining makes the most sense to me.
I use Omega 4 and use @import in my SASS.
Answer: You'll want to follow this issue https://www.drupal.org/node/2396609 Inline critical css
I'm guessing you're using the "Inline CSS on specific pages" setting on the AdvAgg: Modifications page. If the imports and not working correctly when everything is inlined, please open up a bug report explaining this with a good way for me to reproduce the issue locally.
Also noted that you can use the Adjust CSS location and execution setting to load the css async without having to mess with the tpl file.


How to display one row of six columns on desktop and two rows of three columns on mobile?

Question: I have a section that contains 6 images. I want to display them in a single row of 6 columns on desktop and then in 2 rows of 3 columns on mobile.
I am able to achieve the desired layout on desktop. But on mobile, the images appear stacked on top of each other in a single column. I want them to appear in 2 rows with 3 columns each.
Here's the markup:

Comment: If you have made any CSS yet, then kindly share it with us or just check the answer for a new CSS of the demanded output
Comment: Try reading the documentation https://getbootstrap.com/docs/4.0/layout/grid/
Answer: Remove the "-sm" from the classname as this targets screens of ≥576px. Bootstrap 4 is mobile first so you just need to use "col-4" for the smallest screen sizes <576px as is explained in the documentation here https://getbootstrap.com/docs/4.0/layout/grid/

Answer: If the following is your html then try adding the given CSS for desired outputs -
CSS & HTML-

.row {
  width: 100%;
}

.row img {
  height: 100px;
  width: auto;
}

.col-sm-4 {
  height: 100px;
}

.col-sm-4:nth-child(1) {
  background: #999;
}

.col-sm-4:nth-child(2) {
  background: #888;
}

.col-sm-4:nth-child(3) {
  background: #777;
}

.col-sm-4:nth-child(4) {
  background: #555;
}

.col-sm-4:nth-child(5) {
  background: #333;
}

.col-sm-4:nth-child(6) {
  background: #111;
}

@media only screen and (max-width: 767px) {
  .col-sm-4 {
    float: left;
    width: 33.3%;
  }
}

@media only screen and (min-width: 768px) {
  .col-lg-2 {
    float: left;
    width: 16.6%;
  }
}

Kindly resize the browser window to see the results.
Comment: This is the wrong solution. The answer is to follow the bootstrap docs and not create unneeded custom code or overwrite bootstrap core code https://getbootstrap.com/docs/4.0/layout/grid/
Comment: You should not be overriding Bootstrap's grid CSS... he just needs to use the `col-4` class instead of `col-sm-4`
Comment: Kindly let me know if you need any sort of help and please accept my answer if you think that I was able to solve your problem.
Comment: he haven't mentioned anywhere in his question that he is using bootstrap, he just wants to know, that how can he achieve that, and because of it, I gave him a demonstration of CSS for that ! All what I mean was concept of doing it, but if he already have a bootstrap solution, then of course, the other answer is helpful.
Comment: @Om_16 the question is tagged Bootstrap


operand type does not match error

Question: I have to learn Assembly for my university and i need to do this:
(a+b+c+1) *(a+b+c+1) /((a-b+d)*(a-b+d)).

When i try to create the exe file using the "tasm" command i get this messages:
**Error** lab1.ASM(14) Operand types do not match
**Error** lab1.ASM(15) Operand types do not match
**Warning* lab1.ASM(30) Open segment:Data

Here is my code:
assume cs:code,ds:data
data segment
a db 1
b db 2
c db 3
d db 4
code segment
start:
mov ax,data
mov ds,ax
mov al,a
mov ah,0
add ax,b ;ax=a+b
add ax,c ;ax=a+b+c
add ax,1 ;ax=a+b+c+1
mov bx,ax ;bx=ax
mul bx ;dx:ax=(a+b+c+1) *(a+b+c+1)
mov al,a
mov ah,0
sub al,b ; al=a-b
add al,d ; al=a-b+d
mov bl,al ; bl=al
mul bl ; ax=(a-b+d)*(a-b+d)
mov bx,ax
div bx ; dx:ax :bx =(a+b+c+1) *(a+b+c+1) /((a-b+d)*(a-b+d))
mov ax,4c00h
int 21h
code ends
end start

Comment: It is not at all clear "what you need to do", nor is it clear which lines your error messages refer to.
Answer: AX is word-size; A and B are byte-size.
observe that you don't have the same problem later on in the code where you subtract B from AL for instance (both byte-size)

operand type does not match error


how to use regular expression to match the string included two backslash

Question: I have to write a regular expression refer to a string.I need to get the part between "$u" and the final "$",also I need match the part before "$u"
Now I wrote the regular expression as follow, but it can not work
a='=856  \\$uhttp://sfx-852cuh.hosted$'
#Two backslash may replace by other characters:a='=856  aa$uhttp://sfx-852cuh.hosted$'
result=re.search('=\w{3}\s{2}\S{2}\$u(.*)\$', a)
target_str=result.group(1)

Comment: Replace `\S{2}` with `\S` and retry. ``\\`` is actually 1 symbol. Also, why not use [`r'\$u([^$]+)'`](https://ideone.com/yNmbzK)?
Comment: Don't assignn to `str`. That's a built-in.
Answer: Replace \S{2} with \S{1,2} if you expect 1 or 2 non-whitespace chars before $u and do not use a variable with str name:
import re
a='=856  \\$uhttp://sfx-852cuh.hosted$'
result=re.search(r'=\w{3}\s{2}\S{1,2}\$u(.*)\$', a)
expected_value = ''
if result:
    expected_value = result.group(1)
print(expected_value)

See the Python demo
Comment: This is great! Thanks!
Comment: So, you can have 1 or 2 non-whitespace chars before `$u`, right? You need to indicate that in your question.


Finding a stochastic process from Ito's lemme on $Y_t$ such that $\int_0^1Y_s\,\mathrm{d}B_s= B_1-2B_1\mathbb{I}_{|B_1|}$

Question: Problem:
I would like to zoom in on a particular part of a question as a follow-up on a question I have previously asked, which I feel deserves its own space. I was looking at the random variable
$$X=B_1-2B_1\mathbb{I}_{|B_1|}=\begin{cases}B_1&\text{if }|B_1|\geq1\\-B_1&\text{otherwise}\end{cases}$$
for $t\in[0,1]$, where $\{B_t\}$ is a standard BM. I also have
$$X_t=\mathbb{E}(X|\mathcal{F}_t)=\mathbb{E}(B_1-2B_1\mathbb{I}_{|B_1|<1}|\mathcal{F}_t)$$
where the filtration $\mathcal{F}_t$ satisfies the usual conditions. I need to find an adapted process $\{Y_t\}_{t\in[0,1]}$ s.t. $X=\int_0^1Y_s\,\mathrm{d}B_s$. I was thinking that $Y_t=1-2\mathbb{I}_{|B_1|<1}$ was a good choice, but apparently it is wrong, why is this so?
Furthermore, is it true that $X_t=\int_0^tY_s\,\mathrm{d}B_s$ in general? How does this lead to the result that $\int_0^tX_sY_s\,\mathrm{d}B_s$ is a martingale?
Lastly, in my original question, I was trying to figure out the distribution of $X$, and I mistakenly thought was a Brownian motion. How do we determine the distribution from the form of $X$ without looking at $Y_t$?
My attempt:
Using the Markov property and independent increments, I have established $X_t=B_t-2f(B_t,\sqrt{1-t})$ where $f(x,s)=\mathbb{E}\left[(x+sZ)\mathbb{I}_{|x+sZ|<1}\right]$ and $Z\sim\mathcal{N}(0,1)$. Letting $s=\sqrt{1-t}$, I have from Ito's formula
$$\mathrm{d}X_t=\left(1-2\frac{\partial f}{\partial B_t}\right)\mathrm{d}B_t-\left(\frac{\partial^2f}{\partial B_t^2}-\frac1s\frac{\partial f}{\partial s}\right)\mathrm{d}t.$$
Since $X_t$ is a martingale, it is also a local martingale and the drift term is zero, so the PDE satisfied by $f(x,s)$ on the interval $s\in(0,1]$ is
$$\frac{\partial^2f}{\partial x^2}=\frac1s\frac{\partial f}{\partial s}.$$
Additionally, $X_0=\mathbb{E}(X_t|\mathcal{F}_0)=\mathbb{E}(X_t)=0$ a.s., so we have initial condition $f(0,1)=0$. To my knowledge, there is no closed form solution to this PDE (I think). Then, $Y_t=1-2\frac{\partial f}{\partial B_t}$ which I got from the diffusion part of Ito's formula. If I have missed out on a possible closed form solution for $f$ or $\partial f/\partial B_t$ do let me know.
Comment: Maybe this $Y_t$ is not a good choice because it's not adapted to the admissible filtration, because it depends on $B_1$.  Notice that $\int_0^1 1-2 \mathbb I_{|B_1|<1} dB_s$ cannot be computed in the Itô sense, since the integrand is not adapted, still this can be (potentially) be computed in the Skorokhod sense, yielding $B_1- 2  B_1\mathbb I_{|B_1|<1}+\langle D \mathbb I_{|B_1|<1},2\rangle$ where the last term is the Malliavin directional derivative. Unfortunately the indicator function is not a smooth Brownian functional and I don't know if the Malliavin derivative can be computed.
Comment: @Chaos I haven't learnt that stuff before, will give it a read!
Answer: Let $f(b) := b 1_{|b|< 1}$ and compute by the Markov property of Brownian motion and independent increments that $$E[f(B_1)|\mathscr{F}_t] = E[f(B_1)|B_t] = E[f((B_1-B_t) + B_t)|B_t] = E[f(Z\sqrt{1-t} + b)]|_{b=B_t},$$ where $Z \sim N(0,1)$.
Thus we need to compute for a fixed $b$ the value of the integral
$$
E[f(Z\sqrt{1-t} + b)]
= E[(Z\sqrt{1-t} + b) 1_{-1 <Z\sqrt{1-t} + b < 1}]
= E[(Z\sqrt{1-t} + b) 1_{\frac{-1-b}{\sqrt{1-t}} <Z< \frac{1-b}{\sqrt{1-t}}}]
$$
$$
=\sqrt{1-t} E[Z1_{\frac{-1-b}{\sqrt{1-t}} <Z< \frac{1-b}{\sqrt{1-t}}}] +bP(\frac{-1-b}{\sqrt{1-t}} <Z< \frac{1-b}{\sqrt{1-t}})
$$
$$
=\left(\sqrt{1-t} E\left[Z\mid{\frac{-1-b}{\sqrt{1-t}} <Z< \frac{1-b}{\sqrt{1-t}}}\right] +b\right)P(\frac{-1-b}{\sqrt{1-t}} <Z< \frac{1-b}{\sqrt{1-t}})
$$
and using the formula for the mean of a truncated normal https://en.wikipedia.org/wiki/Truncated_normal_distribution this is (using $c:= \frac{-1-b}{\sqrt{1-t}} $ and $d:=\frac{1-b}{\sqrt{1-t}}$ and $\phi, \Phi$ normal density and CDF)
$$
=\left(\sqrt{1-t}\frac{\phi(c)-\phi(d)}{\Phi(d)-\Phi(c)} +b\right)(\Phi(d)-\Phi(c))
$$
$$
= \sqrt{1-t}(\phi(c)-\phi(d)) + b(\Phi(d)-\Phi(c)).
$$
Thus $$
E[B_1-2B_1 1_{|B_1|<1}|\mathscr{F}_t] $$
$$
= B_t - 2\sqrt{1-t}\left(\phi\left( \frac{-1-B_t}{\sqrt{1-t}}\right)-\phi\left(\frac{1-B_t}{\sqrt{1-t}}\right)\right) - 2B_t\left(\Phi\left(\frac{1-B_t}{\sqrt{1-t}}\right)-\Phi\left( \frac{-1-B_t}{\sqrt{1-t}}\right)\right) = M(B_t).
$$
Thus one should have
$
E[\int_0^1 Y_s dB_s|\mathscr{F}_t] =\int_0^t Y_s dB_s
$
equal to the previous line. Thus $Y_t = d M(B_t)$ can just be computed using Ito's formula on that monstrous formula, which involves only smooth functions of $B_t$. I'm confident a dedicated person could carry out the Ito formula calculation without further instruction, hopefully leading to some great cancellation of terms using that $\Phi' = \phi$, though I cannot force myself to type it up for you.
As for your question about $\int_0^t X_s Y_s dB_s$, this is a martingale because any integral with respect to Brownian motion is a local martingale, and you can check that $E\int_0^t (X_s Y_s)^2 ds < \infty$ so it is indeed a martingale.
One has that $X$ is normally distributed, this construction is used to give a standard example of normals that are uncorrelated but not independent. Check https://en.wikipedia.org/wiki/Normally_distributed_and_uncorrelated_does_not_imply_independent. I'm not sure about $X_t$.
Comment: Thank you, wow that looks nasty! I'll give this a try before accepting!
Comment: I also wrote something independently in my newest update which follows a similar train of thought but generates a PDE for $f$, but unlike yours I couldn't get it to be in terms of the normal CDF, was wondering if it's true? I don't think my PDE has a closed form.

Finding a stochastic process from Ito’s lemme on $Y_t$ such that $\int_0^1Y_s\,\mathrm{d}B_s= B_1-2B_1\mathbb{I}_{|B_1|}$


Conflict between Omega and Views 3 exposed sort (Ajaxified)

Question: I have made a subtheme out of the Omega 4 with the responsive structure.
I tried to use exposed sort for views inside the layouts of the subtheme.
The exposed sorts are not working under the activation of AJAX inside the views, but the exposed filters are working.
Any recommendations?!
Comment: I need to use them with AJAX! but the exposed sorts are not really working!
Answer: I found the solution, it seems to be a database problem for Drupal, and nothing to do with Theme or Views!

Just remove that specific view from the layout inside your Panel/Page
  design in Pages section, and add it another time.

It will update the Drupal database and everything starts to work!
Answer:
This Issue may come from Omega's responsive grid Try Deactivating it.
Check this Link which replicates your question
Comment: Thank you for your reply. I have actually read it previously and the only issue is that I have to keep the responsive design as its a requirement for the current project I'm doing. I was only looking for other ideas inside here, as I explored the ideas in drupal.org
Comment: I found the solution and have updated both my post and Drupal.org post.
Comment: That's cool !!!
Answer: Replace your Views theme file with the original, that you get from Views.
For me; copying views-view.tpl, to my custom theme (e.g. views-view--locations--contact-us.tpl) helped to solve the issue.


How to call different database for different user as per some group stored in file in NodeJS?

Question: app.use(function(req, res, next) {
var database = require('./bootstrap/database');
req.dbPool = database.pool;
req.dbquery = database.query;
req.cacheData = require('./bootstrap/cache')(req.dbPool);
req.nosql = mongoose;
next();  });

I want to load different database for the different user.
How can implement this?
Suppose, User A belongs to group 1 and User B belongs to group 2.
When User A comes to site and try to log in, it requests to Database A1 and when user comes to site and try to log in, it requests to Database B2.
Answer: When your user logs in, your server will presumably set a cookie for that user.  You can then use that cookie in your app.use() middleware to identify which user is making the request and set the appropriate database for that user into the req object.  Then, when your actual route handler fires, you will have the appropriate database already available for that user in the req object.
If the group for a given user is constant, you can look that up just once when the user logs in and either set that in a separate cookie (probably encrypted so it can't be messed with) or if you are using a session manager to keep track of logged in state, you can set the appropriate database reference or group identifier into the user's session.  Then, when the middleware fires, it can find the right session object for this user and retrieve the information about which group they are in.
If the group is dynamic, then you make have to look up the group for this user on every request.
Comment: how can we change db name while node server is already started. It may require to restart node server, so that new config can be load in node server


Convert bytes to a list of dictionaries

Question: I had a list of dictionaries called xyz
[
  {
    "x": -11.370502,
    "y": -8.545141,
    "z": -0.083815
  },
  {
    "x": -11.36693,
    "y": -8.403456,
    "z": -0.081571
  },
  {
    "x": -11.353832,
    "y": -7.935539,
    "z": -0.074171
  },
  {
    "x": -11.315733,
    "y": -7.325937,
    "z": -0.06436599999999999
  },
  {
    "x": -11.266916,
    "y": -6.716335,
    "z": -0.054387000000000005
  },
  {
    "x": -11.185953,
    "y": -6.106733,
    "z": -0.043016
  },
  {
    "x": -11.094276,
    "y": -5.497132,
    "z": -0.030890999999999995
  },
  {
    "x": -10.982357,
    "y": -4.88753,
    "z": -0.018994999999999998
  }
]

I wrote this to my sqlite3-database using
sqlite3.Binary(pickle.dumps(border, protocol=-1))

Now I want to read it back it from the db.
xyz = bytes(sqlite3_xyz)

What's the next step?
Answer: You just need to reverse the steps.
test.py:
import pickle
import sqlite3

XYZ = [
    {"x": -11.370502, "y": -8.545141, "z": -0.083815},
    {"x": -11.36693, "y": -8.403456, "z": -0.081571},
    {"x": -11.353832, "y": -7.935539, "z": -0.074171},
    {"x": -11.315733, "y": -7.325937, "z": -0.06436599999999999},
    {"x": -11.266916, "y": -6.716335, "z": -0.054387000000000005},
    {"x": -11.185953, "y": -6.106733, "z": -0.043016},
    {"x": -11.094276, "y": -5.497132, "z": -0.030890999999999995},
    {"x": -10.982357, "y": -4.88753, "z": -0.018994999999999998},
]

def main():
    con = sqlite3.connect(":memory:")
    cur = con.cursor()
    cur.execute("CREATE TABLE t1 (data BLOB)")

    data = sqlite3.Binary(pickle.dumps(XYZ))

    with con:
        cur.execute("INSERT INTO t1 VALUES (?)", (data,))

    for row in cur.execute("SELECT data FROM t1"):
        data, *_ = row
        print(pickle.loads(data)[0])

    con.close()

if __name__ == "__main__":
    main()

Test:
$ python test.py
{'x': -11.370502, 'y': -8.545141, 'z': -0.083815}

The security principles for unpickling data from unknown source still applies here:

Warning
The pickle module is not secure. Only unpickle data you trust.

Convert bytes to a list of dictionaries