text:
Q: How to get KML Polygon and Multigeometry values in c#? I can read and get the KML data Placemark values using this code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            List<XElement> placemarks = doc.Descendants().Where(x => x.Name.LocalName == "Placemark").ToList();
            List<string> states = placemarks.Descendants().Where(x => x.Name.LocalName == "name").Select(x => x.Value).ToList();
        }
    }

}

But I don't know how to get the KML data if it has the following details:

*

*Example : Alabama state KML format like
<Polygon> <outerBoundaryIs> <LinearRing> <coordinates>-85.070067,31.980703,0.0 -85.11515,31.907425,0.0 -85.135567,31.854884,0.0 -85.0567,32.017377,0.0 -85.070067,31.980703,0.0</coordinates> </LinearRing> </outerBoundaryIs> </Polygon>

*Example : Texas state KML format like
<MultiGeometry> <Polygon> <outerBoundaryIs> <LinearRing> <coordinates>-161.333785,58.703653</coordinates> </LinearRing> </outerBoundaryIs> </Polygon> <Polygon> <outerBoundaryIs> <LinearRing> <coordinates>-131.594177,55.106316,55.23548,0.0</coordinates> </LinearRing> </outerBoundaryIs> </Polygon> </MultiGeometry>
I tried this LINQ procedure to get the Polygon values :
List<string> states = placemarks.Descendants().Where(x => x.Name.LocalName == "Polygon").Select(x => x.Value).ToList();

Output:

-85.070067,31.980703,0.0 -85.11515,31.907425,0.0 -85.135567,31.854884,0.0 -85.0567,32.017377,0.0 -85.070067,31.980703,0.0

After I tried to replace the coordinates in the format shown below and copy/paste them into fusion table location preview, the map worked exactly as expected.
<Polygon> <outerBoundaryIs> <LinearRing> <coordinates>-85.070067,31.980703,0.0 -85.11515,31.907425,0.0 -85.135567,31.854884,0.0 -85.0567,32.017377,0.0 -85.070067,31.980703,0.0</coordinates> </LinearRing> </outerBoundaryIs> </Polygon>

But when I tried to get Multigeometry value using the same way :
List<string> states = placemarks.Descendants().Where(x => x.Name.LocalName == "MultiGeometry").Select(x => x.Value).ToList();

I got this output:

-161.333785,58.703653 -131.594177,55.106316,55.23548,0.0

But I don't know how to get the details.

A:
"After I tried to replace the coordinates in the format shown below and copy/paste them into fusion table location preview, the map worked exactly as expected."
<Polygon> <outerBoundaryIs> <LinearRing> <coordinates>-85.070067,31.980703,0.0 -85.11515,31.907425,0.0 -85.135567,31.854884,0.0 -85.0567,32.017377,0.0 -85.070067,31.980703,0.0</coordinates> </LinearRing> </outerBoundaryIs> </Polygon>

If you want the XML markup of the XElement, simply call ToString() instead of getting Value property of it :
List<string> states = placemarks.Descendants()
                                .Where(x => x.Name.LocalName == "MultiGeometry")
                                .Select(x => x.ToString())
                                .ToList();

..or if you actually meant to get individual coordinates value from MultiGeometry :
List<string> states = placemarks.Descendants()
                                .Where(x => x.Name.LocalName == "MultiGeometry")
                                .Descendants()
                                .Where(x => x.Name.LocalName == "Polygon")
                                .Select(x => x.Value)
                                .ToList();


text:
Q: NHibernate laziness concern public IEnumerable<UserReadNews> GetLatestUserReadNews(IEnumerable<string> userIds)
{

    IQuery query = Session.CreateQuery("from UserReadNews as j where j.FacebookUser_id in (:userIds)");
    query.SetParameterList("userIds", userIds );
    return query.List();
}

I have this method where I want to return this data as lazily as possible, because I am determining which data to show and then stopping. I don't want the whole query to be executed against the whole table.
My concern is the List() method. is this lazy or eager?
Can I call this method from another method and yield break when I'm done with what I need?

A: IQuery.List always returns the whole result set so early termination of the consuming loop with a yield break does not help getting more lazy.
The best thing is (if that's feasible in this case) to put your decision which items you really need from the result set already in the query so you don't cause effort in fetching not required data.

A: I agree with @CSharper about only querying what you absolutely need.
If you still need to make this as lazy as possible after that optimization, use ICriteria.Future<T>() instead of ICriteria.List<T>():
public IEnumerable<UserReadNews> GetLatestUserReadNews(IEnumerable<string> userIds)
{
    IQuery query = Session.CreateQuery("from UserReadNews as j where j.FacebookUser_id in (:userIds)");
    query.SetParameterList("userIds", userIds );
    return query.Future<UserReadNews>();
}

Future will give you an actual IEnumerable with deferred querying instead of a whole list right off the bat.  It will sometimes optimize queries too when given the chance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Number of threads in relation to num.standby.replicas Asking to confirm if my reasoning is correct.
My application has 12 input partitions spread across 3 instances of applications.
Normally, I would expect number of threads to be set as 4 given that 4 partitions equals 4 tasks what indicates at most 4 threads.
However, my application maintains state in statestore with num.standby.replicas configured to 2. Given that this setting should result in processing changelog across 12 partitions, would it make sense to change threads to 12?
During restarts/rebalances I get WARN as below:
Unable to assign 1 of 2 standby tasks for task [0_0] There is not enough available capacity. You should increase the number of threads and/or application instances to maintain the requested number of standby replicas.
Is this an indication of sub-optimal configuration which may result in bad performance? (when rebalancing or context switching between tasks to catch up with changelog)


text:
Q: SharePoint Powershell Number and User columns I need to create two list fields by powershell.
One that accept only Integer (type Number with no decimal) and the other User (multiple selection).
I can create Number field and Single User field with this code:
$spFieldType = [Microsoft.SharePoint.SPFieldType]::User
$myCustomList.Fields.Add("myUsers",$spFieldType,$false)

$spFieldType = [Microsoft.SharePoint.SPFieldType]::Number
$myCustomList.Fields.Add("myNumber",$spFieldType,$false)

How can I add Integer and multiple users fields?

A: For number field accepting only Integers (no decimal), do following:
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Number
$myField = $myCustomList.Fields.Add("myInteger",$spFieldType,$false)
$myIntegerField = [Microsoft.SharePoint.SPFieldNumber]$myCustomList.Fields[$myField]
$myCustomList.Fields[$myIntegerField].DisplayFormat = SPNumberFormatTypes.NoDecimal
$myCustomList.Fields[$myIntegerField].Update()

User multi-selection
$spFieldType = [Microsoft.SharePoint.SPFieldType]::User
$myField = $myCustomList.Fields.Add("myMultiUsers",$spFieldType,$false)
$myMultiUsers = [Microsoft.SharePoint.SPFieldUser]$myCustomList.Fields[$myField]
$myCustomList.Fields[$myMultiUsers].AllowMultipleValues = true
$myCustomList.Fields[$myMultiUsers].Update()

This should work !


text:
Q: rabbitpy - Exception not raised outside context manager Publishing to a non-existing exchange with rabbitpy does not raise an exception if not using with block:
>>> conn = rabbitpy.Connection('amqp://user:passw@ms7:5672/MyHost')
>>> ch = conn.channel()
>>> msg = rabbitpy.Message(ch, body_value='hello')
>>> msg.publish(exchange='invalid')
>>>

Using Channel as a context manager does raise the error:
>>> conn = rabbitpy.Connection('amqp://myuser:mypass@ms7:5672/myhost')
>>> with conn.channel() as ch:
...     msg = rabbitpy.Message(ch, body_value='hello')
...     msg.publish(exchange='invalid')
...
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "D:\Programming\mqclient\env36x64\lib\site-packages\rabbitpy\channel.py", line 101, in __exit__
    self.close()
  File "D:\Programming\mqclient\env36x64\lib\site-packages\rabbitpy\channel.py", line 147, in close
    super(Channel, self).close()
  File "D:\Programming\mqclient\env36x64\lib\site-packages\rabbitpy\base.py", line 204, in close
    self._check_for_pending_frames()
  File "D:\Programming\mqclient\env36x64\lib\site-packages\rabbitpy\base.py", line 318, in _check_for_pending_
frames
    self._check_for_rpc_request(value)
  File "D:\Programming\mqclient\env36x64\lib\site-packages\rabbitpy\channel.py", line 271, in _check_for_rpc_r
equest
    super(Channel, self)._check_for_rpc_request(value)
  File "D:\Programming\mqclient\env36x64\lib\site-packages\rabbitpy\base.py", line 328, in _check_for_rpc_requ
est
    self._on_remote_close(value)
  File "D:\Programming\mqclient\env36x64\lib\site-packages\rabbitpy\base.py", line 380, in _on_remote_close
    raise exceptions.AMQP[value.reply_code](value)
rabbitpy.exceptions.AMQPNotFound: <pamqp.specification.Channel.Close object at 0x333e438>

*

*Python 3.6.8 x64

*rabbitpy 2.0.0

*RabbitMQ server 3.7.4


text:
Q: ArrayList to String Without the spaces in Android Studio I am trying to convert this ArrayList to a String, but don't want the spaces between the numbers. This is what I have so far:
ArrayList<String> arrayList = new ArrayList<String>();

String NumberRightString = "";
String ButtonText = "";

public void OnClick (View v) {

    Button button = (Button) v;

    String ButtonText = button.getText().toString();

    arrayList.add(ButtonText);

    StringBuilder sb = new StringBuilder();

    for (Object obj : arrayList) {
        sb.append(obj.toString());
        sb.append("\t");
    }

    String NumString = sb.toString();

    NumString.replaceAll("//s","");

    textView.setText(NumString + "/" + number);
}

This does not work and the spaces are still there. Please help me!

A: Try to replace
NumString.replaceAll("//s","");

to
NumString = NumString.replaceAll("\\s","");


text:
Q: Why is AdMob screwing with my basic music play/pause app when I haven't even tried using anything remotely linked with AdMob I really don't understand why is Android giving me shit when i'm not even using AdMob.
All I'm trying to do is, add 2 buttons saying 'play' and 'pause' for the sole purpose of trying to understand how to use the MediaPlayer class and app keeps crashing with the following message:-

* The Google Mobile Ads SDK was initialized incorrectly. AdMob publishers    *
* should follow the instructions here:                                       *
* https://googlemobileadssdk.page.link/admob-android-update-manifest         *
* to add a valid App ID inside the AndroidManifest.                          *
* Google Ad Manager publishers should follow instructions here:              *
* https://googlemobileadssdk.page.link/ad-manager-android-update-manifest.   *
******************************************************************************

I don't even have my AdMob configured.
I am sure my code is correct, but I'm unable to de-bug this, even after trying to follow what's written in the above mentioned links.
Following is my code:-
package com.arsh.android.musicplayer;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.musicfile);

        Button Play = (Button) findViewById(R.id.play);
        Play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaPlayer.start();
            }
        });

        Button Stop = (Button) findViewById(R.id.pause);
        Stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaPlayer.pause();
            }
        });
    }

}

A: remove all admob dependency if you are not using it and try again


text:
Q: Firebase On click con envio de parametros estoy trabajando hace poco con firebase y js y tengo una duda: Tengo por un lado el .html y por otro un .js el tema que en el js quiero hacer un boton para poder abrir el detalle de un objeto y que al hacer click este pase su id lo que tengo es lo siguiente:
function listarMisPrestamos(res){
var pag = "detalle.html"
var contenido="
";

contenido+="
";
contenido+="
";
contenido+="Interno	";
contenido+="Domino	";
contenido+="Acciones	";

contenido+="
";

contenido+="
";
contenido+="
";

res.forEach(el=>{
    var fila= el.data();
    contenido+="
";
    contenido+=""+fila.interno+"	";
    contenido+=""+fila.dominio+"	";
    contenido+="";

    ACA VA EL BOTON

    contenido+="<input type='button' class='btn btn-primary' value='Ver Detalle' onclick='document.location.href =((\""+pag+"\"),(\""+el.id+"\"))' data-toggle='modal' data-target='#exampleModal' />";

    contenido+="	";
    contenido+="
";

});

contenido+="
";
contenido+="
";

document.getElementById("divListUnidades").innerHTML=contenido;

}
alguna forma de poder enviar en el onclick a detalle.html y como envio su id para mostrarlo uso +el.id+ y despues como hago para recuperarlo en la otra pagina.
muchas gracias

A: Así puede añadir un evento click a cada uno de los botones con una misma función... dentro de esa función tiene el elemento completo y puede hacer con el lo que desee.

let contenido = "";
let pag = "Otrapagina.html";

const onClick = (elem) => {
  return () => alert(`hizo click en el botón con id ${elem.id} y other ${elem.other}`);
}

const elements = [
  { id: 1, other: "a" },
  { id: 2, other: "b" },
  { id: 3, other: "c" },
  { id: 4, other: "d" },
  { id: 5, other: "e" },

];

for(elem of elements) {
contenido+=`<div><input type='button' class='btn btn-primary' value='Boton con Id = ${elem.id}' data-toggle='modal' data-target='#exampleModal' id='btn${elem.id}' /></div>` ;
}

//Escribe los botones en el dom
document.write(contenido);

//Obtiene una referencia a ellos y les asinga el evento
for(elem of elements) {
   const domElem = document.querySelector("#btn"+elem.id);
   domElem.addEventListener("click", onClick(elem));
}


text:
Q: accounting lettering algorithm to find matching amounts Do you know resources or links who talks about lettering algorithms ?
I need to find positives amounts that matchs with negatives ones to do lettering. For example :
array (
  0 =>
  array (
    'debit' => NULL,
    'credit' => '440'
  ),
  1 =>
  array (
    'debit' => '880',
    'credit' => NULL
  ),
  2 =>
  array (
    'debit' => '440',
    'credit' => NULL
  ),
)

here, indexes 0 and 2 can be associated with index 1, baut i can have more complicated associations
more examples :
     DEBIT        CREDIT
1       20
2                     20
3       40

result => 1 / 2

     DEBIT        CREDIT
1       20
2       40
3                     40

result => 2 / 3

     DEBIT        CREDIT
1       20
2       20
3                     20
4       20

result => 1 / 3

     DEBIT        CREDIT
1       20
2       20
3                     20
4                     40
5       20

result => 1-2-5 / 3-4

thanks


text:
Q: How to add something to a linked list I'm just a little bit confused about an error I'm getting.  I've made a class called "SensorNode", and each SensorNode has a linked list of sensors.  One data member of SensorNode is a SensorBlock(the linked list) pointer called mySensors.  mySensors is supposed to point to the first sensor in the linked list of sensors owned by the sensor node it's in.  Here's the class declaration for SensorNode:
class SensorNode {
    char* NodeName;
    int NodeID;
    LOCATION Node1;
    float batt;
    int func;
    SensorBlock *mySensors;

public:
    SensorNode(char *n, float x, float y, float z, int i, float ah);
    void print();
    void setOK(int o);
    int getOK();
    void setLOC(float longi, float lat, float h);
    int amIThisSensorNode(char *n);
    void addSensorToNode(sensor *s);
};

and here's the class declaration for SensorBlock:
class SensorBlock {

    friend class SensorNode;
    SensorBlock * LLelement;
    sensor * SensEl;
};

my problem is with my void addSensorToNode(sensor *s) function.  Argument s points to a sensor which is supposed to be added to the end of the list of sensors that belong to that node.  And I can't figure out how to do that since it's not a new sensor that I'm creating and adding, but a pointer to a sensor that I'm adding.
Here's what I have so far:
void SensorNode::addSensorToNode(sensor *s) {
    if(mySensors == '\0') //mySensors is first initialized to NULL
    {
        mySensors = s; //I get an error on this line.
    }
    else {

    }
}

I don't know how to fix the error I get on that above line, and I don't know what to put in the "else" when mySensors is no longer equal to null.  If I solved the above error I might be able to better understand the addition process for a new sensor.  Thank you in advance for any help you can offer!!

A: mySensors = s should be mySensors.SensEl= s
Because mySensors  is of type SensorBlock while s is a sensor
void SensorNode::addSensorToNode(sensor *s) {
    if(mySensors == NULL) //mySensors is first initialized to NULL
    {
        mySensors = new SensorBlock();
        mySensors->SensEl = s; //I get an error on this line.
        mySensors->LLelement = NULL;
    }
    else {

       SensorBlock newBlock = new SensorBlock();
       newBlock->SensEl = s;
       newBlock->LLelement = NULL;
       mySensors->LLelement = newBlock;

    }
}


text:
Q: How can I get the number of pages in a PDF file inside a Google Apps Script? The PDF files are in my Google Drive. I just got that I can get the number of pages of a PDF sending it as a job to Cloud Print, because Cloud Print will return a JSON object with "numberOfPages" attribute.
Is there any faster and easier way? Thanks in advance.

A: Well, I actually did like I said.
I take my file, then send it to CloudPrint via its JSON Api. I need to send it to a dummy printer, a printer I registered in CloudPrint but actually is never connected to Internet. Then, I get the number of pages of the PDF file in the value of response's "numberOfPages" attribute. Save this number in some var. Finally, I send a delete petition to JSON Api for my file in the dummy printer, indeed isn't necessary at all.
Thanks!


text:
Q: Pass Value From GridView to another How to change DataGridView in this code with GridView Dev Express ..
        For I = 0 To DT.Rows.Count - 1
         DataGridView1.Rows.Add()
         DataGridView1.Rows(I).Cells(1).Value = DT.Rows(I).Item("Name1")
         DataGridView1.Rows(I).Cells(2).Value = DT.Rows(I).Item("Name2")
         DataGridView1.Rows(I).Cells(3).Value = DT.Rows(I).Item("Name3")
         DataGridView1.Rows(I).Cells(4).Value = DT.Rows(I).Item("Name4")
         DataGridView1.Rows(I).Cells(5).Value = DT.Rows(I).Item("Name5")
Next

A: I reckon that both of the grid controls you refer to should [have] be[en] used like this:
DataGridView1.DataSource = DT

devExpressGridView.DataSource = DT


text:
Q: Linking to a .dll file without the .lib I need to rewrite some Delphi code to C++ and we need to link to the dynamic library TMLComm2004.dll. It turns out that we don't have any .lib file so we decided to generate it, using the following command lines:
dumpbin /EXPORTS C:\Users\fayard\Desktop\TMLComm2004.dll > C:\Users\fayard\Desktop\TMLComm2004.txt

We obtain the following file
Microsoft (R) COFF/PE Dumper Version 14.00.24215.1
Copyright (C) Microsoft Corporation.  All rights reserved.

Dump of file C:\Users\fayard\Desktop\TMLComm2004.dll

File Type: DLL

  Section contains the following exports for TMLcomm.dll

    00000000 characteristics
    401F6AD5 time date stamp Tue Feb  3 10:33:09 2004
        0.00 version
          1 ordinal base
          27 number of functions
          27 number of names

    ordinal hint RVA      name

          1    0 00001122 _MSK_COFFDownloadFlash@16
          2    1 0000114F _MSK_COFFDownloadRAM@20
          3    2 0000106E _MSK_CheckSum@12
          4    3 00001172 _MSK_CloseComm@0
          5    4 00001190 _MSK_GetActiveBoard@4
          6    5 0000109B _MSK_GetBoardInfo@8
          7    6 0000104B _MSK_GetBytesCountInQueue@0
          8    7 0000119A _MSK_GetChar@4
          9    8 000010E6 _MSK_GetCharNoWait@4
         10    9 000011A4 _MSK_GetCommBaudRate@4
         11    A 000010DC _MSK_GetHostBoard@4
         12    B 0000108C _MSK_OpenComm@16
         13    C 000011DB _MSK_ReceiveData@16
         14    D 000011CC _MSK_ReceiveMessage@4
         15    E 0000105A _MSK_RegisterReceiveUnsolicitedMsgHandler@4
         16    F 000011AE _MSK_ResetMSKBoard@0
         17   10 00001037 _MSK_SendChar@4
         18   11 000010EB _MSK_SendData@16
         19   12 0000126C _MSK_SendMessage@4
         20   13 0000128F _MSK_SetActiveBoard@4
         21   14 00001136 _MSK_SetB0BlockAsData@4
         22   15 0000100A _MSK_SetBoardBaudRate@4
         23   16 00001019 _MSK_SetCharMode@4
         24   17 00001168 _MSK_SetCommBaudRate@4
         25   18 00001050 _MSK_SetDebugWindow@8
         26   19 00001276 _MSK_SetHostBoard@4
         27   1A 00001046 _MSK_UpdateCommTimeouts@0

  Summary

        C000 .data
        3000 .idata
        6000 .rdata
        4000 .reloc
       21000 .rsrc
       3E000 .text
        2000 shdata

Then, we have edited the TMLComm2014.txt file and changed it to a .def file with the @xx removed. The file looks like:
EXPORTS
_MSK_COFFDownloadFlash
...

Then, we generate a .lib file with:
lib /def:C:\Users\fayard\Desktop\TMLComm2004.def /out:C:\Users\fayard\Desktop\TMLComm2004.lib

We compile the following program:
extern "C" {
  bool MSK_OpenComm(unsigned char a, unsigned short b, bool c, unsigned char d);
}

...

When we compile and link against the .lib, we get an error:
LNK2019 unresolved external symbol _MSK_OpenComm referenced in function...

What's wrong with what I do?
Update
I have managed to compile with:
extern "C" {
  bool __stdcall MSK_OpenComm(unsigned char a, unsigned short b, bool c, unsigned char d);
}

but now the problem is at link time. I am puzzled as from command line, I have:
==================================================
dumpbin /headers TMLComm.lib

  Version      : 0
  Machine      : 14C (x86)
  TimeDateStamp: 5964C365 Tue Jul 11 14:24:05 2017
  SizeOfData   : 00000022
  DLL name     : TMLComm2004.dll
  Symbol name  : __MSK_OpenComm@16
  Type         : code
  Name type    : no prefix
  Hint         : 11
  Name         : _MSK_OpenComm@16

==================================================
dumpbin /exports TMLComm.dll

         12    B 0000108C _MSK_OpenComm@16

==================================================

Compilation goes fine now, but the problem is at link time:
link tmlcomm.obj Motor.obj main.obj TMLComm.lib /out:main.exe

Microsoft (R) Incremental Linker Version 14.00.24215.1
Copyright (C) Microsoft Corporation.  All rights reserved.

tmlcomm.obj : error LNK2019: unresolved external symbol _MSK_OpenComm@16 referenced in function "bool __cdecl msk_opencomm(unsigned char,unsigned short,bool,unsigned char)" (?msk_opencomm@@YA_NEG_NE@Z)
Teclis.exe : fatal error LNK1120: 1 unresolved externals

A: Have a look at Microsoft's documentation of decorated names. For C, a leading underscore and a trailing @<number> denotes the stdcall calling convention, which is different from the standard cdecl.
So, you should just modify your declarations for all functions where the symbol ends with @<number>:
extern "C" {
  __stdcall bool MSK_OpenComm(unsigned char a, unsigned short b, bool c, unsigned char d);
}

I'm not sure whether stripping the @<number> part from the .def file is the right thing to do, I doubt it, but just try it out.
From my experiment with MinGWs tool for creating a .def file (gendef), the name in the .def should not include the leading underscore, but it should include the @<number> part at the end. So for this example function, the .def should have the following line:
MSK_OpenComm@16

An alternative to manually creating these required files are the tools that come with MinGW. You could just do the following:
gendef foobar.dll                     # generates the .def
dlltool -d foobar.def -l foobar.lib   # generates the import library

Based on your comments, you might need to manually edit the .def file gendef is giving you to contain lines like this:
MSK_OpenComm@16=_MSK_OpenComm@16

It seems that gendef could be confused because the dll exports decorated names which isn't expected.

When using an import library, this will have "static stubs" named like the actual exported symbols of the DLL, but with __imp__ prepended. To account for this, you need yet another attribute in your declarations:
extern "C" {
  __declspec(dllimport) __stdcall bool MSK_OpenComm(unsigned char a, unsigned short b, bool c, unsigned char d);
}


text:
Q: Wordpress: call function from functions.php OR write plugin, which one better? To extend wordpress and make pages loaded fast (best performance), we should write a new function and put in WP-THEME/functions.php or write a new plugin? Which way is better?
Thanks,
--Joanson

A: I am willing to bet that if we are exclusively looking at performance, writing the function in functions.php is going to be easier and a better option for you. Also note that the plugin could be used across all themes etc... if you're going to have a mobile theme etc... whereas the functions.php is only usable within the theme you placed the function in.
Happy coding!

A: I find myself reusing a lot of custom built functions across wordpress sites. I create an includes folder and comment in and out what I need for that particular site from the functions.php file.

A: It better to create function in function.php

A: there's a big difference in choosing to create a plugin or a function. is it using across several theme's? is it theme oriented or site oriented? maybe you'll use it in future projects?
a great solution is the mu-plugins, an must-use always-running plugins, that runs before the regular plugins. you can find more information in these links:

http://codex.wordpress.org/Must_Use_Plugins
http://justintadlock.com/archives/2011/02/02/creating-a-custom-functions-plugin-for-end-users

Further more, i advise you to go and read the following excellent article, it will help you to decide:

http://wpcandy.com/teaches/how-to-create-a-functionality-plugin


text:
Q: External PHP Email Request Responding with 500 Internal Server Error I am working on creating a contact us form for a website. I am using jquery to create an .click() function for an html button. then using ajax to call the email.php code. When I click the button the console displays the following error:
500 (Internal Server Error).
I'm new to ajax and php being used together so I have no idea what to do at this point.
Here is the HTML form:

    <form name = "contact">

        Subject:
        <input name = "subject" id = "subject" ng-model = "subject" required/>
        You Must Enter a subject!
        Valid!

        Body:
        <input name = "body" id = "body" ng-model = "body" required/>
        Your email must have a body!
        Valid!

        Return Email:
        <input name = "signature" id = "signature" ng-model = "signature" type = "email" required/>
        You must enter a valid return email!
        Valid!

        <button ng-disabled = "contact.$invalid" id = "sendmail" type = "submit" class = "btn btn-success">Submit</button>

    </form>

and here is the jQuery/AJAX call to the php code:
$(function() {
$("#sendmail").click(function() {

    var data = {

        to: "myemail",
        subject: $("#signature").val() + ": " + $("#subject").val(),
        message: $("#body").val()
    }

    $.ajax({

        type: "POST",
        url: "email.php",
        data: data,
        success: function() {

            alert("Message sent");

        }

    });

    console.log(data);

});

});
And finally, here is the php code that is responsible for sending out the email:
<?php
    if ($_POST["submit"]) {

        $subject = $_POST["subject"];
        $message = $_POST["message"];
        $headers = "From: " . $_POST["name"] . "Reply to: " . $_POST["signature"];

        mail("myemail", $subject, $message, $headers))

    }

?>

Any help would be greatly appreciated.

A: The problem with Error 500 is it's not specific. It just means "something went wrong". It's impossible to diagnose much of anything with just an Error 500.
What you need to find out is what caused the Error 500, which would be in your PHP error log, if you know where that is.
The first question I'd ask you is - what environment are you running PHP in? Is it on your computer or is it on a web server with an internet service provider? If you don't run a development environment on your PC I strongly advise you to get something simple like XAMPP installed and develop there. It's not ideal for advanced developers but for learning your way around PHP, it's good. Not least because it writes out proper error logs you can actually access and read :)
The other thing is to look at the PHP documentation which provides some handy information about the mail function:
http://php.net/manual/en/mail.requirements.php
As you can see - mail() expects to be run on a system with access to a sendmail command. If the system you're running php on either doesn't have sendmail or might not have sendmail this could be your problem. However, without an error log to look at I'm making guesses.
So my advice would be to try on a local installation of PHP first. And also with locally running PHP (eg using xampp) you'll have to set up SMTP server details - the server, username and password and security details you use for sending mail. But you will get access to much more comprehensive logs and error information.

A: Firstly, you should have a "submit" key in your JavaScript code.
$("#sendmail").click(function() {

    var data = {
        to: "youremail@gmail.com",
        subject: $("#signature").val() + ": " + $("#subject").val(),
        message: $("#body").val(),
        signature: $('#signature').val(),
        name: "Your name",
        submit: true //You'll receive $_POST['submit'] in email.php
    }

    $.ajax({
        type: "POST",
        url: "email.php",
        data: data,
        success: function() {
            alert("Message sent");

        }
    });
});

I just added some lines in data variable. Do not forget The data received in $_POST array in PHP are the same that you've send in your ajax method
In the code you'd posted, $_POST['name'] was undefined.
<?php
if ($_POST["submit"]) {
    $subject = $_POST["subject"];
    $message = $_POST["message"];
    $headers = "From: " . $_POST["name"] . "Reply to: " . $_POST["signature"];
    //Use the receiver email you've set in your JS
    $to = $_POST['to'];

    mail($to, $subject, $message, $headers))

}

?>

Then, as said in an other answer, you should try to develop on you own PC and only when your website is finished deploy it onto your server.
On a Debian based OS for instance you can use it:
$ sudo apt-get install apache2 mysql-server php5
This command will install an Apache webserver, a MySQL server, and PHP 5 on your PC. Or, as said in an other answer you can use XAMP that do the same things.
Once you have a website running, you can configure your server to send email.
This post explain how to configure the php.ini in order to use your own mail adress. Of course you can use other than Gmail if you want.
If you receive a mail from your own server, that means your code is right. You
can deploy it onto the server, and configure it the same way if necessary.


text:
Q: How do I get my regex to ignore decimal-separator if it is not followed by a number? I am trying to come up with a function to capture a number from a string. What I came up with on my own is currently used in this code:
Function ArrayOfCleanedString(strIn As String) As Variant
  Dim objRegex As Object, objAllMatches As Object, sAllMatches() As String, v As Variant, i As Long
  Set objRegex = CreateObject("vbscript.regexp")

  objRegex.Global = True
  objRegex.IgnoreCase = False
  'objRegex.Pattern = "^(?:(?i)(?:[+-]?)(?:(?=[0123456789]|[.])(?:[0123456789]*)(?:(?:[.])(?:[0123456789]{0,}))?)(?:(?:[E])(?:(?:[+-]?)(?:[0123456789]+))|))$"
  'objRegex.Pattern = "^-?(?:(?:0|[1-9][0-9]*)(?:,[0-9]+)?|[1-9][0-9]{1,2}(?:,[0-9]{3})+)$"
  objRegex.Pattern = "\-?\d+[" & Application.DecimalSeparator & "\.]?\d*"

  Set objAllMatches = objRegex.Execute(strIn)

  If objAllMatches.Count <> 0 Then
    ReDim sAllMatches(1 To objAllMatches.Count)
    For Each v In objAllMatches
      i = i + 1
      sAllMatches(i) = v
    Next
    ArrayOfCleanedString = sAllMatches
  Else
    ArrayOfCleanedString = Array()
  End If
End Function

Sub test()
  Dim v As Variant, v2 As Variant

  v2 = ArrayOfCleanedString("1abc-10.1-1abx1,1o1.")
  'v2 = ArrayOfCleanedString("")
  If Not IsArrayEmpty(v2) Then
    For Each v In v2
      Debug.Print CStr(v)
    Next
  End If
End Sub

This code does however have a problem in that it captures a punctuation / comma at the end of the number, even if there are no digits after it.
I did some searching, and found the two other patterns I've tried in this post, but as you can probably guess they didn't work in VBA :)
I'd try modifying them, but considering that I don't really understand them that is somewhat tricky.
So what I am asking is; is there any simple way to strip the punctuation mark / comma from the end of the match, if it isn't followed by a number?
Alternately, is there any way to translate any of the other two patterns to VBA's brand of regex?
Is there any other obvious flaws in my method? I am quite new to this, so I do a lot of trial and error :P
Oh, and in case any of you wonder about the isEmptyArray method in my code, it is copied from Chip Pearson's page of functions for VBA-arrays.

A: You can use the posted regex and simply remove trailing "." from elements of the array before returning the array:
Function ArrayOfCleanedString(strIn As String) As Variant
    Dim objRegex As Object, objAllMatches As Object, sAllMatches() As String, v As Variant, i As Long
    Set objRegex = CreateObject("vbscript.regexp")

    objRegex.Global = True
    objRegex.IgnoreCase = False
      'objRegex.Pattern = "^(?:(?i)(?:[+-]?)(?:(?=[0123456789]|[.])(?:[0123456789]*)(?:(?:[.])(?:[0123456789]{0,}))?)(?:(?:[E])(?:(?:[+-]?)(?:[0123456789]+))|))$"
      'objRegex.Pattern = "^-?(?:(?:0|[1-9][0-9]*)(?:,[0-9]+)?|[1-9][0-9]{1,2}(?:,[0-9]{3})+)$"
    objRegex.Pattern = "\-?\d+[" & Application.DecimalSeparator & "\.]?\d*"

  Set objAllMatches = objRegex.Execute(strIn)

  If objAllMatches.Count <> 0 Then
    ReDim sAllMatches(1 To objAllMatches.Count)
    For Each v In objAllMatches
      i = i + 1
      sAllMatches(i) = v
      If Right(sAllMatches(i), 1) = "." Then
        sAllMatches(i) = Left(sAllMatches(i), Len(sAllMatches(i)) - 1)
      End If
    Next
    ArrayOfCleanedString = sAllMatches
  Else
    ArrayOfCleanedString = Array()
  End If

End Function


text:
Q: Node with text in top left and bottom right rectangle corner I like to define style for the following node:

So far I manage to do the following code:
\documentclass[border=3mm,tikz]{standalone}
    \usetikzlibrary{positioning,shapes.multipart}

\makeatletter
\def\tikzsavelastnodename#1{\let#1=\tikz@last@fig@name}
\makeatother

\tikzset{%
    node distance=0mm and 15mm,
element/.style={%
    draw, fill=white,
    text width=24mm, minimum height=11mm,
    node contents={},
    append after command={\pgfextra{\tikzsavelastnodename\tikzsavednodename}},#1
                },
subelement/.style={%
    append after command =
    {node[fill=cyan!30,minimum size=3mm, inner sep=2pt, outer sep=0.4pt,
          anchor=north west]
          at (\tikzsavednodename.north west) {#1}}
                            },
subtext/.style={%
    append after command =
    {node[text width=24mm-3mm, %draw,
          inner sep=0pt, outer sep=2pt,
          align=center, anchor=south east]
          at (\tikzsavednodename.south east) {#1}}
                            },
             }

\begin{document}
    \begin{tikzpicture}
\linespread{0.8}
\node [element,
       subelement=HB,
       subtext=max. two line long text];
\end{tikzpicture}
    \end{document}

This code gives what I like to have, however it has serious weakness: text width is fixed in style. I like to have it as one option for both  styles: element and subtext. Also I like to have common interface for all style option, something similar as follows:
\node [element=<text width> / <top left text> / <bottom right text>];

For this I looking how to merge all three styles (element, subelement and subtext) into one, but I quickly recognize that in this I need help of  someone more skilled then I am in the programming TikZ.
Edit:
Encouraged with percusse comment I try to construct a solution using path picture:
    \documentclass[border=3mm,tikz]{standalone}
    \usetikzlibrary{chains, positioning}
    \newcommand\ppbb{path picture bounding box}

    \begin{document}
        \begin{tikzpicture}[
element/.style args = {#1:#2:#3}{draw, fill=white,
    text width=#1,
    minimum height=11mm, outer sep=0pt, node contents={},
    path picture={%
        \node[fill=cyan!30, minimum size=3mm, inner sep=2pt, outer sep=0.4pt,
              below right=\ppbb.north west] {#2};
        \node[text width=#1-3mm, inner sep=0pt, outer sep=2pt, align=right, font=\small,
              above right=of \ppbb.south east] {#3}; }
                                }% end of style
                            ]
    \linespread{0.8}
    \node (d1) [element=21mm:D1:short text];
    \node (d2) [element=22mm:D2:two line long text];
    \node (d3) [element=15mm:D3:narrow node];
    \node (d4) [element=18mm:D4:two line long text];
        \end{tikzpicture}
    \end{document}

This solution doesn't work. Error is:
Unknown function `path` (in 'path picture bounding box.north west)

I don't know, what I do wrong in this MWE.

A: Meanwhile I made the following solution:
\documentclass[border=3mm,tikz]{standalone}
\usetikzlibrary{chains, positioning}
\newcommand\ppbb{path picture bounding box}

\begin{document}
    \begin{tikzpicture}[
    node distance = 0mm,
      start chain = going right,
element/.style args={#1:#2:#3}{name=local name,%
    draw, fill=white,
    text width=#1, minimum height=11mm, outer sep=0pt,
    node contents={},
    append after command={node[fill=cyan!30,
        minimum size=3mm, inner sep=2pt, outer sep=0.4pt,
        anchor=north west]
        at (local name.north west) {#2}},
    append after command={node[text width=#1-3mm,
%        minimum height=9mm, text depth=0.5ex, % <-- this doesn't work as expected
        inner sep=0pt, outer sep=2pt,
        align=right, font=\small, anchor=south east]
          at (local name.south east) {#3}},
    on chain
                                },
                            ]
\linespread{0.8}
\node (d1) [element=21mm:D1:short text];
\node (d2) [element=22mm:D2:two line long text];
\node (d3) [element=15mm:D3:narrow node];
\node (d4) [element=18mm:D4:two line long text];
    \end{tikzpicture}
\end{document}

This solution is very close to what I like to have. Its weakness is formatting bottom right nodes. I also try to construct solution as propose percusse in his comment above, but so far I'm not able to resolve errors (see my edit of question). I still looking for better solution :)


text:
Q: Break JSON response into new line without removing comma React When I receive a JSON response I want this to be broken into a new line.

This solution breaks into a new line but it also removes the "," after every line

{JSON.stringify(op.responses['properties'][key]).split(",").join("\n")}

I everything to break into a new line without removing the "comma , ".

A: It's quite simple: do it exactly like you are doing it, but add a comma to your 'join'

{JSON.stringify(op.responses['properties'][key]).split(",").join(",\n")}


text:
Q: Coroutne не перехватывают кастомные исключения Решил перевести проект с rxjava на coroutne,начал с retrofit
//кофиг ретрофита
       mAuthRetrofit = Retrofit.Builder()
        .baseUrl(BASE_URL_AUTH)
        .client(authClient())
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .build()

        fun authClient() =OkHttpClient.Builder().addInterceptor { chain ->
            val response = chain.proceed(chain.request())
            when (response.code()) {
               400 -> throw ErrorLogin()
               ...
            }
        response
       }.build()

//метод из интерфейса для retrofit
 @Headers("Content-Type: application/json")
 @POST("auth/login")
 suspend fun login(@Body body: UserBody): UserApiPojo

//сам вызов в презентере
    val errorHandler = CoroutineExceptionHandler { context, exception ->
      Timber.e(exception)
 }

fun clickLogin() {
    if (loginAndPassIsNotEmpty()) {
        viewModelScope.launch(Dispatchers.IO + errorHandler) {
            val result = runCatching { repository.auth.login(login, password) }
            result.onSuccess { user ->
                repository.auth.saveUser(user)
                withContext(Dispatchers.Main + errorHandler) {
                    router.loginComplete()
                }
            }.onFailure { error ->
                viewState?.let { view ->
                    when (error) {
                        is ErrorLogin -> view.showErrorLogin()
                    }
                }
            }
        }
    }
}

Если запрос успешный то все работает хорошо, но если я ввожу неверные данные, то у меня OkHttpClient обрабатывает данные и возращает ошибку ErrorLogin(). На rx  далее без проблем перехватывал тот или Exception и далее уже в презентере выполнял те или ные действия. Почему здесь приложение крашится и ошибка не поподает ни в errorHandler  ни в result.onFailure
FATAL EXCEPTION: OkHttp Dispatcher
Process: ru.exomple.app, PID: 11546
java.lang.Error: ru.exomple.app.api.error.ErrorLogin: Login or password wrong
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1173)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:919)
 Caused by: ru.exomple.app.api.error.ErrorLogin: Login or password wrong
    at ru.exomple.app.api.AppService$authSetupClient$1.intercept(AppService.kt:48)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
    at okhttp3.RealCall$AsyncCall.execute(RealCall.java:200)
    at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)

Я конечно могу убрать  throw ErrorLogin() из OkHttpClient. Но мне хотелось понимать как все это работает и почему эти ошибки не ловятся.

A: Чтобы ваши исключения ловились Retrofit-ом и передавались вызываемому коду, они должны быть унаследованы от IOException. Все другие считаются фатальными и пропускаются выше.
Вот тут была дискуссия почему так: https://github.com/square/okhttp/pull/5457
Вот тут ответ enSO: https://stackoverflow.com/a/58711127/5479247


text:
Q: How can I put something like this in a Smarty template? I am trying to convert a pre-existing site that had html and php intermingled into a Smarty template based site. I never used Smarty before so this is proving very difficult for me. I get that you can assign a variable like so:
$smarty->assign('number_of_items_in_cart', $number_of_items_in_cart);

and use it in the tpl file like so:
{$number_of_items_in_cart}

but what about more complex things like this block of code that I had on the old site:
$query = mysql_query(" SELECT * FROM products WHERE id = '$pid' ");

if (mysql_num_rows($query) == 1) {

    while ($row = mysql_fetch_array($query)) {
        extract($row);
        echo "
$name
";
        echo "";
        echo $description;
        echo '
'.money($price).'
';
        echo "<input type='text' value='1' class='qty-$id' />";
        echo "Add to Cart";
    }

} else {
    redirect('404.php');
}

How can I work with this in a Smarty template, since the output is within a while loop?

A: Instead of echoing this, you can append it in a string variable  then pass it to smarty:
$string = "";
while ($row = mysql_fetch_array($query)) {
        extract($row);
        $string .= "
$name
";
        $string .=  "";
        $string .=  $description;
        $string .=  '
'.money($price).'
';
        $string .=  "<input type='text' value='1' class='qty-$id' />";
        $string .=  "Add to Cart";
    }

Now u can pass it to smarty
$smarty->assign('place_holder', $string);

I hope this is what you are looking for

A: You can use the foreach builtin function to iterate over an array containing your query results.
You could also use foreachelse to display an alternate message (though in this case you're redirecting).
See example 7.9 in http://www.smarty.net/docsv2/en/language.function.foreach .
Edit: there's also a while function if that's what you really want.


text:
Q: React js Socket.io and State Hello I am trying to save in a state the response that my socket sends me through the back end
This is a method where I send messages to my socket
export default class Home extends Component {

    constructor(){
        super()

        this.state = {
          informationReceived: 'Nothing yet!'
        }
        const token = localStorage.getItem('token');
        const socket = io('http://localhost:8080', {
            query: { token: token }
        });

        socket.on('success', (receivedInfo) => {
            this.setState({
              informationReceived: receivedInfo
            })
          })

      }

      emitInfoToAll = () => {
        const token = localStorage.getItem('token');
        console.log('entrou')
        const socket = io('http://localhost:8080',{
            query: { token: token }
        });

        socket.emit('myevent', 'Hello realtime connected users!')
        console.log(this.state.informationReceived);
      }
}

But this way I would be opening connection to my socket twice when sending and receiving
I was wondering how I can only open one connection so when I send a reply to my backend I don't have to open again
and how could I set these values that I get for my p's tags:

 Name:

 Points:  0

A: You should place socket as state of the component so that you can mock it in emitInfoToAll method
export default class Home extends Component {

constructor(){
    super()

    this.state = {
      informationReceived: 'Nothing yet!'
      socket: null;
    }

    const token = localStorage.getItem('token');
    socket = io('http://localhost:8080', {
        query: { token: token }
    });

    socket.on('success', (receivedInfo) => {
        this.setState({
          informationReceived: receivedInfo
        })
      })

  }

  emitInfoToAll = () => {
    const { socket } = this.state;
    console.log('entrou')
    socket.emit('myevent', 'Hello realtime connected users!')
    console.log(this.state.informationReceived);
  }
}

Update: Help set value to p tag
export default class Home extends Component {

    constructor() {
        super()

        this.state = {
            informationReceived: 'Nothing yet!',
            socket: null
        }

        const token = localStorage.getItem('token');
        socket = io('http://localhost:8080', {
            query: { token: token }
        });

        socket.on('success', (receivedInfo) => {
            this.setState({
                informationReceived: receivedInfo
            })
        })

    }

    emitInfoToAll = () => {
        const { socket } = this.state;
        console.log('entrou')
        socket.emit('myevent', 'Hello realtime connected users!')
        console.log(this.state.informationReceived);
    }

    render() {
        const { informationReceived } = this.state;
        const { name, point } = informationReceived;
        return (

 Name: {name}

 Points: {point}

        );
    }
}


text:
Q: Closed form probability random walk will hit k >=1 times in n steps I'm using Mathematica to try to solve
https://quant.stackexchange.com/questions/24970 and came across what
seems like a simple question: if you take a standard random walk of
n steps, what is the formula for the probability you'll touch +k
at least once. More generically, what's the probability distribution
of a random walk of n steps.
I can compute this chance using a recursive formula:

c[n_,0] := 1
c[0, k_] := 0
c[n_,k_] := c[n,k] = 1/2*(c[n-1,k-1] + c[n-1,k+1])

but Mathematica won't RSolve it:

RSolve[{f[n,0] == 1, f[0,k] == 0, f[n,k] == 1/2*(f[n-1,k-1]+f[n-1,k+1])},
 f[n,k], {n,k}]

returns unevaluated. I'm not too surprised, since Mathematica isn't
that good with two variable recursion.
However, I'm convinced there's a "simple" formula here, or at least a
good approximation for large n.
I did try a few different things to no avail:

*

*Trying to find a formula for specific values of n or k.

*Using Log to see if this was an exponential distribution of some sort.

*Comparing it to the right half of the normal distribution.

*Trying to find a formula for the interpolation, since the function
itself is somewhat "juddery" (ie, f(x+1) = f(x) in many cases).
I'm convinced I can use Pascal's triangle (ie, the binomial theorem
and Mathematica's Binomial function) to resolve this, but can't
quite figure out how.

A: This is basically a reformulated problem of a random walk with absorbing boundary. If you place an absorbing boundary at $k$, your probability is complementary to the probability of being absorbed after $n$ steps. This does not have a recursion relation by itself, you need to also study where the walker is after $n$ steps (in order to know whether there's a chance of hitting the boundary in the next) and take the marginal of that distribution. This converts a seemingly 2-variate problem into a 3-variate one, which is even worse, so let's try and help Mathematica a bit first.
It helps greatly to imagine the absorbing boundary as a source of "negative probabilities" which cancel out exactly with the probability the walker arrives there after any particular number of steps. If we then let these probabilities propagate just as normal, they evolve into the corresponding modifications of the probability distribution of the unperturbed walk.
Even more interestingly, all one needs to do is to start another walker with a formal probability of $-1$ at the mirror image of the original starting position, reflected along the absorbing boundary. One then can work with the full line without the need to change the behaviour at $x=k$ in any way. Indeed, the probabilities of getting to $k$ at any time $t$ from the left and from the right cancel out, which is exactly what we want according to the above paragraph.
The total probability, only summed in the "positive half-plane" $x < k$, is then the probability that the walker hasn't reached $x=k$ up to the corresponding time. This can be expressed rather easily,
$$p_t = \sum_{x=-t}^{k} 2^{-t} {t \choose \frac{t+x}2} - \sum_{x=-t}^{k} 2^{-t} {t \choose \frac{t+x-2k}2}$$
The first sum is simply the normal probability of finding a walker at $x ≤ k$ at time t. The second is the probability of finding another walker at the same time in the same region if we shift the initial position to $2k$. This is to be subtracted for the effect of the absorbing boundary. Importantly, in both sums, only terms $x$ for which $t-x$ is even are taken, other (which would result in noninteger terms in the binomial coefficients) are ignored.
The next obvious operation to simplify this formula is to change the summation index in the second sum from $x$ to $2k-x$ (this does not change parity so does not affect which $x$'s are taken), resulting in
$$p_t = \sum_{x=-t}^{k} 2^{-t} {t \choose \frac{t+x}2} - \sum_{x=k}^{2k+t} 2^{-t} {t \choose \frac{t-x}2}.$$
The second summand can be changed to match the first without effect. Moreover, the second summation bound can be trimmed down to $t$ as any further terms are zero:
$$p_t = \sum_{x=-t}^{k} 2^{-t} {t \choose \frac{t+x}2} - \sum_{x=k}^{t} 2^{-t} {t \choose \frac{t+x}2}.$$
The behaviour splits depending on whether $x=k$ belongs to the sum or not. If it does not, the sums do not have any overlapping terms. If it does, they overlap in $k$. Let us focus on the former case as it is slightly easier.
Therefore, let $k$ and $t$ be of different parity. Define $d = \lfloor(k+t)/2\rfloor$. After one more change of summation indices the formula becomes
$$p_t = 2^{-t} \left( \sum_{y=0}^{d} {t \choose y} - \sum_{y=d+1}^{t} {t \choose y} \right).$$
Note that this almost looks like a binomial formula but one where a slice of the terms is taken with a negative sign. The familiar theorem does not apply in such cases, so here's where Mathematica comes in handy. Let's try
Sum[Binomial[t, y], {y, 0, d}]

(* 2^t - Binomial[t, 1 + d] Hypergeometric2F1[1, 1 + d - t, 2 + d, -1] *)

Voilà. The second sum is obviously just the complement to $2^t$, so the difference reads
$$p_t = 2^{-t} \left( 2^t - 2 {t\choose d+1} {}_2F_1(1, d-t+1; d+2; -1) \right)$$
and the desired probability of hitting $k$ at least once is
$$1 - p_t = 2^{1-t} {t \choose d+1} {}_2F_1(1, d-t+1; d+2; -1)$$
This formula does not work when the difference of $t$ and $k$ is even, that is, in times $t$ when the walker can actually reach the position $k$. But, instead of calculating a new formula, one just needs to realize that the probability can't change from such a $t$ to the next step. So, we can take
$$1 - p_t = \begin{cases}
2^{1-t} {t \choose d+1} {}_2F_1(1, d-t+1; d+2; -1)\\
\quad \mathrm{where}\ d = \lfloor(k+t)/2\rfloor
\quad\hfill \mbox{if $t-k$ odd,} \quad\\
2^{-t} {t+1 \choose d+1} {}_2F_1(1, d-t; d+2; -1)\\
\quad \mathrm{where}\ d = (k+t)/2
\quad\hfill \mbox{if $t-k$ even.} \quad
\end{cases}$$
The Mathematica function would be
c[k_, n_] := If[OddQ[n - k],
    With[{d = Floor[(n + k)/2]},
        2^(1 - n) Binomial[n, d + 1] Hypergeometric2F1[1, 1 + d - n, 2 + d, -1]],
    With[{d = (n + k)/2},
        2^(-n) Binomial[n + 1, d + 1] Hypergeometric2F1[1, d - n, 2 + d, -1]]]

To conclude and confirm let's compare the values predicted by it:
Table[c[k, n], {k, 1, 3}, {n, 0, 6}] // Column

(* {0, 1/2, 1/2, 5/8, 5/8, 11/16, 11/16}
   {0, 0, 1/4, 1/4, 3/8, 3/8, 29/64}
   {0, 0, 0, 1/8, 1/8, 7/32, 7/32} *)

with counting the trajectories of length $n$ appearing at least once at $k$ directly:
Table[
    Count[Accumulate /@ Tuples[{-1, 1}, n], {___, k, ___}]*1/2^n,
    {k, 1, 3}, {n, 0, 6}] // Column

(* {0, 1/2, 1/2, 5/8, 5/8, 11/16, 11/16}
   {0, 0, 1/4, 1/4, 3/8, 3/8, 29/64}
   {0, 0, 0, 1/8, 1/8, 7/32, 7/32} *)

Edit: By the way, the hypergeometrics reduce to a finite summation in both cases and cancel out nicely with their respective prefactors, leaving
$$1 - p_t = \begin{cases}
2^{1-t} \sum_{n=0}^{t-d-1} {t \choose d+n+1}
& \mbox{if $t-k$ odd,} \quad\\
2^{-t} \sum_{n=0}^{t-d} {t+1 \choose d+n+1}
& \mbox{if $t-k$ even.} \quad
\end{cases}$$
with $d = \lfloor(k+t)/2\rfloor$. At the moment I'm not sure why but I'm certain there will be a very simple explanation. But often expressions with $_2F_1$ count better as a "closed form".


text:
Q: Self referencing email form in Sharepoint 2007 I am a content editor new to Sharepoint and have to build a registration form for a training department. As there is no need to access a db, I have been told InfoPath is not required, is this correct?
If not using Infopath, can I just build a form using html in either a content web part or page content area? I have intermediate html skills but am unsure whether Sharepoint will support any scripting, and, if so ,which language - I assume asp.net of which I know nothing, my skills being more php based.
There is nothing tricky about most of the form itself. The applicant fills in their details including their line manager's email address. The main place I get unstuck is the form is then submitted to the line manager, who's address is an input to the form, for approval. As this will change everytime, I assume a script is required, but there is where my knowledge runs out and I cannot find a similar question after several days searching the web.
I assume I will also need a script to validate the email address (not compare it to a db, just for making sure it is a valid email format).
Is anyone able to point me in the direction of some of these answers? I am not asking for someone to code it for me, but It would be helpful if you know of a tutorial site where I could learn to do this myself.

A: I think I found what I am after at this site


text:
Q: Major sets and their algebra, operations There are many major sets of numbers which have definitions we are all familiar with. For example, the set $\mathbb{Z}$ contains a countable number of elements which are given the labels $\dots,-3,-2,-1,0,1,2,3,\dots$ etc.
When we talk about this set, we assume that there are particular operators defined on the set (among others):
$$\begin{align}+&:\mathbb{Z}\times\mathbb{Z} \rightarrow \mathbb{Z}
\\
\cdot\:&:\mathbb{Z}\times\mathbb{Z} \rightarrow \mathbb{Z}\end{align}$$
Such that $(\mathbb{Z},+,\,\cdot\,)$ defines a particular commutative ring where $0$ and $1$ are the additive and multiplicative identities respectively.
My question is this: are these operations inherently defined somewhere within the set's definition, or is the algebra of the set merely implied?
My understanding was that a set consisted solely of a series of elements which we label with whatever names we want. Any algebra on the set, including operations such as $+$, $\cdot$ and exponentiation would then defined in addition to the set itself. Is this done using relations on the set?

A: The operations on something like the integers are not what you'd call inherently defined; we can ignore them entirely and treat $\mathbb{Z}$ as an arbitrary countable set; or we can take any arbitrary countable set, fix a bijection, and use that bijection to "transfer" the operations over, creating an algebraic structure indistinguishable from $\mathbb{Z}$.
That said, some sets are certainly more amenable than others to defining the desired operations. Instantiating $\mathbb{Z}$ as a quotient of $\mathbb{N}\times\mathbb{N}$, for instance, makes it fairly easy to find set theoretic formulae that define the algebraic operations by using the operations on $\mathbb{N}$. While it's true that we can equip any countable set with an isomorphic ring structure, the extra information about the underlying sets of our usual constructions is what helps us show nicely that we have such a ring structure on some countable set in the first place.


text:
Q: SpringBoot Security & MongoRepository how to fetch user by username and password I have Spring boot app that uses mongo as db. I am using spring-security to secure my endpoints:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

However I would like to introduce login endpoint where users will be able to provide username & password. Once I have their credentials I am going to verify if such user (with this password and username) exists in mongodb. All of my attempts to retrieve the user by username and password from Mongodb failed.
My repository looks like:
public interface UserRepository  extends MongoRepository<User, String> {

@Query("{ 'username' : ?0 }")
User findUserByUsername(String username);

@Query("{username : ?0, password : ?1}")
User findUserByUsernameAndPassword(String username, String password);
 }

method  User findUserByUsernameAndPassword(String username, String password); always returns null even though such user exists in db.
Application starts with the following configuration:
@SpringBootApplication

public class AccountApplication {
@Bean
RestTemplate restTemplate() {
    return new RestTemplate();
}

public static void main(String[] args) {
    SpringApplication.run(AccountApplication.class, args);
}

}
@EnableWebSecurity
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
            .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/id/login", "/users").permitAll()
            .antMatchers(HttpMethod.GET,  "/users").permitAll()
            .anyRequest().authenticated();
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

}
Even if I tried to comment this row:   .addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
the user can not be fetched by username and password.
How I can fetch the user by username and password?
Thanks in advance!
EDIT
I founded the solution here: why spring security gives empty password to password encoder?
I forgot to set Getter of password field.


text:
Q: Session state unexpected behavior with async I am investigating async and await in the context of ASP.NET MVC controller methods, and am getting some unexpected behavior.
I have the following controller class:
[SessionState(System.Web.SessionState.SessionStateBehavior.Required)]
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    public async Task<ActionResult> Check1()
    {
        Session["Test"] = "Check";
        System.Diagnostics.Debug.WriteLine("Session: " + Session["Test"]);
        await Task.Delay(20000);
        return View();
    }

    public ActionResult Check2()
    {
        var test = Session["Test"];
        ViewBag.Test = test;
        return View();
    }
}

And simple views for each method Check1 and Check2:
Check1
@{
    ViewBag.Title = "Check1";
}

View with Delay

Check2
@{
    ViewBag.Title = "Check2";
    var check = ViewBag.Test;
}

Immediate View @check

Now immediately after starting the application, when I open http://localhost:23131/Home/Check1 in one tab and http://localhost:23131/Home/Check2 in 2nd tab, the call to Check1 returns after 20 seconds as expected, and call to Check2 returns immediately, but it doesn't have the value set in the session state, which I fail to understand why. It should be set immediately since it is before the delay. However, correct value is printed on output window.
Now after Check1 returns, hitting refresh on Check2 tab brings value from session in viewbag and displays it.
After this, if I again refresh both tabs, Check2 doesn't return after Check1 is completed (20 seconds delay) despite Check2 being async.
My questions are:

*

*First time when both tabs are opened, Check2 returns immediately due to Check1 being async, and it is not blocked despite SessionStateBehavior.Required since await statement returns control until awaited task completes. Why doesn't Check2 gets the value before Check1 returns?

*After 1st time, Check2 gets stuck until Check1 returns despite Check1 being async, why is this? Upon re-running the application, Check1 returns immediately as stated in the previous question but only once.

*Is there any concept I have missed or stated wrong in my explanation.

Using ASP.NET with .NET Framework 4.5, Visual Studio 2013 running on Windows 7 Ultimate.

A: For your question 2, if I understand correctly what you are doing is you refresh both tabs (presumably the one with check1 just before check2), and observe that check2 is not finishing loading until after check1 is finished.
The reason for this is that asp.net processes requests that are (potentially) writing to the same session in serial, not in parallel. That means, as long as any one request is pending, a second request will not even start processing until the first request is finished. Using tasks, async or manual thread handling will not work around this behaviour. The reason is that accessing the session is not a thread-safe operation. Potential workarounds are to not use session state in pages that do not require them, or use ReadOnly session state in pages that do not need to write to the session.
Both are accomplished by using the EnableSessionState property on the page, either setting to False to disable session state, or to ReadOnly to indicate that you do not write to the session in any requests to this page.
Also see for example answers here.
For question 1, it may be the reason is that session state is persisted only after the ReleaseRequestState life-cycle event (which is executed at the very end of the request), even though I would have expected this to to only matter when using a non-inproc session store. The more likely reason is however, that the request to check2 executes first (and blocks even the start of processing for check1). Perhaps you can elaborate how exactly you test this and how you make sure which request is executed first.
Edit:
what may be happening is this: in your first try, you do not actually use the same session (the session is not yet created when you start and a new one is created for each request. That also explains why the second request is not blocked until the first is finished). Then, on the second try, both will use the same session (because the last written session-cookie is used by both tabs). You can confirm that theory by printing the asp session (Session.SessionID) id and/or using cookieless session state


text:
Q: BPC VBA After_Refresh I am automating a report that will open an upload template to perform an EVSND and close the upload template in order to complete the report.  When the upload template is closed, I get the message:

UploadTemp.xlsm is closed.
  Trimming EvINP function or refresh schedules cannot be completed.

I understand there are VBA available for After_Refresh, but I do not know how to include this in my code.
This is my code:
Dim ULTemplate As Workbook

Set ULTemplate = Workbooks.Open("C:\UploadTemp.xlsm")

With ULTemplate

Application.Run ("MNU_eSUBMIT_REFSCHEDULE_BOOK_CLEARANDREFRESH")

End With

ULTemplate.Close SaveChanges:=True

How would I make Excel wait until the refresh is complete prior to closing this file?

A: You Could Try this
For i = 1 To ActiveWorkbook.Connections.Count
  ActiveWorkbook.Connections(i).OLEDBConnection.BackgroundQuery = False
  MsgBox ActiveWorkbook.Connections(i).OLEDBConnection.BackgroundQuery
Next
Activeworkbook.RefreshAll


text:
Q: Css media queries percent width I have following markup (simplified for demostration)
https://jsfiddle.net/n07znakb/3/

playlist-content is the width of 1000px (which is playlist-item number x  playlist-item width), I set this in javascript.
If there were 10 playlist-items then the width would be 2000px for example.
I want to achieve the following:
wrapper max width is 600px, 3 playlist-items are visible (this works)
when the wrapper width is between 600 and 400px, I want playlist items to be 33.3% width of the playlist-inner (which is the second upper parent!), so 3 playlist items visible.
when the wrapper width is below 400px width, I want playlist items to be 50% width of the playlist-inner (which is the second upper parent!), so 2 playlist items visible.
I know I can do this with javascript. I wonder if I can do it with css alone?
With current css it doesnt work because setting 33.3% width takes parent width which is playlist-content, but I want it to be 33.3% width of one more upper parent which is playlist-inner.
Hopefully someone will understand.

A: You should code from mobile and up.
And set the wrapper to be relative.
So from 0px to be drastic, you want the playlist items to be 100%;
.playlist-item{width:100%;}

from 400 and up, you want 50%;
@media screen and (min-width: 400px) {
   .playlist-item{width:50%;}
}

from 600 and up, you want 33.3%;
@media screen and (min-width: 600px) {
   .playlist-item{width:33.3%;}
}

I made a ul list for example here:
https://jsfiddle.net/n07znakb/4/


text:
Q: Header template wont alway pull up css I am new to php, but suspect there is a simple solution that I am not aware of.
I have made a template for the header on every page, but when the user loads pages the css page changes in relation to their current page.
How do I have php track how many levels up in a folder the user is so I can pull the css from anywhere in the website?
<link rel="stylesheet" href="../templates/css/css.css" type="text/css" />

That is my current link to css, but for a page further down in folders I need it to add additional ../

A: You should use an absolute path from the root of the website (note, no ".." just a "/"):
<link rel='stylesheet' href='/templates/css/css.css' type='text/css' />

Will always work, as long as your css is at:
http://yourwebsite.com/templates/css/css.css

A: you shouldn't be using a relative path then. Why not just do something like:
<link rel="stylesheet" href="http://www.mysite.com/templates/css/css.css" type="text/css" />

or
<link rel="stylesheet" href="/templates/css/css.css" type="text/css" />

or
<link rel="stylesheet" href="<?php echo $_SERVER['DOCUMENT_ROOT']; ?>/templates/css/css.css" type="text/css" />

whichever suits your needs - since you may be working locally and have a strange file structure, or a shared style directory for example

A: The best method is to use:
<link rel="stylesheet" href="<?php echo $_SERVER['DOCUMENT_ROOT']; ?>/templates/css/css.css" type="text/css" />


text:
Q: Function composition on finite set is identity function Let $X$ be a finite set and $f: X \to X$ a bijective function.
Show that there exists a natural number $n \ge 1$ so that $f^n = \text{id}_X$ where $f^n := \underbrace{f \circ f \circ \ldots \circ f}_{n \text{ times}}$.
Intuitively I can explain it: Since $f$ is bijective every element of $X$ is uniquely mapped onto every element of $Y$ (here $X$). So because $X$ is finite, there are only finitely many possible combinations in which the elements can be mapped. Now if I repeatedly apply $f$ on an input, there must come a point where the second latest output is so that applying the function once more gives exactly the original input again. Since there are only finitely many combinations in which the elements can be mapped the function needs to be applied repeatedly only finitely many times.
Is my intuition correct? And how would one prove it actually?

A: Your intuition is right, but perhaps incomplete. How do you know that you can't get trapped in some kind of "cycle" that never gets you back to the starting point? (It's true that you can't, but why?)
As for how to prove it, here are some hints: since $X$ is finite, there are only a finite number (say, $m$) of bijections of $X$ to itself. So, consider the collection of functions $f, f^2, f^3, \dots, f^{m+1}$. By the pigeonhole principle, two of those must in fact be the same function. Use this fact, along with the fact that every bijection has an inverse, to make a conclusion.


text:
Q: Request is missing required authentication credential - Expected OAuth 2 access token, login cookie or other valid authentication credential I want to refund to Google Play Developer Console IAP(In-App-Purchase) or order using Google API. I got an error when I hit their url, someone help me fix it.
This is my code
<?php
$url = "https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{packageName}/orders/{orderId}:refund";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
echo "<pre>";
print_r($server_output);
?>

Responce
{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "errors": [
      {
        "message": "Login Required.",
        "domain": "global",
        "reason": "required",
        "location": "Authorization",
        "locationType": "header"
      }
    ],
    "status": "UNAUTHENTICATED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "CREDENTIALS_MISSING",
        "domain": "googleapis.com",
        "metadata": {
          "service": "androidpublisher.googleapis.com",
          "method": "androidpublisher.OrdersService.Refund"
        }
      }
    ]
  }
}


text:
Q: How to add CA certificate to cacerts store so that it works as expected? UPDATE: After I have found a solution, I edited the question to be more clear for future reference.
I've got a corporate (ie not well known) CA certificate from a company which provides us a web services to be called from Java. I added this CA certificate to default cacerts trust store (keytool -import -file cert.cer -alias myca -keystore jre/lib/security/cacerts), but connection to the service still fails with the dreaded "PKIX path building failed" message. I have checked that issuer field of the end server certificate is the same as in the CA certificate and also validity dates is ok.
I don't know how to explain this. I can think of the following reasons but I don't know which one is true:

*

*I have noticed that when I add also the end server certificate to trust store, the connection is OK. Maybe cacerts by design don't work as I expect (ie all the certificates signed by an authority added there are considered valid), but instead I have to add all the end server certificates to a trust store including CA certificate of their issuer.

*I have to add CA certificate in some other way - by different command, to different file etc.

*Maybe the CA certificate is not correct and keytool refuses to consider it a certificate authority.

*Maybe PKIX path building fails for other reason.

How can I debug this problem more to find an answer?
Details:

*

*The end server certificate is wildcard certificate

*There is no intermediate certificate, just root and the end certificate

A: I was facing the same problem with "PKIX path building failed" with Let's Encrypt signed certificates at a time Java didn't incorporate the Let's encrypt CA certificate in its default trust store.
My story is written in detail here: http://blog.novoj.net/2016/02/29/how-to-make-apache-httpclient-trust-lets-encrypt-certificate-authority/
At the end I was able to make Java trust "the end of the chain" server certificate by creating internal trust store embedded in my application that contains only root CA certificate (and the backup one).
I much more prefer creating internal application truststore than importing certificate in main Java trust store for two reasons:

*

*you don't need another extra step in install procedure for initializing the global trust store

*you limit "the trust" to you application and don't affect another applications running on the same JVM (or better you can even limit the trust to the certain instances of client objects in your application if required)

Maybe I had a different scenario than you're facing, so downvote me if I didn't get the point.

A: The trust store needs to contain the root certificate (the CA's cert).
I'm not sure if that's what you mean by "the last one I'm the chain", but the CA certificate should be the last one in the certificate chain presented by the server.
If your certificate is signed by a well-known CA, then the CA cert should be in the trust store, and if the server's certificate chain is set up properly, everything should just work.
If yours is a self-signed certificate, then the root certificate will not be in the trust store, and you will have to add it.

A: Thanks to @pedrofb comment I found out that the reason PKIX path fails is simply that the CA certificate I got is not the CA that signed the end certificate. What made it so complicated is the monstrous incompetence of company that gave me the CA certificate which obviously has two CAs with almost the same description (cn, o, st, c) which differs only in SN and which both issued the same wildcard certificate. Only after I became super paranoid and compared the SNs, I understood the problem.


text:
Q: Storing dynamic objects with growing lists on disk Okay so I have been developing a system so far in main memory that has many different objects and each object stores lists of other objects in the system. Now I want to move this to persistent storage. I'm not looking for the obvious answer of using a DBMS because the point is that I'm writing a custom database for my system.
Now for each object I'm assigning an ID. The ids can be looked up in a table to find the block and offset for the location of the data for that object. Now each object has lists/sets that point to other objects in the system. So obviously in the storage they will be lists of 8 byte (using longs for the ids) ids that can be used to find the other objects. Now my question here is that I know the lists will be growing over time so they need room to grow. My best thought so far for storing the lists so that I won't need to move around objects when they grow is to have each list assigned an id just like the objects so that they can looked up in a table just like the objects to find them on the disk.
Now each list portion will have a set allocated space to store 10 objects and then at the end will be the id of the next list portion if it contains more objects. This seems like a decent way to do it and to deal with constantly growing objects but I'm wondering if there are any better approaches. I would store the indexes in memory (space permitting) so given an object id, the lookup is in memory then it would take 1 I/O to find get it's data and list ids from the disk. then for each list you want to traverse through it would take another lookup and I/O for every 10 objects in the list or less if the block is cached.
The number of I/O's is not terrible and I would try to keep locality of list portions to eliminate unnecessary I/Os, but is there a better way of doing this? Am I right to try and store the lists separate from the object or should I consider methods of storing them with the object's data. My worry about doing that is that as one list grows it will run into another list and then need to be fragmented and this can get more complicated. Any suggestions are appreciated and thanks in advance.

A: Your idea of having these expandable lists is good. I think your explanation is missing some details (ie: ordered lists or not, what do you mean by trying to separate lists from objects, a diagram of these lists might help).
I would keep a sorted index in memory for fast access. The index would have list id, and location on disk. If you're interested in range queries go with a B tree approach, otherwise you could use a hashmap to store these indeces.
A further improvement, if you're doing searching on the lists, is to keep them sorted... or at least semi sorted so that you can group similar lists in the same chunk. This would speed up searching in the lists if you every so often cache to memory say the boundaries of each chunk (nodes with values b/w 1-9, 10-25, etc). Merge sort is probably the best sort for lists. Or even better, when you insert nodes in the lists insert in the correct location so the list is always sorted. Then look up with binary search. If data is not indexed properly and not sorted, you're going to disk multiple times for queries and in this case any search you use will give you linear time because of disk time.
You can also cache data nodes of the 10% most looked up nodes/lists.
Depending on the size of these lists (and how manyc chunks you have for them), you could use some RAID so you can get some parallel reads/writes.


text:
Q: Does it still make sense to learn low level WinAPI programming? Does it make sense, having all of the C#-managed-bliss, to go back to Petzold's Programming Windows and try to produce code w/ pure WinAPI?
What can be learn from it? Isn't it just too outdated to be useful?

A: Analogy: If you build cars for a living (programming), then its very pertinent to know how the engine works (Win32).

A: Simple answer, YES.

A: This is the answer to any question that is like.. "does it make sense to learn a low level language/api X even when a higher level language/api Y is there"
YES
You are able to boot up your Windows PC (or any other OS) and ask this question in SO because a couple of guys in Microsoft wrote 16-bit assembly code that loads your OS.
Your browser works because someone wrote an OS kernel in C that serves all your browser's requests.
It goes all the way up to scripting languages.
Big or small, there is always a market and opportunity to write something in any level of abstraction. You just have to like it and fit in the right job.
No api/language at any level of abstraction is irrelevent unless there is a better one competing at the same level.
Another way of looking at it: A good example from one of Michael Abrash's book: A C programmer was given the task of writing a function to clear the screen. Since C was a better (higher level) abstraction over assembly and all, the programmer only knew C and knew it well. He did his best - he moved the cursor to each location on the screen and cleared the character there. He optimized the loop and made sure it ran as fast as it could. But still it was slow... until some guy came in and said there was some BIOS/VGA instruction or something that could clear the screen instantly.
It always helps to know what you are walking on.

A: Yes, for a few reasons:
1)  .net wraps Win32 code.  .net is usually a superior system to code against, but having some knowledge of the underlying Win32 layer (oops, WinAPI now that there is 64-bit code too) bolsters your knowledge of what is really happening.
2)  in this economy, it is better to have some advantages over the other guy when you are looking for a job.  Some WinAPI experience may provide this for you.
3)  some system aspects are not available through the .net framework yet, and if you want to access those features you will need to use p/invoke (see http://www.pinvoke.net for some help there).  Having at least a smattering of WinAPI experience will make your p/invoke development effort a lot more efficient.
4)  (added)  Now that Win8 has been around for awhile, it is still built on top of the WinAPI.  iOS, Android, OS/X, and Linux are all out there, but the WinAPI will still be out there for many many years.

A: This question is bordering on religious :) But I'll give my thoughts anyway.
I do see value in learing the Win32 API. Most, if not all, GUI libraries (managed or unmanaged) result in calls to the Win32 API. Even the most thorough libraries don't cover 100% of the API, and hence there are always gaps which need to be plugged by direct API calls or P/invoking. Some of the names of the wrappers around the API calls have similar names to the underlying API calls, but those names aren't exactly self-documenting. So understanding the underlying API, and the terminology used therein, will aid in understanding the wrapper APIs and what they actually do.
Plus, if you understand the nature of the underlying APIs that are used by frameworks, then you will make better choices with regards to which library functionality you should use in a given scenario.
Cheers!

A: Learning a new programming language or technology is for one of three reasons:
1. Need: you're starting a project for building a web application and you don't know anything about ASP.NET
2. Enthusiasm: you're very excited about ASP.NET MVC. why not try that?
3. Free time: but who has that anyway.
The best reason to learn something new is Need. If you need to do something that the .NET framework can't do (like performance for example) then WinAPI is your solution. Until then we keep ourself busy with learning about .NET

A: For most needs on the desktop you wont need to know the Win32, however there is a LOT of Win32 not in .NET, but it is in the outlaying stuff that may end up being less than 1% of your application.
USB support, HID support, Windows Media Foundation just off the top of my head. There are many cool Vista API's only available from Win32.
You will do yourself a large favor by learning how to do interop with a Win32 API, if you do desktop programing, because when you do need to call Win32, and you will, you won't spend weeks scratching your head.

A: Personally I don't really like the Win32 API but there's value in learning it as the API will allow more control and efficiency using the GUI than a language like Visual Basic, and I believe that if you're going to make a living writing software you should know the API even if you don't use it directly.  This is for reasons similar to the reasons it's good to learn C, like how a strcpy takes more time than copying an integer, or why you should use pointers to arrays as function parameters instead of arrays by value.

A: Learning C or a lower level language can definitely be useful. However, I don't see any obvious advantage in using the unmanaged WinAPI.

A: I've seen low level Windows API code... it ain't pretty... I wish I could unlearn it.  I think it benefits to learn low level as in C, as you gain a better understanding of the hardware architecture and how all that stuff works.  Learning old Windows API... I think that stuff can be left to the people at Microsoft who may need to learn it to build higher level languages and API... they built it, let them suffer with it ;-)
However, if you happen to find a situation where you feel you just can't do what you need to do in a higher level language (few and far between), then perhaps start the dangerous dive into that world.

A: yes.  take a look at uTorrent, an amazing piece of software efficiency.  Half of it's small size is due to the fact that much of it's core components were re-written to not use gargatuian libraries.
Much of this couldn't be done without understanding how these libraries interface with the lower level API's

A: I kept to standard C/C++ for years before learning Win32 API, and to be quite blunt, the "learning Win32 API" part is not the best technical experience of my life.
In one hand Win32 API is quite cool. It's like an extension of the C standard API (who needs fopen when you can have CreateFile. But I guess UNIX/Linux/WhateverOS have the same gizmo functions. Anyway, in Unix/Linux, they have the "Everything is a file". In Windows, they have the "Everything is a... Window" (no kidding! See CreateWindow!).
In the other hand, this is a legacy API. You will be dealing with raw C, and raw C madness.

*

*Like telling one's structure its own size to pass through a void * pointer to some Win32 function.

*Messaging can be quite confusing, too: Mixing C++ objects with Win32 windows lead to very interesting examples of Chicken or Egg problem (funny moments when you write a kind of delete this ; in a class method).

*Having to subclass a WinProc when you're more familiar with object inheritance is head-splitting and less than optimal.

*And of course, there is the joy of "Why in this fracking world they did this thing this way ??" moments when you strike your keyboard with your head once too many and get back home with keys engraved in your forehead, just because someone thought it more logical to write an API to enable the changing of the color of a "Window", not by changing one of its properties, but by asking it to its parent window.

*etc.

In the last hand (three hands ???), consider that some people working with legacy APIs are themselves using legacy code styling. The moment you hear "const is for dummies" or "I don't use namespaces because they decrease the runtime speed", or the even better "Hey, who needs C++? I code in my own brand of object-oriented C!!!" (No kidding... In a professional environment, and the result was quite a sight...), you'll feel the kind of dread only condemned feel in front of the guillotine.
So... All in all, it's an interesting experience.
Edit
After re-reading this post, I see it could be seen as overly negative. It is not.
It is sometimes interesting (as well as frustrating) to know how the things work under the hood. You'll understand that, despite enormous (impossible?) constraints, the Win32 API team did wonderful work to be sure everything, from you "olde Win16 program" to your "last Win64 over-the-top application", can work together, in the past, now, and in the future.
The question is: Do you really want to?
Because spending weeks to do things that could be done (and done better) in other more high-level and/or object-oriented API can be quite de-motivational (real life experience: 3 weeks for Win API, against 4 hours in three other languages and/or libraries).
Anyway, you'll find Raymond Chen's Blog very interesting because of his insider's view on both Win API and its evolution through the years:
https://blogs.msdn.microsoft.com/oldnewthing/

A: It's important to know what is available with the Windows API.  I don't think you need to crank out code with it, but you should know how it works.  The .NET Framework contains a lot of functionality, but it doesn't provide managed code equivalents for the entire Windows API.  Sometimes you have to get a bit closer to the metal, and knowing what's down there and how it behaves will give you  a better understanding of how to use it.

A: This is really the same as the question, should I learn a low level language like C (or even assembler).
Coding in it is certainly slower (though of course the result is much faster), but its true advantage is you gain an insight into what is happening at close to the system level, rather than than just understanding someone else's metaphor for what is going on.
It can also be better when things won't work well, or fast enough or with the sort of granularity that you need.  (And do at least some subclassing and superclassing.)

A: I'll put it this way. I don't like programming to the Win32 API. It can be a pain compared to managed code. BUT, I'm glad I know it because I can write programs that otherwise I wouldn't be able to. I can write programs that other people can't. Plus it gives you more insight into what your managed code is doing behind the scenes.

A: The amount of value you get out of learning the Win32 API, (aside from the sorts of general insights you get from learning about how the nuts and bolts of the machine fit together) depends on what you're trying to achieve.  A lot of the Win32 API has been wrapped nicely in .NET library classes, but not all of it.  If for instance you're looking to do some serious audio programming, that portion of the Win32 API would be an excellent subject of study because only the most basic of operations are available from .NET classes.  Last I checked even the managed DirectX DirectSound library was awful.

At the risk of shameless self-promotion....
I just came across a situation where the Win32 API was my only option.  I want to have different tooltips on each item in a listbox.  I wrote up how I did it on this question.

A: Even in very very high level languages you still make use of the API. Why? Well not every aspect of the API has been replicated by the various libraries, frameworks, etc. You need to learn the API for as long as you will need the API to accomplish what you are trying to do. (And no longer.)

A: Apart from some very special cases when you need direct access to APIs, I would say NO.
There is considerable time and effort required to learn to implement the native API calls correctly and the returning value is just not worth it. I would rather spend the time learning some new hot technology or framework that will make your life easier and programming less painful. Not decades-old obsolete COM libraries that nobody really uses anymore (sorry to COM users).
Please don't stone me for this view. I know a lot of engineers here have really curious souls and there is nothing wrong with learning how things work. Curiousity is good and really helps understanding. But from a managerial point of view, I would rather spend a week learning how to develop Android apps than how to calls OLEs or COMs.

A: Absolutely.  When nobody knows the low level, who will update and write the high level languages?  Also, when you understand the low level stuff, you can write more efficient code in a higher level language, and also debug more efficiently.

A: The native APIs are the "real" operating system APIs. The .NET library is (with few exceptions) nothing more than a fancy wrapper around them. So yes, I'd say that anybody who can understand .NET with all its complexity, can understand relatively mundane things like talking to the API without the benefit of a middle-man.
Just try to do DLL Injection from managed code. It can't be done. You will be forced to write native code for this, for windowing tweaks, for real subclassing, and a dozen other things.
So yes: you should (must) know both.
Edit: even if you plan to use P/Invoke.

A: On the assumption that you're building apps targeted at Windows:

*

*it can sure be informative to understand lower levels of the system - how they work, how your code interacts with them (even if only indirectly), and where you have additional options that aren't available in the higher-level abstractions

*there are times when your code might not be as efficient, high-performance or precise enough for your requirements

*However, in more and more cases, folks like us (who never learned "unmanaged coding") will be able to pull off the programming we're trying to do without "learning" Win32.

*Further, there's plenty of sites that provide working samples, code fragments and even fully-functional source code that you can "leverage" (borrow, plagiarize - but check that you're complying with any re-use license or copyright!) to fill in any gaps that aren't handled by the .NET framework class libraries (or the libraries that you can download or license).

*If you can pull off the feats you need without messing around in Win32, and you're doing a good job of developing well-formed, readable managed code, then I'd say mastering .NET would be a better choice than spreading yourself thin over two very different environments.

*If you frequently need to leverage those features of Windows that haven't received good Framework class library coverage, then by all means, learn the skills you need.

*I've personally spent far too much time worrying about the "other areas" of coding that I'm supposed to understand to produce "good programs", but there's plenty of masochists out there that think everyone's needs and desires are like their own.  Misery loves company.  :)

On the assumption that you're building apps for the "Web 2.0" world, or that would be just as useful/beneficial to *NIX & MacOS users:

*

*Stick with languages and compilers that target as many cross-platform environments as possible.

*pure .NET in Visual Studio is better than Win32 obviously, but developing against the MONO libraries, perhaps using the Sharp Develop IDE, is probably an even better approach.

*you could also spend your time learning Java, and those skills would transfer very well to C# programming (plus the Java code would theoretically run on any platform with the matching JRE).  I've heard it said that Java is more like "write once, debug everywhere", but that's probably as true as (or even moreso than) C#.

A: If you planning to develop a cross platform application, If you use win32, then your application could easily run on linux through WINE. This results in a highly maintainable application. This is one of the advantages of learning win32.


text:
Q: Use owen storage server instead one drive in Office365 I want to switch to office365. I am going to use all its features except OneDrive, because the clients don't want that their files be on the cloud. So is there a way to point on other storage server instead office365.
Thanks,

A: I believe they can use something called OneDrive for Business. I think they need a SharePoint server to host it though.

If you're using Office 365, you get 1 TB of space in the cloud for OneDrive for Business. If your OneDrive for Business library is hosted on a SharePoint server in your organization, your organization's administrators determine how much storage space is available.

Below is the link where I found it.
What is OneDrive for Business?

A: Right now, not that I have heard of.
The whole point of 365 is that everything is in the cloud. The only things that would be spread across on-prem and cloud would be an Exchange server running in Hybrid.


text:
Q: df.diff() how to compare row A with last row B If we have two columns A and B
how to compare row A with last row B
   A         B            diff
0  0.904560  0.208318     0
1  0.679290  0.747496     0
2  0.069841  0.165834     0
3  0.045818  0.907888     0
4  0.485712  0.593785     0
5  0.771665  0.800182     0
6  0.485041  0.024829     0
7  0.897172  0.584406     0
8  0.561953  0.626699     0
9  0.412803  0.900643     0

A: You can use Pandas' shift function to create a 'lagged' version of column B. Then it's a simple difference between columns.
from io import StringIO
import pandas as pd

raw = '''
A,B
0.904560,0.208318
0.679290,0.747496
0.069841,0.165834
0.045818,0.907888
0.485712,0.593785
0.771665,0.800182
0.485041,0.024829
0.897172,0.584406
0.561953,0.626699
0.412803,0.900643
'''.strip()

df = pd.read_csv(StringIO(raw))
df['B_lag'] = df.B.shift(1)
df['diff'] = df.A - df.B_lag

print(df)

Output looks like
          A         B     B_lag      diff
0  0.904560  0.208318       NaN       NaN
1  0.679290  0.747496  0.208318  0.470972
2  0.069841  0.165834  0.747496 -0.677655
3  0.045818  0.907888  0.165834 -0.120016
4  0.485712  0.593785  0.907888 -0.422176
5  0.771665  0.800182  0.593785  0.177880
6  0.485041  0.024829  0.800182 -0.315141
7  0.897172  0.584406  0.024829  0.872343
8  0.561953  0.626699  0.584406 -0.022453
9  0.412803  0.900643  0.626699 -0.213896