text:
Q: Random Walk: Probability of Hitting to Another State Before Returning To the Current State I have a random walk problem that has 8 states, (1, 2, 3, 4, 5, 6, 7, 8).
The agent is currently at the original state 1. For the next move, it has a probability of p1 moving to state 2, and a probability of 1-p1 staying at state 1.
When the agent is at state i (for all i that belong to {2, 3, ..., 7}), it always has a probability of p1 moving to i+1, a probability of p2 moving back to i-1, and a probability of 1-p1-p2 staying at state i.
When the agent is at state 8, its probability to move back to state 7 is p2, and its probability of staying at state 8 is 1 - p2.
For this problem, my questions is that: Assume the agent is currently at the original state 1, what is the agent's probability of first visiting state 8 before he/she moves back to the current state 1.

TO THE ANSWER GIVEN BELOW:
"I have a more challenging question which is similar but the agent could diverge to another route at state d (d is bigger than 1 and smaller than n). At state d, the agent changes its probability of moving to state d+1 to p2, and keep the same probability of moving up to state n, its probability of moving back one state is always p1 down back to state d.
However, at state d, the agent can diverge to another route d -> n+1 -> n+2 -> ... -> n+m, which follows the similar transition probability of the route between state 1 to state d.
I have uploaded a picture that draws the Markov chain of this random walk problem. Now, the question is that: if the agent starts at state 2, what is his/her probability of visiting state n before he/she visits state 1 or state n+m. Note that state n+m is an absorbing state.
Following the equation given by Ionza, I believe a probability can be calculated for this. However, does anybody know that some work has been done for such a problem before? Is there a clean formula that can describe such a probability. Thank you very much."

A: This is a version of the gambler's ruin problem, whose standard solution can be adapted to solve it as shown below.
Consider the more general problem with $\ n\ $ states and the same transition probabilities. Let $\ \pi_i\ $ be the probability, given that the agent is in state $\ i\ $, $i=2,3,\dots,n-1\ $, that he or she will visit state $\ n\ $ before state $1$.  Then $\ \pi_2, \pi_3, \dots,\pi_{n-1}\ $ satisfy the equations
\begin{eqnarray}
\pi_2&=& p_1\pi_3 + \left(1-p_1-p_2\right)\pi_2\ ,\\
\pi_i&=& p_1\pi_{i+1} + \left(1-p_1-p_2\right)\pi_i + p_2\pi_{i-1}\\
&& \mathrm{\ for\ \ } i=3,4,\dots,n-2\ ,\mbox{ and}\\
\pi_{n-1}&=& p_1 + \left(1-p_1-p_2\right)\pi_{n-1} + p_2\pi_{n-2}\ .
\end{eqnarray}
If we set $\ \xi_i=\pi_i\ $ for $\ i=2,3,\dots,n-1\ $, $\ \xi_1=0\ $, and $\ \xi_n=1\ $, then the $\ \xi_i\ $ satisfy the linear recurrence
$$ p_1\xi_{i+1} -\left(p_1+p_2\right)\xi_i + p_2\xi_{i-1}\ , $$
with boundary conditions $\ \xi_1=0, \xi_n=1\ $.  If  $\ p_1\ne p2\ $, this has solution
$$ \xi_i=\frac{1-\left(\frac{p_2}{p_1}\right)^{i-1}}{1 - \left(\frac{p_2}{p_1}\right)^{n-1}}=\frac{\left(\frac{p_2}{p_1}\right)^{i-1}-1}{\left(\frac{p_2}{p_1}\right)^{n-1}-1}\ , $$
while if $\ p_1=p_2\ $, it has solution
$$ \xi_i = \frac{i-1}{n-1}\ .$$
If staying in state $1$ for one or more steps before leaving it does not constitute a "visit" to that state before state $\ n\ $, then the probability of visiting state $\ n\ $ before revisiting state $1$ is just $\ \xi_2\ $.  On the other hand, if the agent must leave state $1$ immediately to retain the possibility of being able to visit state $\ n\ $ first, then the probability of visiting state $\ n\ $ before revisiting state $1$ is $\ p_1\xi_2\ $.


text:
Q: Google Analytic Disparity From March 28th there is a disparity in Google Analytics when compared to the same day to next day.
For example 16th April night it shows 26,649 but if see it next day its decreased by 2k.
I have few AMP pages too on my site, I hope that's not making this disparity.
  (16th night)
  (later day)
  (Comparison)

A: What I see is that you're not comparing the same requests: for the 16th you're making a comparison with the 9th (which might trigger sampling and explain why numbers differ) whereas for the later request you're only querying for the 16th.
Make the same April 16 vs 9 comparison again and see at the top of your report if the results are being sampled.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the proper way to write doc for bindings? While writing a Haskell binding for some libs written in C, a thing has to do is writing docs in haddock format. But since normally the binding is just plain, the doc would be just reformat of original libs' doc.
So my question is, is there some tools to help with this? Thanks.

A: I don't know of any tool for that. Since C docs can take many forms, I don't think there is any tool.
If the binding is indeed plain, essentially everything in IO, same names as the C library, etc. there is a very lazy option: provide a link to the C docs and refer to that.
Better: if the C docs are online, and each function/variable/entity has its own link, provide a link for each entity. In such way, the Haskell programmer can find your docs in Hackage, as usual, and then it's just one more click away to the real docs.
Of course, ideally one should copy the C docs, so that it's immediately available. However, this can require a lot of work, and some care in handling copyright correctly.


text:
Q: Android Seekbar float values from 0.0 to 2.0 how can I get the values from 0.0 to 2.0 with a seekbar? values should go in steps of 0.5 ( 0.0 , 0.5 , 1.0, 1.5, 2.0)
can someone help me?

A:      textView.setProgress(0);
     textView.incrementProgressBy(1);
     textView.setMax(4);

       public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {

                       float progressD=(float) progress/2;
                       textView.setText(String.valueOf(progressD));

// from 0  to 2 step 0.5

A: SeekBar extends ProgressBar.
ProgressBar has a method
public void setMax(int max)

Since it only accepts int you'll have to do some conversion from an int value to get the float that you are after.
Something like this should do the trick:
mSeekBar.setMax(4);
//max = 4 so the possible values are 0,1,2,3,4
seekbar.setOnSeekBarChangeListener( new OnSeekBarChangeListener(){
    public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser)
    {
        // TODO Auto-generated method stub
        Toast.makeText(seekBar.getContext(), "Value: "+getConvertedValue(progress), Toast.LENGTH_SHORT).show();
    }
    public void onStartTrackingTouch(SeekBar seekBar)
    {
        // TODO Auto-generated method stub
    }
    public void onStopTrackingTouch(SeekBar seekBar)
    {
        // TODO Auto-generated method stub
    }
});

This part  will be in your onCreate() and you'll have to use findViewById() or something to get a reference to mSeekBar.
public float getConvertedValue(int intVal){
    float floatVal = 0.0;
    floatVal = .5f * intVal;
    return floatVal;
}

This part is another method that you can add to your Activity that will convert from int to float values within the range you need.

A: You should implement your own custom seek bar, make it jump between the desired values and stick to them, you could find useful info here:
Making A Custom Skinny ProgressBar / Seekbar


text:
Q: Dynamic table as data source in SSAS I want to use dynamic table as my data source in SSAS to create my Time Series model. But only views and static tables from my database are shown in the data source wizard.Is there any method to access available dynamic tables in the database as data source?
Because I need to create around 20-25 models by changing the parameter of dynamic table. If I can't access the dynamic table I have to create 20-25 static tables or views which is very inefficient.


text:
Q: loops list slicing + elements allocation Python I am pretty beginner in Python and trying to do the following:
main_list[80,80,30,30,30,30,20,10,5,4,3,2,1] #list of integers
- slicing the main_list in multiple lists for example list1,2,3,..,n with a sum of sub lists < 100
for i in range of n:
     print(list(i))
list1[80,20], list2[80,10,5,4,1], list3[30,30,30], listn[30,3,2]
Thanks!

A: It's not really clear to me what you consider an acceptable output so I'm assuming that it's any list where its elements sum less than 100.
The solution I found is using recursion. For the list [a, b, c, d] we are going to check the condition for this sublists:
[a]
[a, b] (if the condition for [a] is met)
[a, b, c] (if the condition for [a, b] is met)
[a, b, c, d] (if the condition for [a, b, c] is met)
[a, c] (if the condition for [a] is met)
[a, c, d] (if the condition for [a, c] is met)
[a, d] (if the condition for [a] is met)

[b]
[b, c] (if the condition for [b] is met)
[b, c, d] (if the condition for [b, c] is met)
[b, d] (if the condition for [b] is met)

[c]
[c, d] (if the condition for [c] is met)

[d]

The concept is that for the "n" element in the list we are going to look for the sublists of size "n - 1" to 0 (so the element itself) that meet the requirements. The sublists are formed by the elements at the right of the studied element of each iteration, so for the first 30, the sublist to use would be [30, 30, 30, 20, 10, 5, 4, 3, 2, 1]
This process of finding the sublists for each element is the one that uses recursion. It calls itself for each element of the sublists checking if it meets the condition. For the example above, if the condition is met for [a, b] then it will also try for [a, b, c] and [a, b, d] (by calling itself with the sum of (a, b) and the sublist [c, d].
I've added a few prints so you can study how it works, but you should just use the results variable at the end of the script for getting your results.
main_list = [80,80,30,30,30,30,20,10,5,4,3,2,1]

def less_than_hundred(input) -> bool:
    return input < 100

def sublists_meet_condition(condition, input):
    """
    This function is used to call the sublists_for_element function with every element in the original list and its sublist:
    - For the first element (80) it calls the second function with the sublist [80,30,30,30,30,20,10,5,4,3,2,1]
    - For the fifth element (30) it calls the second function with the sublist [30,20,10,5,4,3,2,1]
    Its purpose is to collect all the sublists that meet the requirements for each element
    """
    results = []
    for index, element in enumerate(input):
        print('Iteration {} - Element {}'.format(index, element))
        if condition(element):
            results.append([element])
            print('{} = {}'.format([element], element))
            num_elements = len(input) - index
            main_element = element
            sublist = input[index+1:]
            for result in sublists_for_element(condition, main_element, sublist):
                new_result = [element] + result
                sum_new_result = sum(new_result)
                results.append(new_result)
                print('{} = {}'.format([element] + result, sum_new_result))
    return results

def sublists_for_element(condition, sum_main_elements, sublist):
    """
    This function is used to check every sublist with the given condition.
    The variable sum_main_elements allows the function to call itself and check if for a given list of numbers that meet the conditions [30, 30, 4] for example, any of the elements of the remaining sublists also meets the condition for example adding the number 3 still meets the condition.
    Its purpose is to return all the sublists that meet the requirements for the given sum of main elements and remaining sublist
    """
    num_elements = '{}{}'.format('0' if len(sublist) + 1 < 10 else '',len(sublist) + 1)
    #print('Elements: {} | Main element: {} | Sublist: {}'.format(num_elements, sum_main_elements, sublist))
    result = []
    for index, element in enumerate(sublist):
        if condition(sum_main_elements + element):
            result.append([element])
            sublist_results = sublists_for_element(condition, sum_main_elements + element, sublist[index+1:])
            for sublist_result in sublist_results:
                result.append([element] + sublist_result)
    return result

results = sublists_meet_condition(less_than_hundred, main_list)


text:
Q: SD Card re initialization using fatfs on stm32f103RB I am using a SD Card Module that has no pin for checking existence of SD Card, So i should do the check using fatfs libs. The micro-controller is STM32F103RB and i'am using SPI protocol to communicate with SD Card. Up to now i can detect a removal state with this code:

bool check_SdCard()
{
    FATFS check_fatfs;

    if(f_mount(&check_fatfs,"",1)==FR_OK)
    {
        f_mount(NULL,"",1);
        return true;
    }
    else return false;
}

The problem is that i can't check insertion of SD Card (or i cant re init the SD Card properly) to Read/Write to it after removing it from a previous initialization.
the above code returns true if the SD Card is inserted to the module from first startup of the device but always returns false if SD Card removed/reinserted after startup. so f_mount could not reinitialize SD Card after reinsertion. I've also tried disk_initialize(0) with no success. Does anyone know how to solve the problem of re initialization of SD Card using fatfs?

A: This isn't exactly the same scenario as the question, but I haven't found a working solution to reinitializing a new card after one was removed and reinserted anywhere on the internet. I managed to figure out how to do it myself, so I figured I'd share it so anyone else searching can fix it.
I've found that when you detect that the card was removed, you need to first call FATFS_UnLinkDriver(SDPath); followed by MX_FATFS_Init(); before you can try to reinitialize the drive. The unlink call is needed to clean up and decrement a counter the initialization function checks. The initialization function clears the state on an internal struct indicating that the drive was already initialized. This'll make it reinitialize the drive next time you go and mount it.
This isn't entirely consistent, but it works most of the time. I'm sure I'm missing something else though.


text:
Q: No results in query after loading data into AWS RDS using Data Pipeline? I have loaded some csv data from S3 into RDS using Data Pipeline. I am using Postgres 10.6. I know the Data Pipeline is definitely doing some writes, since I can see the corresponding increases in write latency, write IOPS, queue depth, etc. The problem is I don't know what it is writing to, because running select count(*) from users returns 0. There are no errors or warnings in Data Pipeline.
I am running the query using psycopg2:
conn = psycopg2.connect(
    host=host,
    port=5432,
    user=username,
    password=password,
    connect_timeout=10,
    database='postgres'
)
cursor = conn.cursor()
cursor.execute('select count(*) from users')

This is my insert query:
INSERT INTO users (id, gender, country_code)
VALUES (?, ?, ?)
ON CONFLICT (id)
DO UPDATE SET
gender = EXCLUDED.gender, country_code = EXCLUDED.country_code;

This is the config for my RDS database/data node:
{
  "*password": "#{*myRDSPassword}",
  "name": "postgres",
  "jdbcProperties": "allowMultiQueries=true",
  "id": "rds_mysql",
  "region": "us-west-1",
  "type": "RdsDatabase",
  "rdsInstanceId": "#{myRDSInstanceId}",
  "username": "#{myRDSUsername}"
},
{
  "database": {
    "ref": "rds_mysql"
  },
  "name": "DestinationRDSTable",
  "insertQuery": "#{myRDSTableInsertSql}",
  "id": "DestinationRDSTable",
  "type": "SqlDataNode",
  "table": "#{myRDSTableName}",
  "selectQuery": "select * from #{table}"
},
{
  "myRDSTableName": "users",
}

The only explanation I can think of is that I am writing to a different database than the default of postgres which I am querying from, but I am not sure where I should set this property. Does anyone have experience with this issue?

A: For reference, fixed this issue by adding optional parameter databaseName="postgres" to the RdsDatabase object.


text:
Q: Help identifying component values, same codes different sizes this is a ESP32 dev kit board, I'm confused about the tantalum capacitor, I can read 106C on both of them which are likely to be 10uF and 16V however their sizes are different. Are those actually the same capacity and voltage rating?

I've looked a few schematics and they all say 10uF on both sides
My best two guesses are

*

*Different ESR o other parameter

*These things are sometimes not highest quality, so they my be trying to fool somebody?

A: If you refer to the AVX catalog, there are three sizes of 10uF/16V capacitors available (EIA imperial 1206/1210/2312), and the main differences are the ESR and the ripple current vs. temperature ratings.


text:
Q: ajax auto complete extender not working right, VB.Net I'm trying to use an ajax auto complete extender, but it's not working....
I put a break point on the GetCompanyNames method in the web service, but it doesn't even hit the break point.
Here is my ajax autoextender
<asp:TextBox TabIndex="1" ToolTip="* Required - enter the Company name" ID="txtCompanyName"
runat="server"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender runat="server" ID="acCompanyName" TargetControlID="txtCompanyName" ServiceMethod="GetCompanyNames" ServicePath="~/WebServices/AutoComplete.asmx" MinimumPrefixLength="1"
EnableCaching="true">
 </ajaxToolkit:AutoCompleteExtender>

Here is the web service that I created
    Imports System.Web
    Imports System.Web.Services
    Imports System.Web.Services.Protocols

    ' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the    following line.
    ' <System.Web.Script.Services.ScriptService()> _
    <WebService(Namespace:="http://tempuri.org/")> _
    <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
    <System.Web.Script.Services.ScriptService()> _
    Public Class AutoComplete
        Inherits System.Web.Services.WebService

<WebMethod()> _
Public Function HelloWorld() As String
    Return "Hello World"
End Function

<WebMethod()> _
Public Function GetCompanyNames(ByVal prefixTest As String) As String()

    Dim db As New DataClassesDataContext

    Dim company = From c In db.CT_Companies
                  Where c.CompanyName.Contains(prefixTest)
                  Select c.CompanyName

    Return company.ToArray

End Function

    End Class

Can anybody see what I'm doing wrong or missing?  Thanks

A: Per the documentation here, you're missing the <System.Web.Script.Services.ScriptMethod()> attribute and an integer count parameter on your method signature.


text:
Q: Determine the volume of an object from pictures Im doing some preliminary research into the problem stated above. I have read a bit about OpenCV and it looks like it may be able to help me out.
I have a subject (it is a metal chain) i can take pictures of and would like to determine the volume of one of the chain links. I can take as many pictures as required. What would be required to accurately calculate the volume of the link? Would i need some size reference in the pictures?
What i am thinking to achieve my goal is to reconstruct a 3D model using x number of images, then import it into Solidworks/CAD to calculate length/width/volume etc.
Any pointers would be appreciated.

A: I think that you could apply space carving in this instance (PDF can be downloaded from the link).  This technique will allow you to construct a closed, polygonal representation of the subject.
And, yes, some means of establishing the scale of your object will be needed.  Here is a brief discussion of the camera intrinsic and extrinsic parameters that are used to establish a relationship between an image pixel and an area (or volume). Since space carving requires that the viewpoint change between each frame, it's probably a good idea to recompute the external camera calibration parameters (extrinsic parameters) frequently. OpenCV has some capacity for determining camera parameters, see this reference or perhaps this tutorial.
Alteratively - if you can assume that the camera orientation will not change much between frames, you might try an easier method.  As you suggested, an object of known size and orientation may be placed in the image, thereby providing scale cues.  Note that this method is fairly straightforward, but will work under limited conditions.  Foreshortening due to perspective and changes in perceived scale due to changing camera orientation will limit this method.
Once the "space" of the chain has been identified and represented in polygonal (i.e. meshed) form, it should be straight-forward to compute the volume.  OpenCV provides some mathematical primitives that should help.

A: If the links were of the same general shape, could you create a base model in Solidworks?  Then you could take 2 pictures, and side view and a top view.  You would then need a way to judge the scale of the link in the picture.  Then you could just drive the dimensions in Solidworks such as length, width, radius, etc.


text:
Q: Telnet to the EchoServer Grizzly sample application I've been working on a server application that will over time receive quite a lot of connections. In order to be able to handle this I have been implementing a non blocking design using the standard java NIO classes. But there are a lot of details to handle, and I would much prefer to use some sort of framework. Preferably I would like to use Spring Integration but I have not been able to find some simple, working examples.
In stead I am now evaluating the Grizzly framework, which seems to offer the functionality I need. I implemented their EchoServer example but found that I was unable to Telnet to the server and have the results echoed back to me on the console. Their EchoClient application works as expected.
In my case I cannot make any assumptions about the clients trying to connect to me, so I have to be able to support everything from simple telnet clients to NIO clients. Is Grizzly able to do this, and if so how?

A: The sample you're working with is based on special input format implemented by StringFilter. The StringFilter decodes/encodes Strings as sequence of bytes with a string-length prefix.
For sure telnet doesn't use the same format to encode Strings that's why server doesn't echo the data back.
In order to make the server work with telnet - just remove a StringFilter from the server's FilterChain (comment out this line):
//          filterChainBuilder.add(new StringFilter(Charset.forName("UTF-8")));


text:
Q: ses.sendmail() gives CORS error. 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'..credentials mode is 'include' I have been stuck on this for 4 days now. I really need some insights.
I have a serverless express app deployed on AWS. I am serving my frontend from S3 and backend from lambda. API gateway has proxy as shown in the serverless.yml below.
I have also used cloudfront to map my domain(https://my.domain.com.au) with the S3 bucket origin URL.
The normal GET POST PUT DELETE requests are working fine. But when I try to access any of the other AWS service from Lambda I get following CORS error.
Access to XMLHttpRequest at 'https://0cn0ej4t5w.execute-api.ap-southeast-2.amazonaws.com/prod/api/auth/reset-password' from origin 'https://my.domain.com.au' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

My use case is to send a mail from my app for which I tried using.
ses.sendEmail(params).promise();

This gave me the same error. So i tried invoking it through lambda, same error. Now i am trying to push mail contents to S3 and send mail from lambda using trigger but this gave me the same error.
The issue doesn't seem to be on the code as its working perfect from local environment. However, i don't want to leave any stones unturned.
Since, my lambda is in a VPC i have used internet gateway and tried setting up the private link as well.
Serverless.yml
service: my-api

# plugins
plugins:
  - serverless-webpack
  - serverless-offline
  - serverless-dotenv-plugin

# custom for secret inclusions
custom:
  stage: ${opt:stage, self:provider.stage}
  serverless-offline:
    httpPort: 5000
  webpack:
    webpackConfig: ./webpack.config.js
    includeModules: # enable auto-packing of external modules
      forceInclude:
        - mysql
        - mysql2
        - passport-jwt
        - jsonwebtoken
        - moment
        - moment-timezone
        - lodash

# provider
provider:
  name: aws
  runtime: nodejs12.x
  # you can overwrite defaults here
  stage: prod
  region: ${env:AWS_REGION_APP}
  timeout: 10
  iamManagedPolicies:
    - 'arn:aws:iam::777777777777777:policy/LambdaSESAccessPolicy'
  vpc:
    securityGroupIds:
      - ${env:AWS_SUBNET_GROUP_ID}
    subnetIds:
      - ${env:AWS_SUBNET_ID1}
      - ${env:AWS_SUBNET_ID2}
      - ${env:AWS_SUBNET_ID3}
  environment:
    /// env variables (hidden)
  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - s3:*
        - ses:*
        - lambda:*
      Resource: '*'

# functions
functions:
  app:
    handler: server.handler
    events:
      - http:
          path: /
          method: ANY
      - http:
          path: /{proxy+}
          method: ANY
          cors:
            origin: ${env:CORS_ORIGIN_URL}
            allowCredentials: true
            headers: 'Access-Control-Allow-Origin, Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization'
            method: ANY

# you can add CloudFormation resource templates here
resources:
  # API Gateway Errors
  - ${file(resources/api-gateway-errors.yml)}
  # VPC Access for RDS
  - ${file(resources/lambda-vpc-access.yml)}

I have configured response headers as well:
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", process.env.CORS_ORIGIN_URL);
    res.header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
    res.header("Access-Control-Allow-Credentials", "true");
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
    next();
});

A: I actually have the same exact error as you but I've figured it out.
I'll just paste my code since you didn't show what your lambda function looks like.
I also know its been two weeks... so hopefully this helps someone in the future.
CORS errors are server side, and I'm sure you are aware. The problem with AWS SES is you have to handle the lambda correctly or it'll give you a cors error even though you have the right headers.
First things first... I don't think you have OPTIONS method in your api gateway...although I'm not sure if ANY can work as a replacement.
Second here is my code:
I check which http method I'm getting then I respond based on that. I am receiving a post event and some details come in the body. You might want to change the finally block to something else. The OPTIONS is important for the CORS, it lets the browser know that its okay to send the POST request (or at least that's how I see it)
var ses = new AWS.SES();

var RECEIVER = 'receiver@gmail.com';
var SENDER = 'sender@gmail.com';

exports.handler = async(event) => {

  let body;
  let statusCode = '200';
  const headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET,DELETE,POST,PATCH,OPTIONS',
    'Access-Control-Allow-Credentials': true,
    'Access-Control-Allow-Headers': 'access-control-allow-credentials,access-control-allow-headers,access-control-allow-methods,Access-Control-Allow-Origin,authorization,content-type',
    'Content-Type': 'application/json'
  };
  console.log(event);

  try {
    switch (event.httpMethod) {
      case 'POST':
        event = JSON.parse(event.body);
        var params = {
          Destination: {
            ToAddresses: [
              RECEIVER
            ]
          },
          Message: {
            Body: {
              Html: {
                Data: html(event.name, event.phone, event.email, event.message), // 'Name: ' + event.name + '\nPhone: ' + event.phone + '\nEmail: ' + event.email + '\n\nMessage:\n' + event.message,
                Charset: 'UTF-8'
              }
            },
            Subject: {
              Data: 'You Have a Message From ' + event.name,
              Charset: 'UTF-8'
            }
          },
          Source: SENDER
        };
        await ses.sendEmail(params).promise();
        break;
      case 'OPTIONS':
        statusCode = '200';
        body = "OK";
        break;
      default:
        throw new Error(`Unsupported method "${event.httpMethod}"`);
    }
  }
  catch (err) {
    statusCode = '400';
    body = err.message;
  }
  finally {
    body = "{\"result\": \"Success\"}"
  }

  console.log({
    statusCode,
    body,
    headers,
  })
  return {
    statusCode,
    body,
    headers,
  };

}


text:
Q: Sinch video call hangup crash android when not received by receiver I am using the video calling feature of the Sinch and facing one issue. The situation is like this. For example I am login as a user A. Try to call user B. Immediately hang up before user B pick up the call. And than User A try to stop the Sinch Client. After a two second I got the Crash. The error logs are below.
W/sinch-android-rtc: webrtc: (mediasession.cc:362): Duplicate id found. Reassigning from 101 to 125
D/DefaultHttpService: Http request to https://sandbox.sinch.com/V1/Session
D/AudioTrackJni: Terminate@[tid=13743]
D/AudioTrackJni: StopPlayout@[tid=13743]
D/AudioTrackJni: ~dtor@[tid=13743]
D/AudioTrackJni: Terminate@[tid=13743]
D/AudioTrackJni: StopPlayout@[tid=13743]
E/rtc: #
# Fatal error in ../../../talk/app/webrtc/androidvideocapturer.cc, line 155
# Check failed: !running_
#
#
A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 13739 (Sinch Worker Th)
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
[ 08-01 12:41:08.376 14347:14347 D/         ]
HostConnection::get() New Host Connection established 0xf3e9b860, tid 14347

A: You fond a bug, the work around is to not stop the client. Usually you start and stop the client as a service. And if you want to receive calls you should never stop it. you should keep it running.
However we added it to bugs to fix because we should not of course crash.


text:
Q: Curl follow location not redirecting to external site I have an initial page which contains a html form which transfers data to post.php to then Curl it.
Problem:
I am transferring the data to a url however, when you click submit from the html page, the url structure then takes you to the following http://localhost:8888/post.php and it brings in all the html back and places it within the post.php.
However, i want it to follow to the external URL but all i get back is a header response which contains the relative URL. I have tried CURLOPT_FOLLOWLOCATION and still nothing.
HTML:
 <form name="nonjava" method="post" action="/post.php">
    <input name="postdata" id="nonjavapostdata" type="hidden" value="<?php echo $variables['postdata']; ?>" />
    £
    <input required="" type="text" class="" id="amount1" name="amount1">

    <input required="" type="text" class="" id="amount2" name="amount2">
    P

    <button type="submit" class="btn btn-default" href="">Submit</button>
</form>

Now with this data, i am transferring everything over to the post.php and determining all the $_POST and curling it to an external URL as a HTTP header.
PHP:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'postdata=' . urlencode(xmlTransfer()));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

// curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
// curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_VERBOSE, true);

// Download the given URL, and return output
$output = curl_exec($ch);

// Close the cURL resource, and free system resources
curl_close($ch);


text:
Q: storing incremented checkbox (jQuery) I have a custom checkbox that increments on click. Everything works fine except I can't figure out how to store the incremented value. This is what I have so far:

var clicks = 0;
$('#checkbox1').click(function() {
  clicks++;
  $('.clickspan').html(clicks);
});
parseInt(document.getElementById('checkbox1').value = clicks)

<input type='checkbox' name='array[]' id='checkbox1' value=''>

print_r($array) gives me 0. I somehow should be able to store the incremented total in a new variable and use that to send back to the value field like this:
parseInt(document.getElementById('checkbox1').value = totalclicks)

But how can I store "totalclicks"?
Thanks!

A: You're setting the value of the checkbox on load only. You need to do that inside the click handler. You can also remove the parseInt(), because, aside from being in the wrong place, it's redundant

$('#checkbox1').click(function() {
  $(this).val(function(i, v) {
    $('.clickspan').html(++v);
    return v;
  });
});

<input type="checkbox" name="array[]" id="checkbox1" value="0">


text:
Q: Order statistic and independence "If $Y_1, Y_2, ..., Y_n$ are independent, uniformly distributed random variables on the interval $[0, \theta]$, show that $U=Y_{(1)}/Y_{(n)}$ and $Y_{(n)}$ are independent."
I have already found $$f_{Y_{(1)}}(y) = \frac{n}{\theta}(1-\frac{1}{\theta}y)^{n-1}$$ and $$f_{Y_{(n)}}(y) = \frac{n}{\theta^n}y^{n-1}$$
I was thinking of showing independence by showing $f(u, y_{(n)}) = f_U(u)f_{Y_{(n)}}(y)$, but I'm not sure if this even makes sense?
Thanks for any help.

A: Approach 1: I would start with the joint distribution of $Y_{(1)}$ and $Y_{(n)}$.  (Since you know how to find the individual order statistic distributions you can use a similar argument to get the joint distribution.)   This is $$f_{Y_{(1)},Y_{(n)}}(y_1, y_n) = \frac{n(n-1)}{\theta^n}(y_n-y_1)^{n-2}, \:\:\:\: 0 < y_1 < y_n < \theta.$$
Then do a bivariate transformation to obtain $f_{U,Y_{(n)}}(u,y_n)$.  The Jacobian of the transformation is just $Y_{(n)}$, and so you get
$$f_{U,Y_{(n)}}(u,y_n) = \frac{n(n-1)}{\theta^n}(y_n - uy_n)^{n-2} y_n, \:\:\: 0 < u < 1, \: 0 < y_n < \theta.$$
Since $f_{U,Y_{(n)}}(u,y_n)$ factors into a function of $u$ and a function of $y_n$, $U$ and $Y_{(n)}$ must be independent.
You can fill in the details, but this is the basic argument for this approach.

Approach 2: Because I can't stop myself, let me also give the argument described by did. :)
Obtain the conditional distribution $f_{Y_{(1)}|Y_{(n)}}(y_1|y_n)$ by dividing $f_{Y_{(1)},Y_{(n)}}(y_1,y_n)$ by the marginal distribution for $f_{Y_{(n)}}$.  This yields
$$f_{Y_{(1)}|Y_{(n)}}(y_1|y_n) = \frac{(n-1)(y_n-y_1)^{n-2}}{y_n^{n-1}}, \:\:\: 0 < y_1 < y_n.$$
Then calculate $P(U < u | Y_{(n)})$ from $f_{Y_{(1)}|Y_{(n)}}(y_1|y_n)$.  This is
$$\begin{align}
P(U < u | Y_{(n)}) &= P(Y_{(1)} < u Y_{(n)} | Y_{(n)} = y_n) \\
&= \int_0^{u y_n} \frac{(n-1)(y_n-y_1)^{n-2}}{y_n^{n-1}} \, dy_1 \\
&= \frac{-1}{y_n^{n-1}} \left[(y_n - y_1)^{n-1} \right]_0^{u y_n} \\
&= \frac{-1}{y_n^{n-1}} \left[(y_n - uy_n)^{n-1} - y_n^{n-1} \right] \\
&= \frac{-1}{y_n^{n-1}} y_n^{n-1} \left[(1 - u)^{n-1} - 1\right]\\
&= 1 - (1-u^{n-1}).
\end{align}$$
Since $P(U < u | Y_{(n)})$ does not depend on $Y_{(n)}$, $U$ and $Y_{(n)}$ are independent.


text:
Q: Join 2 tables on column x based on max value of column y in second table I have read some posts here. Using this post (Select value A from the same record as max( value B) and then join with another table on value C) I have started my query but it does not work. Are nested SELECT queries even allowed in Access?
collar
_______________________
|hole_id|max_depth|...|
|  1    |  340    |   |
|  2    |  400    |   |
|  3    |  250    |   |

assay
______________________
|hole_id|depth_to|...|
|  1    |  58    |   |
|  1    |  62    |   |
|  1    |  69    |   |
|  2    |  102   |   |
|  2    |  110   |   |
|  3    |  20    |   |
|  3    |  25    |   |

I need to return
________________________________
|hole_id|max_depth|depth_to|...|
|  1    |  340    |  69    |   |
|  2    |  400    |  110   |   |
|  3    |  250    |  25    |   |

-
SELECT DISTINCT A.hole_id, A.max_depth, B.depth_from, B.depth_to
FROM collar A
LEFT JOIN assay B
ON A.hole_id = B.hole_id
WHERE A.hole_id = (
     SELECT max(C.depth_to)
     FROM assay C
     WHERE C.hole_id = A.hole_id
     )
WHERE A.max_depth > B.depth_to AND A.section="BLK" AND A.holetype="Exploration"
;

A: Just join the two tables, return the maximum depth_to and group the rest.  No need to nest queries in this case.
SELECT      assay.hole_id
            , max_depth
            , MAX(depth_to) AS max_depth_to
FROM        assay LEFT JOIN collar ON assay.hole_id = collar.hole_id
GROUP BY    assay.hole_id, max_depth
ORDER BY    assay.hole_id

Also no need to fully qualify each field name if it's unique to one table.

A: SELECT collar.hole_id, collar.max_depth, (select max(depth_to) from assay where assay.hole_id=collar.hole_id) AS depth_to
FROM collar;

A: Yes, nested SELECT queries can be done in Access.  Here's one that may give you what you're looking for:
SELECT
    A.hole_id,
    A.max_depth,
    B.depth_from,
    B.depth_to
FROM
    collar A
LEFT JOIN
    (select B.*
    from assay B
        inner join (
            select hole_id, max(depth_to) as max_depth
            from assay
            group by hole_id
            ) BD on BD.hole_id=B.hole_id and BD.max_depth=B.depth_to
     ) as BM on BM.hole_id=A.hole_id
WHERE
    A.section="BLK" AND A.holetype="Exploration"
;


text:
Q: HTML Input Pattern Guide or Answer I am wondering where i could find a Generator for HTML Input Patterns, or a good guide for them.
If you feel like helping even more, im trying to find a pattern that makes sure that a @ is entered.
Thanks alot!
'#' = Information I don't want people seeing (Website name etc.)
P.S (I am wondering because I cannot find any good guides on using them, or how to actually figure out what to put in...)
<form method="post" action="#">
  <input type="text" class="form" placeholder="Name" name="name">

  <input type="text" class="form" placeholder="Email" name="email" pattern=''>
  <input value="@#" class="form" placeholder='@#'  name="type" readonly>

  <input type="text" class="form" placeholder="Backup Email" name="b_email" pattern=''>

  <input type="text" class="form" placeholder=Username name="username">

  <input type="password" class="form" placeholder="Password" name="password">

  <input type="password" class="form" placeholder="Confirm Password" name="password_con">

  <button class="form">Create</button>
</form>

All I know so far is

A: The official documentation, which is literally one of the first results for html pattern has plenty of live examples.
<input type="text" name="type" pattern="[@]+" title="Must have an @ symbol">

In general though, these patterns use regular expressions which is a completely separate subject you need to read up on.


text:
Q: Update 2d array using React and hooks useState and useEffect I'm trying to create easy bouncing ball game in 2d array with React hooks. I have a problem to solve:
When the ball hits the green field, it should change the vector to random and change its value in the array from "Y" to "0". It changes direction, but the green space does not disappear from the board. It's still back after re-render.
Here's a full code: https://stackblitz.com/edit/react-cvlqsp?file=src/App.js
Edit
I found that the green box disappears, but each time the ball moves, it re-renders and it looks like it permanently. I can't help myself not to render the whole thing every time but only the ball movement. Should I use this in useEffect? and how?
Here's functions for random vector and value of array changes not working:
let random = () => {
    if (Math.random() < 0.5) {
      setVectorX((vectorX *= -1));
    } else {
      setVectorY((vectorY *= -1));
    }
  };

  let checkforYCollsion = () => {
    if (board[positionY][positionX] === 'Y') {
      random();
      board[positionY][positionX] = '0'

    }
  };

A: You need to update the state with the changed 2d array by calling setBoardToDisplay, not by assigning the value of board, since this will not trigger a re-render. You can do this by utilising a callback function in setBoardToDisplay.
setBoardToDisplay((prev) => {
  // make desired changes to prev and return it
})


text:
Q: NSAttributedString initWithData and NSHTMLTextDocumentType crash if not on main thread calling
NSAttributedString * as = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil];

on other than main thread, results in a crash
1   0x194b861fc <redacted>
2   0x19801d31c <redacted>
3   0x198010eb4 _os_once
4   0x19801aa2c pthread_once
5   0x195a0858c <redacted>
6   0x195a07c78 WebKitInitialize
7   0x18bb38918 <redacted>
8   0x10020cdf0 _dispatch_client_callout
9   0x10020dcfc dispatch_once_f
10  0x1977f8bd0 <redacted>
11  0x1978009ac <redacted>
12  0x19780bdb8 <redacted>
13  0x1940b259c _NSReadAttributedStringFromURLOrData
14  0x1940b0eb4 <redacted>
15  0x1001041a0 -[MPMPostTextBrickCell attributedTextWithHTMLString:]
16  0x100103d3c __39-[MPMPostTextBrickCell setupWithBrick:]_block_invoke
17  0x187fb3508 <redacted>
18  0x187f04c94 <redacted>
19  0x187ef461c <redacted>
20  0x187fb626c <redacted>
21  0x10020cdf0 _dispatch_client_callout
22  0x100217854 _dispatch_queue_drain
23  0x100210120 _dispatch_queue_invoke
24  0x10021975c _dispatch_root_queue_drain
25  0x10021af18 _dispatch_worker_thread3
26  0x1980192e4 _pthread_wqthread
27  0x198018fa8 start_wqthread

when i don't specify the attribute bellow, than it works
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,

I need to parse the string on background thread, but this makes it impossible :(

A: Maybe its too late to answer this question, but may help others.
Actually NSAttributedString and NSHTMLTextDocumentType must run asynchronously either on main queue or a global queue.
You can use it in a background thread but you have to dispatch your code block containing NSAttributedString's initializer on a global or main queue. For example:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in

            print("Started on \(NSThread.currentThread())")

            let encodedData = "Hello".dataUsingEncoding(NSUTF8StringEncoding)!
            let attributedOptions : [String: AnyObject] = [
                NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
            ]

            let attributedString = (try? NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) ?? NSAttributedString(string: ""))

            print("Finished")

        }

A: The documentation is pretty explicit about that.

The HTML importer should not be called from a background thread (that is, the options dictionary includes NSDocumentTypeDocumentAttribute with a value of NSHTMLTextDocumentType). It will try to synchronize with the main thread, fail, and time out. Calling it from the main thread works (but can still time out if the HTML contains references to external resources, which should be avoided at all costs). The HTML import mechanism is meant for implementing something like markdown (that is, text styles, colors, and so on), not for general HTML import.

Using the HTML importer (NSHTMLTextDocumentType) is only possible on the main thread.
(Source: Apple's documentation)


text:
Q: how to pass dynamic parameters in jquery.autocomplete.js I am using autocomplete for my project of auto selecting cities and areas. I want to now dynamically autoselect areas of city selected. Though the autosearch is working quite well I just not able to send the dynamice cityid for the area. How am I to do this? I tried the option given in this stack answer but to no avail.My code till date:
HTML
<input type="hidden" id="hid_search_city_id" name="hid_search_city_id" value="">

SCRIPT
$(document).ready(function(e) {
    $("#hid_search_city_id").change(function() {
        areas.setOptions({
            params: {
                entity_type: $('#hid_search_city_id').val()
            }
        });
    });
});
var baseUrl = $('input#baseUrl').val();
var url = baseUrl + 'ajax/getSearchCities';
$('input#search_cities').autocomplete({
    serviceUrl: url,
    minChars: 1,
    delimiter: /(,|;)\s*/,
    maxHeight: 400,
    width: 300,
    deferRequestBy: 0,
    onSelect: function(value, data) {
        $('#id').val(+data);
        $('#hid_search_city_id').val('');
        $('#hid_search_city_id').val(data);
    }
})
var url = baseUrl + 'ajax/getSearchAreas';
var areas = $('input#search_areas').autocomplete({
    serviceUrl: url,
    minChars: 1,
    delimiter: /(,|;)\s*/,
    maxHeight: 400,
    width: 300,
    params: {
        entity_type: $('#hid_search_city_id').val()
    },
    deferRequestBy: 0,
    onSearchStart: function(q) {
        areas.entity_type = $('input#search_cities').val();
    },
    onSelect: function(value, data) {
        $('#id').val(+data);
    },
});
areas.setOptions({
    params: {
        entity_type: $('#hid_search_city_id').val()
    }
});


text:
Q: VB6 SCGrid Textbox Within a VB6 form, I'm using an SCGrid object were the cells are editable by means of a textbox.
I suppose the grid control creates a TextBox object as soon as the user clicks a cell.
I need a reference to this TextBox.
In particular, when the user presses the [Left] or [Right] key, I need the current position of the cursor within the textbox. I can then simply call TextBox.SelStart.
Does anybody know how to get the control used when editing a cell?

A: I figured it out myself:
' Declaration needed for getting the current position of the cursor
Private Type Point
  x As Long
  y As Long
End Type

Private Declare Function GetCaretPos Lib "user32" (ByRef lpPoint As Point) As Long

' This function returns the position of the cursor within the cell currently being edited as a TextBox
' The value is expressed as the number of characters preceeding the position
Private Function GetCaretPosition() As Integer

  ' Variables
  Dim position As Point
  Dim result   As Long
  Dim contents As String

  ' Get position
  result = GetCaretPos(position)

  ' Convert it into number of characters
  ' I figured out the factor 15 by trial and error
  ' Don't know where it comes from but it seems independent of the font size
  contents = myGrid.Text(row_gvar, column_gvar)
  result = 0
  While ((result < Len(contents)) And _
         (position.x > (grid_gvar.Parent.TextWidth(Left(contents, result)) / 15)))
    result = result + 1
  Wend

  ' Done
  GetCaretPosition = result

End Function


text:
Q: fluent nhibernate: INSERT error when saving a new entity with a child entity I am trying to save a new entity 'Post' with 1 item added to its 'Revisions' List.
A Post can have many PostRevisions, and a PostRevision can only have one Post.
I have tried several ways of mapping the PostRevisions, my PostRevisionMap is as follows:
 public PostRevisionMap()
    {
        Id(x => x.PostRevisionId, "PostRevisionId");
        Map(x => x.Created, "CreateDateTime").Not.Nullable();
       /// SOME OTHER STUFF HERE
        References(x => x.Post, "PostId"); // OPTION 1

        References(x => x.Post,"PostId").ForeignKey("PostId").PropertyRef(d => d.PostId);  // OPTION 2

        HasOne<Post>(x => x.Post).ForeignKey("PostId").Cascade.All().PropertyRef(x => x.PostId); // OPTION 3
    }

When calling SaveOrUpate I get a different errors
OPTION 1 & 3 cause
The INSERT statement conflicted with the FOREIGN KEY constraint "PostId".

OPTION 2 causes
NHibernate.HibernateException : Unable to resolve property: PostId

My PostMap is as follows:
   public PostMap()
    {
        Id(x => x.PostId).Column("PostId");

        HasMany(x => x.Revisions)
            .Cascade.All()
            .Table("PostRevisions")
            .KeyColumn("PostId")
            .ForeignKeyConstraintName("FK_PostRevision_Post");

       /// OTHER STUFF
    }

Can anyone point me in the right direction as I can not spot the issue.
TIA

A: Try this:
PostMap
HasMany(x => x.Revisions)
    .Inverse()
    .Cascade.All();

PostRevisionMap:
References(x => x.Post);


text:
Q: Are UIViews with alpha=0 or hidden=YES still a performance expense? When a view is hidden or alpha=0 does it still cost CPU power or is it ignored?
if I go:
[view setAlpha:0];

then
[view setFrame:newFrameRect];

What is the performance implication of that?

A: "Something with an alpha of zero, still is drawn, however a view that is hidden is not redrawn to the screen. Since this only happens when the view changes anyways, the difference should be insignificant..."
EDIT
Therefore, setHidden is useful, while changing the alpha is not as beneficial.
In general, memory-wise, there is little benefit. You need to remove from view in order to maximize performance, but the change is so small, it probably won't matter.

A: I doubt there would be a significant difference. Though im just speculating here.
The reason I say this is because ios devices have a gpu, and in this day in age these are very sophisticated. Sophisticated in the sense that if alpha is 0, there is nothing to render, so it's just a simple check with respect to processing cycles. And I am assuming it is smart enough to do this check because graphics chips are smart enough to not render something that is outside of the viewport (or hidden behind foreground pixels).
Maybe running the performance tool on a test app would reveal something more concrete.


text:
Q: Is it possible to accelerate GTK with opengles Is it possible to hardware accelerate the rendering of GTK with OpenglES2.0?

A: Not really. You can put GtkWidgets into the OpenGL scenegraph Clutter using the Clutter-gtk module, but Gtk still draws using cairo and then uploads it to the GFX card as a texture, so there's not a lot of acceleration for just normal windows.


text:
Q: Why would XCode 8.2.1 be applying an ARC rule to a non-ARC file? I'm working on a legacy project that has both ARC and non-ARC modules.  I'm getting an ARC related compiler error ("ARC forbids Objecive-C objects in struct") from a file (SectionedTableModel.h) that is not using ARC though.
I have verified the following
The project setting for "Objective-C Automatic Reference Counting" is NO
There are no compiler flags set for SectionedTableModel.m, while some other files do have "-fobjc-arc" set.  I even tried setting "fno-objc-arc" but it made no difference.
I'm thinking this has to be a bug with the most recent version of XCode, but before I file a radar incident, thought I would see if anyone has any other ideas or suggestions?
Thanks

A: Turns out the .h file was being included by a .m file that WAS set for ARC, which was enough to trigger the warning?  Makes some sense but a little counter-intuitive.


text:
Q: javascript get value from input says Cannot read property 'value' of null I know this should be easy but I have spent hours trying to get this to work.
I am getting back JSON data from a weather api based on zip code. I want the zip code to come from and input(see below). However, when I use document.getElementById('city').value; I keep getting an error message in the console. What am I doing wrong? I know where the problem area is but i'm not sure how to fix it?
HTML
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Weather API</title>

My API call for weather

        <input name="city" type="text" id="city" />
        <button id="submit" onclick="weatherHistory();">Submit</button>

JS
const api = 'http://api.openweathermap.org/data/2.5/weather?';
const city = document.getElementById('city').value; // PROBLEM HERE
const input = 'zip=' + city + ',us';
const api_key = '&APPID= my-key-here';
const units = '&units=imperial';
var url = api + input + api_key + units;

function get(url) {
    return new Promise((resolve, reject) => {
        const req = new XMLHttpRequest();
        req.open('GET', url);
        req.onload = () => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText));
        req.onerror = (e) => reject(Error(`Network Error: ${e}`));
        req.send();
    });
}

function weatherHistory() {
    get(url)
        .then((data) => {
            const x = JSON.parse(data);
            const max = x.main.temp_max;
            const min = x.main.temp_min;
            const humidity = x.main.humidity;
            var div = document.getElementById('blank');
            const api_data = "
 Min Temp: " + min + "
" + "
 Max Temp: " + max + "
" + "
Humidity: " + humidity + "
"
            div.innerHTML = api_data;
        })
        .catch((err) => {
            console.log('Oops something went wrong, please try again');
        });
}

img


text:
Q: How to scroll from one edit text to another when keyboard is visible I've been working on this note app where I have two editTexts, one for the title and one for the note content but for some reason, when there is a keyboard on the screen and the text is very long I can't scroll from say the note content editText to the title editText. I have added one scrollView for each and one for the layout but it still doesn't work.
Though the editTexts scroll just fine when there is no keyboard, how can I make it scroll when there is one?
Below is the screenshot of my problem
`
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context=".screens.newnotescreen.NewNoteFragment">

    <com.google.android.material.card.MaterialCardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="12dp"
        app:cardCornerRadius="4dp"
        app:cardElevation="4dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ScrollView
                android:id="@+id/scrollView"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <com.google.android.material.textfield.TextInputLayout
                        android:id="@+id/title_inputlayout"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="16dp"
                        android:layout_marginTop="16dp"
                        android:layout_marginEnd="16dp"
                        android:layout_marginBottom="8dp"
                        android:paddingStart="8dp"
                        android:paddingEnd="8dp"
                        app:boxBackgroundMode="none"
                        app:hintEnabled="false"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toTopOf="parent">
                        <com.google.android.material.textfield.TextInputEditText
                            android:id="@+id/note_title_edittext"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:background="@android:color/transparent"
                            android:focusable="true"
                            android:hint="@string/title"
                            android:imeOptions="actionNext"
                            android:inputType="textCapSentences|textImeMultiLine"
                            android:textAppearance="@style/TextAppearance.MaterialComponents.Headline6" />

                    </com.google.android.material.textfield.TextInputLayout>

                    <com.google.android.material.textfield.TextInputLayout
                        android:id="@+id/content_inputlayout"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="16dp"
                        android:layout_marginTop="8dp"
                        android:layout_marginEnd="16dp"
                        android:paddingStart="8dp"
                        android:paddingEnd="8dp"
                        app:boxBackgroundMode="none"
                        app:hintEnabled="false"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toBottomOf="@id/title_inputlayout">
                        <com.google.android.material.textfield.TextInputEditText
                            android:id="@+id/note_content_edittext"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:background="@android:color/transparent"
                            android:enabled="true"
                            android:focusable="true"
                            android:hint="@string/note"
                            android:inputType="textMultiLine"
                            android:isScrollContainer="true"
                            android:textAppearance="@style/TextAppearance.MaterialComponents.Body1" />

                    </com.google.android.material.textfield.TextInputLayout>

                </LinearLayout>

            </ScrollView>

        </LinearLayout>

    </com.google.android.material.card.MaterialCardView>

</androidx.constraintlayout.widget.ConstraintLayout>`

A: Add in AndroidManifest.xml for your activity:
android:windowSoftInputMode="adjustPan"

OR
and under the onCreateView() method of the fragment NewNoteFragment do this:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

Hope this solves your problem!


text:
Q: conduit: producing memory leak Working on some observations on a previous question (haskell-data-hashset-from-unordered-container-performance-for-large-sets) I stumbled upon a strange memory leak
module Main where

import System.Environment (getArgs)
import Control.Monad.Trans.Resource (runResourceT)
import Data.Attoparsec.ByteString (sepBy, Parser)
import Data.Attoparsec.ByteString.Char8 (decimal, char)
import Data.Conduit
import qualified Data.Conduit.Attoparsec as CA
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL

main :: IO ()
main = do (args:_) <- getArgs
          writeFile "input.txt" $ unlines $ map show [1..4 :: Int]
          case args of "list" -> m1
                       "fail" -> m2
                       "listlist" -> m3
                       "memoryleak" -> m4
                       --UPDATE
                       "bs-lines":_ -> m5
                       "bs":_ -> m6
                       _ -> putStr $ unlines ["Usage: conduit list"
                                             ,"               fail"
                                             ,"               listlist"
                                             ,"               memoryleak"
                                             --UPDATE
                                             ,"               bs-lines"
                                             ,"               bs"
                                             ]
m1,m2,m3,m4 :: IO ()
m1 = do hs <- runResourceT
            $  CB.sourceFile "input.txt"
            $$ CB.lines
           =$= CA.conduitParser (decimal :: Parser Int)
           =$= CL.map snd
           =$= CL.consume
        print hs
m2 = do hs <- runResourceT
            $  CB.sourceFile "input.txt"
            $$ CA.conduitParser (decimal :: Parser Int)
           =$= CL.map snd
           =$= CL.consume
        print hs
m3 = do hs <- runResourceT
            $  CB.sourceFile "input.txt"
            $$ CB.lines
           =$= CA.conduitParser (decimal `sepBy` (char '\n') :: Parser [Int])
           =$= CL.map snd
           =$= CL.consume
        print hs
m4 = do hs <- runResourceT
            $  CB.sourceFile "input.txt"
            $$ CA.conduitParser (decimal `sepBy` (char '\n') :: Parser [Int])
           =$= CL.map snd
           =$= CL.consume
        print hs
-- UPDATE
m5 = do inpt <- BS.lines <$> BS.readFile "input.txt"
        let Right hs =  mapM (parseOnly (decimal :: Parser Int)) inpt
        print hs
m6 = do inpt <- BS.readFile "input.txt"
        let Right hs =  (parseOnly (decimal `sepBy` (char '\n') :: Parser [Int])) inpt
        print hs

Here is some example output:
$ > stack exec -- example list
[1234]
$ > stack exec -- example listlist
[[1234]]
$ > stack exec -- conduit fail
conduit: ParseError {errorContexts = [], errorMessage = "Failed reading: takeWhile1", errorPosition = 1:2}
$ > stack exec -- example memoryleak
(Ctrl+C)

-- UPDATE
$ > stack exec -- example bs-lines
[1,2,3,4]
$ > stack exec -- example bs
[1,2,3,4]

Now the questions I have is:

*

*Why is m1 not producing [1,2,3,4]?

*Why is m2 failing?

*Why is m4 behaving totally different compared to all other versions  and producing a space leak?

A:
Why is m2 failing?

The input file as a character stream is:
1\n2\n3\n4\n

Since the decimal parser do not expect a newline character, after consuming the first number the remaining stream is:
\n2\n3\n4\n

As the input stream is not exhausted,  conduitParser will run the parser on the stream again, this time it cannot even consume the first character so it failed.

Why is m4 behaving totally different compared to all other versions and producing a space leak?

decimal `sepBy` (char '\n') will only consume \n between two integers, after successfully parsed four numbers, the input stream has only one character in it:
\n

and decimal `sepBy` (char '\n') cannot consume it, even worse it will not fail: sepBy can consume nothing and return empty list. Therefore it parse nothing infinitely and never terminate.

Why is m1 not producing [1,2,3,4]?

I want to know it too! I guess it has something to do with fusing, maybe you should contact the author of conduit package, who just commented your question.

A: To answer the question about m1: when you use CB.lines, you're turning input that looks like:
["1\n2\n3\n4\n"]

into:
["1", "2", "3", "4"]

Then, attoparsec parses the "1", waits for more input, sees the "2", and so on.


text:
Q: Make a textbox fill all the available space in container but there must be some place left for a fixed button I'm making an aspx page that is meant to be viewed inside an iframe. The page exists of a simple gridview and on top of the page is a textbox and a button. (search function)
I want the button on the right side of the textbox so the textbox AND the button together fills all the available width. The button has a fixed width. Only the textbox has a dynamic width.
I've been looking on this but still didn't found a sollution for this CSS problem. Does anyone of you know what css that i have to use to solve my problem so it looks like the scheme below?
[TEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEXTBOX] [BUTTON]
/----------------------------------------------\
|----------------------------------------------|
|-----------------GRIDVIEW---------------------|
|----------------------------------------------|
|----------------------------------------------|
|----------------------------------------------|
\----------------------------------------------/

Thank you!

A: I didn't find something really elegant, but I got 3 options for you.
Set your textbox width with javascript.
textBox.width = textBox.Parent.width - button.width

use a 100% (or almost) width textbox in absolute and put the button over it

  <input type="button" style="float:right" value="search or what not" />
  <input type="text" style="width:100%; position:absolute; top:0px; z-index:-1 " />

use a table

        <input type="text" style="width:100%" />

        <input type="button" value="search or what not" />


text:
Q: Is it possible to print a text message, if condition is not satisfied in protractor? My code:
this.condition = function() {
        element(by.partialLinkText('Times Jobs')).isDisplayed().then(function (result) {
            if (result) {
                element(by.partialLinkText('Times Jobs')).click();
            } else {
                console.log('Times source not found')
            }
        });
    }

If "Times Jobs" is not presented in the page then it should display whatever text inside the else statement. How can i do that?
I don't want to make test fail, just i need to print that text in console.

A: You can use isPresent(), as in this answer, but if you want to keep using isDisplayed(), you must handle the case of the element not being found in the error callback of its returned promise:
element(by.partialLinkText('Times Jobs')).isDisplayed().then(function (result) {
  if (result) {
    element(by.partialLinkText('Times Jobs')).click();
  } else {
    console.log('Times source in page but not displayed');
  }
}, function() {
  console.log('Times source not in page');
});

Or, if you want to output the same message in both of the cases of not being
in the page, or being in the page but not displayed, you can...
element(by.partialLinkText('Times Jobs')).isDisplayed().then(function (result) {
  if (result) {
    element(by.partialLinkText('Times Jobs')).click();
  } else {
    return protractor.promise.rejected();
  }
}).catch(function() {
  console.log('Times source not in page or in page and not displayed');
});

A: You can try this ::
this.condition = function() {
        element(by.partialLinkText('Times Jobs')).isPresent().then(function (result) {
            if (result) {
                element(by.partialLinkText('Times Jobs')).click();
            } else {
                console.log('Times source not found')
            }
        });
    }

as if the element is not present on the page than it give element not found error


text:
Q: Get Vimwiki working with SnipMate (the vim plugins) My issue is that <Tab> completion for SnipMate does not work when I'm in a vimwiki file. I am testing by typing APACHE<Tab> in insert mode, but I don't get the snippet as I do when I'm in, say, .vimrc.
And even though i_<Tab> doesn't work in a vimwikie file, i_<C-R><Tab> does. I get a list of available snippets. Strange.
To make it stranger (well, to me at least), here's the partial output of :imap in a vimwiki file:
i  <Tab>       * <C-G>u<C-R>=snipMate#TriggerSnippet()<CR>
i  <C-R><Tab>  * <C-R>=snipMate#ShowAvailableSnips()<CR>

I think these are correct, and in other files where <Tab> completion does work, the mappings are the same.
oh, and in case you are thinking to suggest putting let g:vimwiki_table_auto_fmt = 0 in my .vimrc as suggested in http://code.google.com/p/vimwiki/wiki/ChangeLog, I tried it and it doesn't solve my problem. That's the only suggestion I found in my search, so that's why I'm here.
I don't know how much of my .vimrc you would want, so I'm just going to give you the ones I think are relevant to keep this question short:
" Vundle: The plugin manager for vim.
    set runtimepath+=~/.vim/bundle/vundle/
    call vundle#rc()
    Bundle 'gmarik/vundle'
" SnipMate: TextMate snippets for vim.
    Bundle "MarcWeber/vim-addon-mw-utils"
    Bundle "tomtom/tlib_vim"
    Bundle "honza/snipmate-snippets"
    Bundle "garbas/vim-snipmate"
" Vimwiki: A personal wiki for vim.
    Bundle 'vim-scripts/vimwiki'
    let g:vimwiki_hl_headers = 1
    let g:vimwiki_hl_cb_checked = 1
    let g:vimwiki_folding = 1
    let g:vimwiki_fold_lists = 1
    let s:vimwiki = {}
    let s:vimwiki.path             = '~/Vimwiki/wiki'
    let s:vimwiki.path_html        = '~/Vimwiki/html'
    let s:vimwiki.ext              = '.md'
    let s:vimwiki.syntax           = 'markdown'
    let s:vimwiki.maxhi            = 1
    let s:vimwiki.diary_rel_path   = 'Journal/'
    let s:vimwiki.diary_index      = 'index'
    let s:vimwiki.diary_header     = 'Journal'
    let s:vimwiki.diary_sort       = 'asc'
    let g:vimwiki_list = [s:vimwiki]

Thanks
Edit:
I don't know why I forgot about this while writing the above. The output of :imap above is incomplete. It also shows:
i  <Tab>       *@vimwiki#tbl#kbd_tab()

Regardless of the value of g:vimwiki_table_auto_fmt. It's probably the source of my problem.. and if so I'd like to get rid of it from .vimrc somehow.

A: The @ in the :imap output shows that Vimwiki defines a buffer-local <Tab> mapping that overrides snipMate's global one. A
:iunmap <buffer> <Tab>

should fix that. You can put that command into ~/.vim/after/ftplugin/vimwiki.vim to make it permanent. But apparently Vimwiki allows customization:
" Table mappings
if g:vimwiki_table_mappings
  inoremap <expr> <buffer> <Tab> vimwiki#tbl#kbd_tab()
  inoremap <expr> <buffer> <S-Tab> vimwiki#tbl#kbd_shift_tab()
endif

So, :let g:vimwiki_table_mappings = 0 in your .vimrc should work, too.

A: Used Ingo Karkat's solution for the longest time but Shift-Tab in insert mode is broken again.
" New fix.
" SOURCE: https://github.com/vimwiki/vimwiki/issues/1268#issuecomment-1312192484
" SOURCE[*g:vimwiki_key_mappings*]: https://github.com/vimwiki/vimwiki/blob/0629b39815c97f1e4ee31e26faa6891b0e13d2d5/doc/vimwiki.txt#L3671
"
" Disable table mappings:
let g:vimwiki_key_mappings =
  \ {
  \ 'table_mappings': 0,
  \ 'table_format': 0,
  \ }


text:
Q: Show items checked on same page using plain javascript Javascript Noob here, trying to learn how to write code in plain javascript using no libraries or frameworks. I'm at a lost for how to display the values of the checked items in a div above the form as well as display the checked values on another page using querystrings URLSearchParams. Thanks in advance for helping me. Hopefully I can pay-it-forward when I finally learn javascript. Here is what I have so far:
<form>

  <input type="checkbox" id="v1" name="toy[]" value="Car">
   Car

  <input type="checkbox" id="v2" name="toy[]" value="boat">
   Boat

  <input type="checkbox" id="v3" name="toy[]" value="Airplane">
   Airplane

  <input type="submit" value="Submit" onsubmit="myFunction()">

</form>

A: You had a few issues:

*

*Missing a "show" element

*<input> fields don't have onsubmit property; that should be on the <form> element

*onsubmit handler should return false to prevent the form from submitting if you want to show the info on the page

*No need for const myToys = document.getElementById("myToys");

*document.getElementsByName("toy").checked won't work since there are no elements named 'toy', but rather 'toy[]'. To get the checked ones, you can't simply append .checked to your function call.

function myFunction() {
  const myToys = document.querySelectorAll("input:checked");
  document.getElementById("show").innerHTML = 'You selected: ';
  let a = []
  myToys.forEach(function(e){
    a.push(e.value);
  })
  document.getElementById("show").innerHTML += a.join(', ')
}
<form onsubmit="myFunction(); return false;">

    <input type="checkbox" id="v1" name="toy[]" value="Car">
     Car

    <input type="checkbox" id="v2" name="toy[]" value="boat">
     Boat

    <input type="checkbox" id="v3" name="toy[]" value="Airplane">
     Airplane

  <input type="submit" value="Submit">
</form>


text:
Q: Values of integer such that a matrix equality does hold The problem is to find all integer values $n\geq 2$ such that there exist two non-zero $n\times n$ real matrices $A,B$ satisfying $$A^2B-BA^2=A.$$
For $n=2$ such matrices do not exist. Therefore, I am a little bit puzzled on the path I should follow: that there are no such matrices for any $n$, or to prove that such matrices exist, at least for some values of $n$ (maybe related to the parity of $n$...). I have managed to prove that if such matrices exist, then $\hbox{tr}(A)=0$ and $\det(A)=0$.

A: $\textbf{Proposition 1}$. $A$ is nilpotent.
$\textbf{Proof}.$ $A^2B-BA^2$ commute with $A^2$. Then (Jacobson) $A^2B-BA^2=A$ is nilpotent.
$\textbf{Proposition 2}$. There are non-zero solutions only when $n\geq 3$;
$\textbf{Proof}$. When $n=2$, $A^2=0$ and $A=0$. No solutions.
When $n=3$, a particular solution is
$A_3=J,B_3=\begin{pmatrix}0&0&0\\-1&0&0\\0&1&0\end{pmatrix}$, where $J$ is the nilpotent Jordan block of dimension $3$.
When $n>3$, a particular solution is
$A=diag(A_3,0_{n-3}),B=diag(B_3,0_{n-3})$.
Note that if $(A,B)$ is a solution, then $(A,B+uI_n)$ is also a solution.

A: The following example is for $n=3.$
$$ A=\begin{bmatrix} 0 &1 &a \\ -1 &0 &0 \\ 1/a &0 &0 \end{bmatrix} $$ and
$$ B = \begin{bmatrix} b & c & ca-a \\ 1-ae & d & -a^2f \\
e & f & 2af+d \end{bmatrix}. $$


text:
Q: How to input certain puzzles from a collection? I'm building a database of math puzzles that each TEX file gathers puzzles in one year such as 2017.tex may have 10 of them, each puzzle and its solution with a label.
Now I give talks and want to choose problems and solutions from these files now and then. Should I use \input and \chapter commands? I'm not using all the puzzles in one file and I don't want to write each puzzle as one TEX file. What is the best way to do this?
Thanks!!

A: I made a package just for purposes like this. It's called exercisebank.
Say you have your 2017.tex, and in there you should have puzzles and solutions in the following format.
%% 2017.tex
%% Heads up! \end{solution} and \end{problem} can't have spaces in front of it and needs it's own line
\begin{problem}
  Puzzle 1 here
\end{problem}
\begin{solution}
  Solution 1 here
\end{solution}

\begin{problem}
  Puzzle 2 here
\end{problem}
\begin{solution}
  Solution 2 here
\end{solution}

Now you can do
\documentclass{article}
\usepackage{exercisebank}
% You might want no part problem headers (only Problem 1, Problem 2 etc), in that case: uncomment the line below:
% \exercisebanksetup{part problems=Off}
% To make a setup, you do this; \makeset{setupName}{puzzle-file}
% So to make a setup with all of the exercises from 2017:
\makeset{allof2017}{2017}
% Or you can cherry pick your favorites
\makeset{2017Favorites}{\select{2017}{1,2}}
\begin{document}
  % Then choose which to build
  \buildset{2017Favorites}
\end{document}

If you end up using this, please feel free to request features or report bugs here

Edit: I've now come across some other packages that do similar things. So I should also mention that e.g. xsim might also do what you want, and is probably more stable at this time. Furthermore, you could check out the  exercise and exam topics on CTAN.


text:
Q: OPC DA client ItemMgt Incorrect function error I have created a simple OPC DA client for the C++ COM API in Qt5.
The client connects to the remote server, gets an OPCServer pointer, creates a new OPC group with an ItemMgt interface, and fails when I try to add items to the group.
The error message is: Incorrect function.
As far as I can see, the IUnknown:: QueryInterface works for this pItemMgt, but the ValidateItems, CreateEnumerator and AddItems calls results in the same Incorrect function error. The OPC server is a QMS220Simulator (Quadera).
Any idea what could be the problem?
This is my first attempt to write a DCOM client, so many, many thing could be wrong with this code.
The qms220.h file contains the CLSID for the QMS220Simulator.
The shortest code to reproduce the problem is this:
#include "opcda.h"
#include "qms220.h"

#include <QApplication>
#include <QDebug>
#include <comdef.h>

static void showStatus(const QString &message,HRESULT code);

IOPCServer *pOPCServer = nullptr;
IOPCItemMgt *pItemMgt = nullptr;
OPCHANDLE serverGroupHandle;

bool initializeCOM()

{
    HRESULT hr = CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);
    if (FAILED(hr)) {
        showStatus("COM initialization failed!",hr);
        return false;
    }

    hr = CoInitializeSecurity(
                NULL, //security descriptor
                -1, //COM authentication
                NULL, //authentication services
                NULL, //reserved
                RPC_C_AUTHN_LEVEL_DEFAULT, //default authentication
                RPC_C_IMP_LEVEL_IMPERSONATE, //default impersonation
                NULL, //authentication info
                EOAC_NONE, //additional capabilities
                NULL //reserved
                );

    if (hr == RPC_E_TOO_LATE) {
        showStatus("RPC initalization is too late, ignoring...",hr);
    } else {
        if (FAILED(hr)) {
            showStatus("CoInitializeSecurity",hr);
            return false;
        }
    }

    return true;
}

void deinitializeCOM()
{
    CoUninitialize();
}

static const int INTERFACE_COUNT = 1;

bool connectToServer(const QString &address)
{
    _bstr_t serverName = address.toStdString().c_str();
    COSERVERINFO cs;
    memset(&cs,0,sizeof(cs));
    cs.pwszName = serverName;
    MULTI_QI qi[INTERFACE_COUNT];
    memset(qi,0,sizeof(qi));

    qi[0].pIID = &IID_IOPCServer;

    HRESULT hr = CoCreateInstanceEx(
                CLSID_QMG220SIMDA,
                NULL,
                CLSCTX_SERVER,
                &cs,
                INTERFACE_COUNT,
                qi
                );

    if (FAILED(hr)) {
        showStatus("CoCreateInstanceEx",hr);
        return false;
    }

    pOPCServer = (IOPCServer*)(qi[0].pItf);

    return true;
}

void disconnectFromServer()
{
    if (pOPCServer != nullptr) {
        pOPCServer->Release();
        pOPCServer = nullptr;
    }
}
void showOPCStatus(const QString &message,HRESULT hr)
{
    if (pOPCServer != nullptr) {
        LPWSTR buffer = nullptr;
        HRESULT hr2 = pOPCServer->GetErrorString(hr,LOCALE_SYSTEM_DEFAULT,&buffer);
        if (hr2 != S_OK) {
            qDebug() << message << QString(": HRESULT: 0x%1").arg(hr,8,16,QChar('0'));
        } else {
            qDebug() << message << QString(": ") << QString::fromWCharArray(buffer);
            CoTaskMemFree(buffer);
        }
    } else {
       qDebug() << message << QString(": HRESULT: 0x%1").arg(hr,8,16,QChar('0'));
    }
}

static const LPCWSTR MIDGROUPNAME = L"mid";

bool createMIDGroup()
{
    if (pOPCServer == nullptr) return false;

    OPCHANDLE clientGroupHandle = 1;
    DWORD revisedUpdateRate;

    HRESULT hr = pOPCServer->AddGroup(
                MIDGROUPNAME,
                FALSE, //active
                0, // requestedUpdateRate
                clientGroupHandle,
                NULL, //timebias
                NULL, //percentDeadBand,
                LOCALE_SYSTEM_DEFAULT, //lcid
                &serverGroupHandle,
                &revisedUpdateRate,
                IID_IOPCItemMgt,
                (LPUNKNOWN *)(&pItemMgt)
                );
    showOPCStatus("OPCServer::AddGroup",hr);
    if (hr != S_OK) return false;

    qDebug() << "The server group handle is: " << QString("0x%1").arg(serverGroupHandle,4,16);
    qDebug() << "The revised update rate is: " << revisedUpdateRate;

    #define ITEM_ID L"Hardware.Modules.Analyser.SI220.SimulationMode"
    QString accessPath("");
    QString itemId("Hardware.Modules.Analyser.SI220.SimulationMode");
    wchar_t accessPathBuffer[1024];
    wchar_t itemIdBuffer[1024];
    accessPath.toWCharArray(accessPathBuffer);
    itemId.toWCharArray(itemIdBuffer);
    static const int ITEM_COUNT = 1;

    OPCITEMDEF ItemArray[ITEM_COUNT] =
        {{
        /*szAccessPath*/ accessPathBuffer,
        /*szItemID*/ itemIdBuffer,
        /*bActive*/ FALSE,
        /*hClient*/ 1,
        /*dwBlobSize*/ 0,
        /*pBlob*/ NULL,
        /*vtRequestedDataType*/ VT_UI1,
        /*wReserved*/0
        }};

    OPCITEMRESULT *itemResults = nullptr;
    HRESULT *errors = nullptr;

    hr = pItemMgt->AddItems(ITEM_COUNT,ItemArray,&itemResults,&errors);

    bool failed = false;
    if (hr != S_OK) {
        failed = true;
    }

    showOPCStatus("createMidGroup/AddItems ",hr);

    for(DWORD k=0;k<ITEM_COUNT;k++) {
        showOPCStatus(QString("createMidGroup/AddItems[%1]").arg(k),errors[k]);
        if (errors[k] != S_OK) {
            failed = true;
        }
        CoTaskMemFree(itemResults[k].pBlob);
    }

    CoTaskMemFree(itemResults);
    CoTaskMemFree(errors);

    return !failed;
}

void removeMIDGroup()
{
    if (pOPCServer != nullptr) {
        if (pItemMgt != nullptr) {
            pItemMgt->Release();
            pItemMgt = nullptr;
        }

        HRESULT hr = pOPCServer->RemoveGroup(serverGroupHandle,false);
        if (hr != S_OK) {
            showStatus("deleteMIDGroup",hr);
        }
    }
}

int main(int argc, char *argv[])
{
    Q_UNUSED(argc)
    Q_UNUSED(argv)

    if (!initializeCOM()) return -1;
    if (connectToServer(QString("192.168.12.106"))) {
        if (createMIDGroup()) {
            removeMIDGroup();
        }

        disconnectFromServer();
    }

    deinitializeCOM();

    return 0;
}

static void showStatus(const QString &message,HRESULT code)
{
    _com_error error(code);

    qDebug() << message + QString(": " ) +  QString::fromWCharArray(error.ErrorMessage());
}

A: So, according to the Qt documentation: https://doc.qt.io/qt-5/qstring.html#toWCharArray
The toWCharArray creates a NOT NULL CHAR TERMINATED unicode string.
So a bit better usage would be:
int size =  itemId.toWCharArray(itemIdBuffer);
itemIdBuffer[size] = L'\0';
And the same for accessPathBuffer.
Probably it's not a really good idea to send an unterminated group name to the OPC server.
The good thing is, that the CreateGroupEnumerator sends back the same unterminated group names as received.
So the problem is not COM nor OPC related, it's just not reading the fine documentation.


text:
Q: issue with centering div that's right aligned to parent in react native I'm having such a hard time transferring something I wrote in HTML/CSS into React Native. The basic idea is that I'm trying to align some divs to the right of a parent div that's as small as possible. Then, I'm trying to center that parent div on the page.
The html looks like:

<!DOCTYPE html>

test name

Yes

long long long name

No

short

No

But when I transfer this into React Native code, it doesn't look the same! The pink container is no longer centered, and you cannot view the gray outer div (copy paste this into Snack to see what I mean):
import * as React from 'react';
import { Text, View } from 'react-native';

let Test = () => (
    <View style={styles_alt.outer}>
      <View style={styles_alt.container}>
        <View style={styles_alt.row}>
          <View style={{...styles_alt.column, ...styles_alt.left}}>
            <Text>test name</Text>
          </View>
          <View style={{...styles_alt.column, ...styles_alt.right}}>
            <Text>Yes</Text>
          </View>
        </View>

        <View style={styles_alt.row}>
          <View style={{...styles_alt.column, ...styles_alt.left}}>
            <Text>long long long name</Text>
          </View>
          <View style={{...styles_alt.column, ...styles_alt.right}}>
            <Text>No</Text>
          </View>
        </View>

        <View style={styles_alt.row}>
          <View style={{...styles_alt.column, ...styles_alt.left}}>
            <Text>name</Text>
          </View>
          <View style={{...styles_alt.column, ...styles_alt.right}}>
            <Text>Yes</Text>
          </View>
        </View>

      </View>
    </View>
  );

const styles_alt = {
  outer: {
    backgroundColor: "gray",
    display: "flex",
    justifyContent: "center"
  },

  container: {
    backgroundColor: "pink",
    display: "flex",
    flexDirection: "column",
  },

  column: {
    flexDirection: "column",
    backgroundColor: "purple",
    padding: "5%",

  },

  row: {
    display: "flex",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "flex-end",

  },

  p: {
    alignSelf: "flex-start",
  },

  h3: {
    alignSelf: "flex-start",
  },

  right: {
    color: "red",
    minWidth: "20%",
  }
}

export default function App() {
  return (
    <View style={{marginTop: "30%"}}>
        <Test/ >
    </View>
  );
}

If anyone is willing to help me out I'd appreciate it a ton!

A: Currently working on a codeSandBox and jsfiddle
This biggest issue I see is applying View Styles to Text Components. For example:
    <View style={{...styles_alt.column, ...styles_alt.right}}>
            <Text>No</Text>
    </View>

should be:
    <View style={styles_alt.column}>
            <Text style={styles_alt.right}>No</Text>
    </View>

You have mismatched html elements as well:

short

long long long name

Also, please keep in mind that html elements such as h2 have default stylings that need to be added manually to your react native styling.


text:
Q: Padding issue? (C / GCC) I'm attempting to unify an ARM project's (specifically, the i.MX27 CPU running Linux 2.6.33.3, being compiled with GCC 4.3.2) approach to its SQLite interactions. As part of that, I've created a structure with a union that gets used to hold values to be bound to prepared statements.
#define SQLITE_DATA_CHARACTER_STRING_MAX 1024

typedef struct
{
    int data_type;
    union
    {
        int integer;
        double floating_point;
        unsigned char character_string[SQLITE_DATA_CHARACTER_STRING_MAX];
    };
}sqlite_data;

Originally, this was int, float, char. I wanted to use long long, double, and char. However, that seems to cause a problem. As typed above, the following code produces predictable output:
int data_fields = 15;
int data_fields_index = 0;
sqlite_data data[data_fields];

LogMsg(LOG_INFO, "%s: Assigning", __FUNCTION__);

for(data_fields_index = 0; data_fields_index < data_fields; data_fields_index++)
{
    data[data_fields_index].data_type = (100 + data_fields_index);
    data[data_fields_index].integer = (1000 + data_fields_index);
    LogMsg(LOG_INFO, "%s: data[%d] - %d; type - %d", __FUNCTION__, data_fields_index, data[data_fields_index].integer, data[data_fields_index].data_type);
}

The output of which is this:
 Assigning
 data[0] - 1000; type - 100
 data[1] - 1001; type - 101
 data[2] - 1002; type - 102
 data[3] - 1003; type - 103
 data[4] - 1004; type - 104
 data[5] - 1005; type - 105
 data[6] - 1006; type - 106
 data[7] - 1007; type - 107
 data[8] - 1008; type - 108
 data[9] - 1009; type - 109
 data[10] - 1010; type - 110
 data[11] - 1011; type - 111
 data[12] - 1012; type - 112
 data[13] - 1013; type - 113
 data[14] - 1014; type - 114

However, if I make only one change (giving integer the type long long) it all falls apart. So, the following change:
typedef struct
{
    int data_type;
    union
    {
        long long integer;
        double floating_point;
        unsigned char character_string[SQLITE_DATA_CHARACTER_STRING_MAX];
    };
}sqlite_data;

Produces this ouput:
Assigning
data[0] - 1000; type - 0
data[1] - 1001; type - 0
data[2] - 1002; type - 0
data[3] - 1003; type - 0
data[4] - 1004; type - 0
data[5] - 1005; type - 0
data[6] - 1006; type - 0
data[7] - 1007; type - 0
data[8] - 1008; type - 0
data[9] - 1009; type - 0
data[10] - 1010; type - 0
data[11] - 1011; type - 0
data[12] - 1012; type - 0
data[13] - 1013; type - 0
data[14] - 1014; type - 0

I've tried deunionizing them, using #pragma pack(6), and putting that array on the heap, all with identical results: int works, long long doesn't.
What's going on here?

A: You're not telling printf() to expect a long long. Use %lld in your format string instead of %d.

A: Sneftel is absolutely correct. The problem is that you are not specifying long long which results in undefined behavior. To help you visualize picture the following:
"%s: data[%d] - %d; type - %d"

%s - [✓] __FUNCTION__ is a valid string.
%d - [✓] data_fields_index is an int
%d - [x] data[data_fields_index].integer is a long long, this will only read
          the first 4 bytes of an 8 byte integer.
%d - [x] this is likely reading the last 4 bytes of
          data[data_fields_index].integer which will be 0 for smaller numbers
          on a little endian architecture.

So as a long long 1000 will be stored in memory in little endian as:
[0x00 0x20 0x00 0x00 0x00 0x00 0x00 0x00]
  ^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^
      first %d          second %d

Changing the format to "%s: data[%d] - %lld; type - %d" will fix this.


text:
Q: Change background colour of knitr::kable headers I need to change the background colour of the headers of a table printed with knitr::kable. I can use kableExtra::column_spec to change the background of a whole column, but it doesn't affect the header row:
library(knitr)
library(kableExtra)

kable(data.frame(a = 1, b = 2)) %>%
  column_spec(1, background = "yellow")

Wanted outcome:
A kable output where the header of column a has a yellow background (and the rest of the table a white background).

A: You can do this using cell_spec.  For example,
df <- data.frame(a = 1, b = 2)
names(df)[1] <- cell_spec(names(df)[1], background = "yellow")
kable(df, escape = FALSE)

This doesn't display automatically in RStudio for me; you need to pipe it through a kableExtra function to do that.  For example, this pipe does nothing except to mark the table to display.
kable(df, escape = FALSE) %>% column_spec(1)

will display

Another way to do it is to set the whole column including the header to yellow, then set the non-header part to the inherited colour.  You do that like this:
kable(df) %>%
  column_spec(1, background = "yellow", include_thead = TRUE) %>%
  column_spec(1, background = "inherit")

This one ends up with messy HTML, but the spacing looks a bit better:

A: kable(data.frame(a = 1, b = 2)) %>%
  row_spec(0, background = "yellow")


text:
Q: facebook logout API - Why Next? I'm writing a Windows Phone 7 app and have gotten Facebook login working using the C# sdk, but logging out has proven interesting.  I've read this post:
Cannot Logout of Facebook with Facebook C# SDK
which seems to mirror the FB docs which indicate I should navigate to
https://www.facebook.com/logout.php?next=[redirect_uri]&access_token=[token]
However, that doesn't work and silently redirects me back to the facebook home page.
My best guess at the moment is facebook doesn't like the "next" URI I'm providing.  I updated my FB app settings but either they haven't propagated yet, or something else is still not working.
I've seen posts recommending using InternetSetOption, but that API is not available on the phone.
In my application flow, logout leads to navigating to a different silverlight page in my app, so I really don't need the browser redirect for my purpose anyway, so I could just "forget" the access token without actually telling FB to invalidate it, but that seems weak and insecure.
So, while I wait longer to see if the app domain changes propagate across FB's servers and solve the problem I have a different question:
Why should the Facebook APIs care whether I provide "next" or not?  Shouldn't I just be able to tell them to invalidate a token and have it happen?
Is there a logic piece I'm missing here?
Thanks!

A: Update: I wrote an open-source Facebook login/logout control for WP7 that allows this (check the example project).  It works by essentially using the web browser control to navigate to the logout page and then submit the logout form by injecting javascript into the web browser control.  The idea came from this blog post.
The closest thing would be to revoke the extended permissions by issuing an HTTP DELETE to /me/permissions as documented here.  Simply forgetting the auth token isn't a bad option either as the access tokens are generally only good for an hour or two unless you asked for offline_access.  And if a user is overly concerned, they can remove your application on their settings page on facebook.com.


text:
Q: Picasso errors on callback I've noticed that occasionally images won't load in my app through picasso and that picasso is in fact erring. I am using two images per list item in a list view. Here's the picasso code:
Picasso.with(DashboardActivity.this).load(status).into(iv_customer_status_pic, new Callback() {
              @Override public void onSuccess() {
                  Log.d("Debug", "Picasso Success");
              }

              @Override public void onError() {
                  Log.d("Debug", "Picasso Errored");
              }
            });

How can I ensure that the images are loaded, I don't want them to error and then make them disappear. Also why does it error? Is there a timeout? I noticed on more powerful devices it happens less.

A: The reason the onError() callback for Picasso.with().load().into(target, callback) exists is because there is no 100% guarantee the load will be successful.  For example if you are trying to load from a uri and you don't have an internet connection, the load will not be successful.
You can somehow attempt a re-try (which I think is already built into Picasso), but ultimately, you need to handle the case were the load fails (for whatever reason). One option would be to load a "default" image, like a generic "profile picture" if you were trying to load a specific users profile picture.
If you move the implementation of the callbacks to a separate class , or even the containing class you should be able to retry from the onError() call back.  Here is what I am thinking:
class ContainingClass implements Callback.EmptyCallback

private int mRetryAttempts = 0;

@Override
public void onError() {
    if (mRetryAttempts < 2) {
        mRetryAttempts++;
        // try again
    } else {
        mRetryAttempts = 0;
    }
}

@Override
public void onSuccess() {
    mRetryAttempts = 0;
}

A: The reasons why it fails might because of no Internet connection and Invalid Image URL.
With regard to the error handling refer to nPn's answer.


text:
Q: Evaluate a switch statement only once in C# I've been working with a switch statement and it works fine. However, I want the case to be evaluated only once and if it comes again don't evaluate. Here's the code I tried, which works:
private static int total = 0;
private static string[] ErrorCode = new string[] { "@", "-2", "!" };

private static int Score(string[] errorCodes)
{
    var sum = 0;
    foreach (var ec in errorCodes)
    {
        switch (ec)
            {
                case "@":
                    sum += 1;
                    break;
                case "-2":
                    sum += -2;
                    break;
                case "!":
                    sum += 5;
                    break;
            }
    }
    return sum; //This returns 4
 }

But, if the string[] array has a repeated value it adds the value, which evaluates again. Like this:
private static string[] ErrorCode = new string[] { "@", "-2", "!", "!" };
//This returns 9 (Because of "!") but would like to return 4

How can I achieve to evaluate "!" only once, or should I take a different approach? Thanks for the help!

A: Use Linq's Distinct extension method to let the foreach loop enumerate over the distinct values in your errorCodes collection/array:
using System.Linq;

...

foreach (var ec in errorCodes.Distinct())
{
    ...
}

(Don't forget to import the System.Linq namespace.)

A: Using .Distinct() is probably the simplest change given the code that you already have.
Alternatively, here is a slightly more succinct solution just using LINQ and a lookup Dictionary:
private static readonly Dictionary<string, int> _errorCodeScores = new Dictionary<string, int>
{
    { "@", 1 },
    { "-2", -2 },
    { "!", 5 },
};

private static int Score(string[] errorCodes)
{
    return _errorCodeScores
        .Where(s => errorCodes.Any(c => s.Key == c))
        .Sum(s => s.Value);
}