text:
Q: Circle follow cursor after hover on button I'm trying to remake hover like on this website:
https://www.samsaraubud.com/
When you hover over a button (and only button. I don't want circle over whole website), a circle appers around cursor. I tried so many solutions from codepen after typing "mouse follow" but nothing works.
I have button like this:
https://codepen.io/Aventadorrre/pen/mdyPJbv

body {
  padding: 100px;
  margin: auto;
}

a {
  color: red;
  border: 2px solid red;
  padding: 20px 50px;
}
Button

and how to make circle around mouse (following mouse) when i hover button?

A: Consider a radial-gradient as background that you make fixed then simply adjust the position based on the cursor

var h =document.querySelector('.cursor');

document.body.onmousemove = function(e) {
  /* 15 = background-size/2 */
  h.style.setProperty('background-position',(e.clientX - 15)+'px '+(e.clientY - 15)+'px');
}
body {
  padding: 100px 0;
}

a.cursor {
  color: red;
  border: 2px solid red;
  padding: 20px 50px;
  background:
    radial-gradient(farthest-side,
     transparent calc(100% - 3px),
     red calc(100% - 2px) calc(100% - 1px),
     transparent 100%)
     fixed /* Fixed to the screen*/
     no-repeat; /* Don't repeat*/

  background-size:30px 30px; /* Control the size of the circle */

}
Button

If you want the circle above the text consider pseudo element and the same trick:

var h =document.querySelector('.cursor');

document.body.onmousemove = function(e) {
  h.style.setProperty('background-position',(e.clientX - 15)+'px '+(e.clientY - 15)+'px');
}
body {
  padding: 100px 0;
}

a.cursor {
  color: red;
  border: 2px solid red;
  padding: 20px 50px;
  background-size:0 0;
  position:relative;
}
a.cursor::after {
  content:"";
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:
    radial-gradient(farthest-side,
     blue  calc(100% - 1px),
     transparent 100%)
     fixed /* Fixed to the screen*/
     no-repeat; /* Don't repeat*/
  background-size:30px 30px;
  background-position:inherit;
}
Button

A: Updated
It shows full circle even on the boundaries of the button

const btn = document.querySelector(".button")
const circle = document.querySelector(".circle")

btn.onmouseenter = function() {
  circle.classList.add("in")
}

btn.onmousemove = function(e) {
  const {
    top,
    left,
    width,
    height
  } = btn.getBoundingClientRect()
  const {
    clientY,
    clientX
  } = e
  if (clientX < left || clientY < top || clientX > left + width || clientY > top + height) {
    circle.classList.remove("in")
  }
  circle.style.top = `${clientY - top}px`
  circle.style.left = `${clientX - left}px`
};
body {
  margin: 20px;
  padding: 20px;
}

.button {
  padding: 40px 80px;
  border: 1px solid grey;
  color: blue;
  display: inline-block;
  position: relative;
}

.circle {
  position: absolute;
  display: none;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  top: 0;
  left: 0;
  transform: translate(-50%, -50%);
  border: 2px solid red;
}

.circle.in {
  display: block;
}

  Button

old answer
The answer is extension of the answer by @Temani Afif.
The listener for mousemove is added on the button itself instead of the body, which would result in performance improvement since the cb is only called when you are hovering over the button.

var h = document.querySelector(".cursor");

h.onmousemove = function(e) {
  /* 15 = background-size/2 */
  h.style.setProperty(
    "background-position",
    e.clientX - 15 + "px " + (e.clientY - 15) + "px"
  );
};
body {
  padding: 100px 0;
}

a.cursor {
  color: red;
  border: 2px solid red;
  padding: 20px 50px;
  background: radial-gradient( farthest-side, transparent calc(100% - 3px), red calc(100% - 2px) calc(100% - 1px), transparent 100%) fixed/* Fixed to the screen*/
  no-repeat;
  /* Don't repeat*/
  background-size: 0px 0px;
  /* by default, circle is of 0px */
}

a.cursor:hover {
  background-size: 30px 30px;
  /* Control the size of the circle */
}
Button

A: You can do that with mousemove event. Catch the event and set the location of cirlce while the mouse moves.

window.addEventListener('mousemove', function(e){
  document.getElementById("circle").style.display = "block";
  document.getElementById("circle").style.left = e.offsetX + "px";
  document.getElementById("circle").style.top = e.offsetY + "px";
});
body {
  padding: 100px;
  margin: auto;
}

a {
  color: red;
  border: 2px solid red;
  padding: 20px 50px;
}

#circle{
  width: 30px;
  height: 30px;
  border: 1px solid red;
  border-radius: 50%;
  position: fixed;
  display: none;
}
Button


text:
Q: HBase scanner exception: Failed to load SIMPLE, KERBEROS, and DIGEST authentication providers Meet an exception while trying to get the next row in the scanner(HBase ResultScanner), below is the part of the code, the exception occurs at "val results = scanner.next(numRows)"
val scan = new Scan(rowStart, rowEnd)
val cFamily: String = "c"
scan.addFamily(cFamily.getBytes)
scan.setCaching(numRows)
val table = hbaseConn.getTable(hbaseTableName.getTableName(baseTableName))
val scanner = table.getScanner(scan)
var done: Boolean = false
var rowProcessed: Long = 0
val results = scanner.next(numRows)

The Exception is as below
[hconnection-0x16f9965f-metaLookup-shared--pool4-t1] o.a.h.h.c.RpcRetryingCallerImpl [RpcRetryingCallerImpl.java:132] Call exception, tries=6, retries=36, started=4611 ms ago, cancelled=false, msg=Call to hbase_cluster_hostname/ip_address:16020 failed on local exception: java.io.IOException: java.lang.IllegalStateException: Failed to load SIMPLE, KERBEROS, and DIGEST authentication providers. Classpath is not sane., details=row 'My_table_name,�(�5:�^]^?,99999999999999' on table 'hbase:meta' at region=hbase:meta,,1.1588230740, hostname=hbase_cluster_hostname,16020,1626108747058, seqNum=-1, see https://s.apache.org/timeout, exception=java.io.IOException: Call to hbase_cluster_hostname/ip_address:16020 failed on local exception: java.io.IOException: java.lang.IllegalStateException: Failed to load SIMPLE, KERBEROS, and DIGEST authentication providers. Classpath is not sane.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.apache.hadoop.hbase.ipc.IPCUtil.wrapException(IPCUtil.java:225)
    at org.apache.hadoop.hbase.ipc.AbstractRpcClient.onCallFinished(AbstractRpcClient.java:383)
    at org.apache.hadoop.hbase.ipc.AbstractRpcClient.access$100(AbstractRpcClient.java:91)
    at org.apache.hadoop.hbase.ipc.AbstractRpcClient$3.run(AbstractRpcClient.java:414)
    at org.apache.hadoop.hbase.ipc.AbstractRpcClient$3.run(AbstractRpcClient.java:410)
    at org.apache.hadoop.hbase.ipc.Call.callComplete(Call.java:117)
    at org.apache.hadoop.hbase.ipc.Call.setException(Call.java:132)
    at org.apache.hadoop.hbase.ipc.AbstractRpcClient.callMethod(AbstractRpcClient.java:427)
    at org.apache.hadoop.hbase.ipc.AbstractRpcClient.callBlockingMethod(AbstractRpcClient.java:325)
    at org.apache.hadoop.hbase.ipc.AbstractRpcClient.access$200(AbstractRpcClient.java:91

I meet this issue after I updated my HBase client version to 2.2.3, Not sure what does this exception means and how to fix it. Has anyone met a similar issue before? Please advise, thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Autocorrelation plot for only negative values I would like to do an acf plot in R for only the negative values of a time series. I cannot do this by just subsetting the data for only negative values beforehand, because then the autocorrelation will remove arbitrary number of positive days in between the negative values and be unreasonably high, but rather, I would like to run the autocorrelation on the whole time series and then filter out the results given the first day is negative.
For example, in theory, I could make a data frame with the original series and all of the lagged time series in a data frame, then filter for the negative values in the original series, and then plot the correlations. However, I would like to automate this using the acf plot.
Here is an example of my time series:
> dput(exampleSeries)
c(0, 0, -0.000687, -0.004489, -0.005688, 0.000801, 0.005601,
0.004546, 0.003451, -0.000836, -0.002796, 0.005581, -0.003247,
-0.002416, 0.00122, 0.005337, -0.000195, -0.004255, -0.003097,
0.000751, -0.002037, 0.00837, -0.003965, -0.001786, 0.008497,
0.000693, 0.000824, 0.005681, 0.002274, 0.000773, 0.001141, 0.000652,
0.001559, -0.006201, 0.000479, -0.002041, 0.002757, -0.000736,
-2.1e-05, 0.000904, -0.000319, -0.000227, -0.006589, 0.000998,
0.00171, 0.000271, -0.004121, -0.002788, -9e-04, 0.001639, 0.004245,
-0.00267, -0.004738, 0.001192, 0.002175, 0.004666, 0.006005,
0.001218, -0.003188, -0.004363, 0.000462, -0.002241, -0.004806,
0.000463, 0.000795, -0.005715, 0.004635, -0.004286, -0.008908,
-0.001044, -0.000842, -0.00445, -0.006094, -0.001846, 0.005013,
-0.006599, 0.001914, 0.00221, 6.2e-05, -0.001391, 0.004369, -0.005739,
-0.003467, -0.002103, -0.000882, 0.001483, 0.003074, 0.00165,
-0.00035, -0.000573, -0.00316, -0.00102, -0.00144, 0.003421,
0.005436, 0.001994, 0.00619, 0.005319, 7.3e-05, 0.004513)

A: I tried to implement your description.
correl <- function(x, lag.max = 10){
  library(dplyr)
  m <- matrix(ncol = lag.max, nrow = length(x))
  for(i in 1:lag.max){
    m[,i] <- lag(x, i)
    }
  m <- m[x<0,]
  res <- apply(m, 2, function(y) cor(y, x[x<0], use = "complete.obs"))
  barplot(res)
}

correl(exampleSeries)

A: Maybe just write your own function?  Something like:
negativeACF <- function(x, num.lags = 10)
{
  n    <- length(x)
  acfs <- sapply(0:num.lags, function(i) cor(x[-i:-1], x[(-n-1+i):-n]))
  names(acfs) <- 0:num.lags
  acfs[acfs < 0]
}

results <- negativeACF(exampleSeries, num.lags=20)
barplot(results)

A: Yea I ended up writing my own functions and just replacing the values in the R acf object with my own values that are just the correlations. So:
genACF <- function(series, my.acf, lag.max = NULL, neg){

    x <- na.fail(as.ts(series))
    x.freq <- frequency(x)
    x <- as.matrix(x)
    if (!is.numeric(x))
        stop("'x' must be numeric")
    sampleT <- as.integer(nrow(x))
    nser <- as.integer(ncol(x))

    if (is.null(lag.max))
        lag.max <- floor(10 * (log10(sampleT) - log10(nser)))
    lag.max <- as.integer(min(lag.max, sampleT - 1L))
    if (is.na(lag.max) || lag.max < 0)
        stop("'lag.max' must be at least 0")

    if(neg){

        indices <- which(series < 0)

    }else{

        indices <- which(series > 0)

    }

    series <- scale(series, scale = FALSE)
    series.zoo <- zoo(series)
    for(i in 0:lag.max){

        lag.series <- lag(series.zoo, k = -i, na.pad = TRUE)
        temp.corr <- cor(series.zoo[indices], lag.series[indices], use = 'complete.obs', method = 'pearson')
        my.acf[i+1] <- temp.corr

    }
    my.acf[1] <- 0
    return(my.acf)

}

plotMyACF <- function(series, main, type = 'correlation', neg = TRUE){

    series.acf <- acf(series, plot = FALSE)
    my.acf <- genACF(series, series.acf$acf, neg = neg)
    series.acf$acf <- my.acf

    plot(series.acf, xlim = c(1, dim(series.acf$acf)[1] - (type == 'correlation')), xaxt = "n", main = main)
    if (dim(series.acf$acf)[1] < 25){

        axis(1, at = 1:(dim(series.acf$acf)[1] - 1))

    }else{

        axis(1)

    }

}

And I get something like this:


text:
Q: WPF: How do I set different default null values in a DataGrid if a new row is added? I have a DataGrid which is bound to a DataTable that is filled by an SqlDataAdapter, which fills it with an unspecified table, and I therefore have no way of knowing how the structure in the table is. I've set the TargetNullValue to NULL, and the cells that contains a null-value from the database shows NULL in the DataGrid, which is perfect.
However... when I want to add a new row using DataGrid's CanUserAddRow, the default values are all "NULL", and I want them to be empty.
I am able to change cells that expect the type of string to show up empty, but in the cells that expect int's for example, it can't contain an empty string, or an int that is NULL. If I want it to be NULL, it has to be DBNull instead, which gives me "NULL" in the cell, which doesn't make any difference.
Any one with an idea how to overcome this issue of mine?
Thanks in advance.
Mainwindow.xaml
<DataGrid x:Name="dataGrid_Table" AutoGenerateColumns="True"
          CanUserAddRows="true"
          AutoGeneratingColumn="dataGrid_Table_AutoGeneratingColumn"
          InitializingNewItem="dataGrid_Table_InitializingNewItem"/>

Mainwindow.xaml.cs
private void dataGrid_Table_AutoGeneratingColumn(object sender,
    DataGridAutoGeneratingColumnEventArgs e)
{
    // Make all columns nullable
    ((DataGridBoundColumn)e.Column).Binding.TargetNullValue = "NULL";
}
private void dataGrid_Table_InitializingNewItem(object sender,
    InitializingNewItemEventArgs e)
{
    DataRowView drv = (DataRowView)e.NewItem;
    for (int i = 0; i < drv.Row.ItemArray.Count(); i++)
    {
        DataColumn col = drv.Row.Table.Columns[i];
        if (col.DataType.ToString() == "System.String")
        {
            drv.Row[i] = "";
        }
        else if (col.DataType.ToString() == "System.Int32")
        {
            // Set cells that expect an int to show up empty
        }
    }
}

Method for filling the DataTable and binding it to the DataGrid
internal void FillDataGrid(User user, MainWindow mainWindow)
{
    dt = new DataTable();
    using (SqlConnection con = new SqlConnection(ConnectionString))
    {
        con.Open();
        using (SqlCommand cmd =
            new SqlCommand("SELECT * FROM " + Name, con))
        {
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            sda.Fill(dt);
            mainWindow.dataGrid_Table.ItemsSource = dt.DefaultView;
        }
    }
}

A: I have a similar setup, where a SqlDataAdapter was populating a DataGrid. I needed Boolean fields to be shown on the DataGrid, but it seems that the default values are always NULL for every column value in the row. The Boolean NULL value in the UI looks like a checked box, which misrepresents what the value actually is.
I found a solution that looks a little messy but it get the job done.
You want to add the LoadingRow option to the DataGrid XAML
<DataGrid ... LoadingRow="myDataGrid_LoadingRow"/>

This will appear sometime during the creation of the row.  Whether or not this is a new line. So if you have a DataGrid with 100 rows, it will call this function 100 times as each row is loaded. So I did a few things here:
(1) Made sure that the e.Row.Item is a DataRowView Object to avoid an error throw.
(2) Checking to see if the row is being created by using .IsNew, avoiding all rows from the original list of rows.
(3) As you cast the object as System.Data.DataRowView you will be able to pull up the future values of that row. I have static columns, so that 11 and 10 are my columns. I need to set the values for the new rows to false, but you could enter any values you want (if you want them to be empty use "").
private void myDataGrid_LoadingRow(object sender,
    System.Windows.Controls.DataGridRowEventArgs e)
{
    if (e.Row.Item is System.Data.DataRowView)
    {
        if (((System.Data.DataRowView)e.Row.Item).IsNew)
        {
            ((System.Data.DataRowView)e.Row.Item)[11] = false;
            ((System.Data.DataRowView)e.Row.Item)[10] = false;
        }
    }
}

I also tried to use LoadingRow but I couldn't work it out correctly.


text:
Q: YouTube Autosuggest API - where to find samples or documentation? I want to create a YouTube video search box with the same autocomplete feature.
Any idea where can I find samples or and documentation?
Thanks

A: You can get the JSON of the autocomplete searching for the word "obama" using the following HTTP GET query:
http://suggestqueries.google.com/complete/search?hl=en&client=youtube&hjson=t&ds=yt&jsonp=window.yt.www.suggest.handleResponse&q=obama&cp=3
I've seen this call using the youtube and watching the generated HTTP queries with Firefox Live HTTP Headers extension.
I hope it helps.


text:
Q: Simple API gateway with Mock response defined in SAM? I have a simple API gateway definition in AWS.
It has a single Method for "/" with a "GET" HTTP type.
I've updated the "Integration Request" to be a "Mock" (return a response purely with API Gateway mappings ...).
There's nothing fancy, all requests will be passed through.
For the response, I've updated the default Integration Response ( response status 200, no regex, model etc. Default mapping).
It has an "application/json" Mapping template, and in here i have just added the static text "hello world" (creative, i know).
Now, the question is, can i define this in a SAM template ?
I can readily find plenty of exmaples to create a lambda function behind this and have it do the response and all sorts of other things.
I can run the SAM cli locally to do "sam deploy" giving the sam template, and have a whole new AWS Stack created in my account, with the API Gateway created, the lambda python or javascript or etc uploaded to s3 and created and linked in to the API (through implicit sam definition, no external oas/swagger looked at yet) and roles etc created.
And it all works beautifully.
But if I want to do the same thing, but simpler - with just API gateway only and a mock integration response (no lambda) - what would the SAM template look like for that ?
As of yet, i am at a loss.
I can see from the serverless model that a lot of the integrations are supported in sam (x-amazon-apigateway-integration response).
I can see what the oas version looks like by using "api-gateway getexport" via the aws cli.
But I can not see a SAM template with implicit API creation that has no lambda linked in, just a simple Mock and static integration response.
Any help appreciated !!

A: SAM is a extension of Cloudformation, so yeah, it is possible, if you create a sam application and add the bellow template.yaml file, and run sam deploy --guided you will create what you need. In this case you will be running a simple cloudformation template that can be deployed with the following command:
aws cloudformation deploy --stack-name mock-api --template-file template.yaml

The main idea of SAM is facilitate the deploy of Serverless aplications, creating a possibility of invoke Lambda functions locally, improve debugging and so on, while provisioning your resources.
As we can see in the AWS documentation:

A serverless application is a combination of Lambda functions, event sources, and other resources that work together to perform tasks. Note that a serverless application is more than just a Lambda function—it can include additional resources such as APIs, databases, and event source mappings

So, if you are not using Lambda and you want provision your resources, you can simply use Cloudformation or another IaC tool as Terraform.
template.yml example (of what you need):
AWSTemplateFormatVersion: '2010-09-09'

Description: AWS API Gateway with a Mock Integration

Resources:

  ApiGatewayRestApi:
    Type: AWS::ApiGateway::RestApi
    Properties:
      ApiKeySourceType: HEADER
      Description: An API Gateway with a Mock Integration
      EndpointConfiguration:
        Types:
          - EDGE
      Name: mock-api

  ApiGatewayResource:
    Type: AWS::ApiGateway::Resource
    Properties:
      ParentId: !GetAtt ApiGatewayRestApi.RootResourceId
      PathPart: 'mock'
      RestApiId: !Ref ApiGatewayRestApi

  ApiGatewayMethod:
    Type: AWS::ApiGateway::Method
    Properties:
      ApiKeyRequired: false
      AuthorizationType: NONE
      HttpMethod: POST
      Integration:
        ConnectionType: INTERNET
        IntegrationResponses:
          - ResponseTemplates:
              application/json: "{\"message\": \"OK mock response\"}"
            SelectionPattern: '2\d{2}'
            StatusCode: 200
          - ResponseTemplates:
              application/json: "{\"message\": \"Internal Server Error mock response\"}"
            SelectionPattern: '5\d{2}'
            StatusCode: 500
        PassthroughBehavior: WHEN_NO_TEMPLATES
        RequestTemplates:
          application/json: "{\"statusCode\": $input.json('$.statusCode'), \"message\": $input.json('$.message')}"
        Type: MOCK
        TimeoutInMillis: 29000
      MethodResponses:
        - ResponseModels:
            application/json: !Ref ApiGatewayModel
          StatusCode: 200
        - ResponseModels:
            application/json: !Ref ApiGatewayModel
          StatusCode: 500
      OperationName: 'mock'
      ResourceId: !Ref ApiGatewayResource
      RestApiId: !Ref ApiGatewayRestApi

  ApiGatewayModel:
    Type: AWS::ApiGateway::Model
    Properties:
      ContentType: 'application/json'
      RestApiId: !Ref ApiGatewayRestApi
      Schema: {}

  ApiGatewayStage:
    Type: AWS::ApiGateway::Stage
    Properties:
      DeploymentId: !Ref ApiGatewayDeployment
      Description: Mock API Stage v0
      RestApiId: !Ref ApiGatewayRestApi
      StageName: 'v0'

  ApiGatewayDeployment:
    Type: AWS::ApiGateway::Deployment
    DependsOn: ApiGatewayMethod
    Properties:
      Description: Mock API Deployment
      RestApiId: !Ref ApiGatewayRestApi

A: To do this another way with SAM - i have

*

*manually created a simple API gateway with a single GET and a mock response of static text in the integration response.

*exported that with aws apigateway get-export

*remove the servers and policy blocks (those i'll have in my sam template)

*refer to the OAS spec in your SAM template in the API properties with DefinitionBody

*upload the OAS spec

*use SAM deploy

the SAM specifications.
For that approach thanks to valdeci for this answer, and Jens Eickmeyer for this post


text:
Q: How to append tuples returned from function to dataframe in python? I have a dataframe from which I'm using "close" to calculate stoch rsi. The StochRSI() function returns a tuple and I cannot figure out how to correctly append the returned results to the original dataframe.
daily = binance_klines()
daily['open'] = daily['open'].astype(float)
daily['high'] = daily['high'].astype(float)
daily['low'] = daily['low'].astype(float)
daily['close'] = daily['close'].astype(float)
daily['volume'] = daily['volume'].astype(float)

def StochRSI(series, period=14, smoothK=3, smoothD=3):
    # Calculate RSI
    delta = series.diff().dropna()
    ups = delta * 0
    downs = ups.copy()
    ups[delta > 0] = delta[delta > 0]
    downs[delta < 0] = -delta[delta < 0]
    ups[ups.index[period-1]] = np.mean( ups[:period] ) #first value is sum of avg gains
    ups = ups.drop(ups.index[:(period-1)])
    downs[downs.index[period-1]] = np.mean( downs[:period] ) #first value is sum of avg losses
    downs = downs.drop(downs.index[:(period-1)])
    rs = ups.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean() / \
         downs.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean()
    rsi = 100 - 100 / (1 + rs)

    # Calculate StochRSI
    stochrsi  = (rsi - rsi.rolling(period).min()) / (rsi.rolling(period).max() - rsi.rolling(period).min())
    stochrsi_K = stochrsi.rolling(smoothK).mean()
    stochrsi_D = stochrsi_K.rolling(smoothD).mean()

    return stochrsi, stochrsi_K, stochrsi_D

calcs = StochRSI(daily.close, period=14, smoothK=3, smoothD=3)

A: It would be helpful to include an example of what the daily DataFrame looks like, but I am assuming it's a DataFrame with the columns ['open', 'high', 'low', 'close', 'volume', 'adj close'].
If you want new columns for your daily DataFrame, you can create them directly within your function, then return the modified df:
def StochRSI(series, period=14, smoothK=3, smoothD=3):
    # Calculate RSI
    delta = series.diff().dropna()
    ups = delta * 0
    downs = ups.copy()
    ups[delta > 0] = delta[delta > 0]
    downs[delta < 0] = -delta[delta < 0]
    ups[ups.index[period-1]] = np.mean( ups[:period] ) #first value is sum of avg gains
    ups = ups.drop(ups.index[:(period-1)])
    downs[downs.index[period-1]] = np.mean( downs[:period] ) #first value is sum of avg losses
    downs = downs.drop(downs.index[:(period-1)])
    rs = ups.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean() / \
         downs.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean()
    rsi = 100 - 100 / (1 + rs)

    # Calculate StochRSI
    stochrsi  = (rsi - rsi.rolling(period).min()) / (rsi.rolling(period).max() - rsi.rolling(period).min())
    stochrsi_K = stochrsi.rolling(smoothK).mean()
    stochrsi_D = stochrsi_K.rolling(smoothD).mean()

    ## create new columns for your daily df
    daily['stockrsi'] = stochrsi
    daily['stochrsi_K'] = stochrsi_K
    daily['stochrsi_D'] = stochrsi_D

    return daily

daily_new = StochRSI(daily.close, period=14, smoothK=3, smoothD=3)


text:
Q: class exsheets automatic points by question and solution I used the exsheets class for my exercises and exams and everything is very configurable but I have some issues with the dealing of points by questions...
\documentclass{scrartcl}
\usepackage{exsheets}

\begin{document}

\SetupExSheets[question]{print=true}
\SetupExSheets[solution]{print=true}
% Note in my version of exam : questions and solutions are not display in the same file => 2 pdf exam witch questions and corrections

% The solution with grading table is also not automatic...

\begin{question}% I want the total points computed automatically ?

  \begin{enumerate}
    \item \addpoints{1}
    Question 1
    \item \addpoints{2}
    Question 2
  \end{enumerate}
  \currentpointssum*
\end{question}

\begin{solution}% I want the total points computed automatically ?
  \begin{enumerate}
    \item \points{1}
    Question 1
    \item \points{2}
    Question 2
  \end{enumerate}
\end{solution}

\begin{question}

  \begin{enumerate}
    \item \addpoints{3}
    Question II.1
    \item \addpoints{4}
    Quesion II.2
  \end{enumerate}
  \currentpointssum*
\end{question}

\begin{solution}
  \begin{enumerate}
    \item \points{3}
    Question II.1
    \item \points{4}
    Quesion II.2
  \end{enumerate}
  \currentpointssum*
\end{solution}

\end{document}

A solution is that you put manually the total by question but I am sure that there is a solution with automatic compute ?
Thanks you in advance.
Greetings.
Benoit

A: This is actually rather easy with an up to date version of exsheets. The idea is this: define a new container (a box or rather coffin in l3) which holds the points of a question:
\DeclareExSheetsHeadingContainer{autopoints}{%
  \points{\GetQuestionProperty{points}{\CurrentQuestionID}}%
}

\GetQuestionProperty here needs two compilations for fetching the correct value.
Now use the new container (I called it autopoints) instead of the predefined points container in the heading instance in use. For the example below I copied the definition of the block heading as myblock and exchanged points by autopoints:
\DeclareInstance{exsheets-heading}{myblock}{default}{
  join   = { title[r,B]number[l,B](1ex,0pt) } ,
  attach = {
     main[l,vc]title[l,vc](0pt,0pt) ;
     main[r,vc]autopoints[l,vc](\marginparsep,0pt)
   }
}

Now all you have to do is use the new heading:
\SetupExSheets{headings = myblock}

Here is the complete example:
\documentclass{scrartcl}
\usepackage{exsheets}[2015/11/18]% need v0.20

% define a new heading container which fetches the points of a question:
\DeclareExSheetsHeadingContainer{autopoints}{%
  \points{\GetQuestionProperty{points}{\CurrentQuestionID}}%
}

% define a variant of the `block' heading which uses the new container instead
% of the usual one for points:
\DeclareInstance{exsheets-heading}{myblock}{default}{
  join   = { title[r,B]number[l,B](1ex,0pt) } ,
  attach = {
     main[l,vc]title[l,vc](0pt,0pt) ;
     main[r,vc]autopoints[l,vc](\marginparsep,0pt)
   }
}

% setup exsheets to use the new heading:
\SetupExSheets{
  headings = myblock ,
  question/print=true ,
  solution/print=true
}

\begin{document}

\begin{question}
  \begin{enumerate}
    \item \addpoints{1}
    Question 1
    \item \addpoints{2}
    Question 2
  \end{enumerate}
\end{question}

\begin{question}
  \begin{enumerate}
    \item \addpoints{3}
    Question II.1
    \item \addpoints{4}
    Quesion II.2
  \end{enumerate}
\end{question}

\end{document}


text:
Q: How to populate MultiSelect dropdown list (MVC) in Bootstrap I am struggling for populate the MultiSelect Dropdown list by Twitter Bootstrap library in MVC. I am getting the List of data on items in JSON string format. And passing to JSON.parse($('#RetailerSelectItems').val()) but list is not enable in web page. the code as below
Inside report.js
 function BinddetailsEvents() {
    //Populate  Retailer Dropdown
    var MAWBSelectItems = JSON.parse($('#MAWBSelectItems').val()); // MAWBSelectItems List of data
    var MAWBDropDown = $('#MAWBDropDown');

    $(MAWBDropDown).data('allselected', true);
    MultiSelectInit(MAWBDropDown);
    $(MAWBDropDown).multiselect('dataprovider', MAWBSelectItems);
}

Inside report.cshtml
{

          MAWB

          <select id="MAWBDropDown" multiple="multiple" style="display: none" data-allselected="true"></select>

}


text:
Q: MySQL query - Inner join using only the latest version of an entry I have a table, named jobs with various pieces of information.  Each job is given a job number (unique id).
There is then another table, named purchaseOrders that has a FK of jobID and a PK of poID.
when a purchase order entry is edited, the old information is saved... meaning, i create a new PO entry (new unique id).
What i'm trying to do, is write one query that selects all fields from "jobs" and all fields from "purchaseOrders" but only the latest poID for that job.
For example:
jobID      Name      State            poID      time      jobID
==========================            ==========================
1          foo       fl               1         1:00      1
2          bar       ga               2         1:10      1
3          zzz       ny               3         1:20      1
                                      4         2:00      2
                                      5         2:01      2
                                      6         2:30      2
                                      7         3:00      3
                                      8         3:40      3
                                      9         3:15      3

How can I run a query that will select all the columns from both tables, but only include the information with the highest poID for the specific jobID?

A: SELECT  a.*, c.*
FROM    jobs a
        INNER JOIN
        (
            SELECT jobID, MAX(time) maxVal
            FROM purchaseOrders
            GROUP BY jobID
        ) b ON a.jobID = b.jobID
        INNER JOIN purchaseOrders c
            ON c.jobID = b.JobID AND
                c.time = b.maxVal

*

*SQLFiddle Demo


text:
Q: setVisibility does not work While toggling between VISIBLE and GONE works, e.g., for a button, it does not work for CalendarView:
CalendarView myCalendar;
....
myCalendar              = (CalendarView) findViewById(R.id.my_calendar);
....
           @Override
            public void onClick(View v) {
                if (myCalendar.getVisibility()== View.GONE) {
                    myCalendar.setVisibility(View.VISIBLE);
                }
                else
                {   myCalendar.setVisibility(View.GONE);
                }
                leftLayout.invalidate();
            }
        });
How can I hide and show the CalendarView?


text:
Q: How To Scan a Seven Segment Display by Firebase ML kit Text Recognition? The Text Recognition API in Firebase Ml kit is not recognizing the digital numbers or a seven segment display numbers that i am trying to scan out from a weight scale , is there anyway to work it out ?
I tried the Dart package for firebase ml vision for flutter apps , and i used the firebaseVisionImage class and Text Recognizer class and visionText class as shown .
 // get image file
final File imageFile = File(widget.imagePath);

// create vision image from that file
final FirebaseVisionImage visionImage =
    FirebaseVisionImage.fromFile(imageFile);

// create detector index
final TextRecognizer textRecognizer =
    FirebaseVision.instance.textRecognizer();

// find text in image
final VisionText visionText =
    await textRecognizer.processImage(visionImage);

I expected to have the numbers as an output but , it's not recognized at all ,

A: If the ML Kit model doesn't automatically recognize the text in your image, there isn't a lot you can do to tweak it.
Instead you'll want to:

*

*Check if the Cloud Vision model is better able to extract the text from your image.

*Look into training a custom model for extracting your specific type of text.

*Look at other dedicated text extraction packages.

A: You need to process the image in this type
 final inputImage = InputImage.fromFilePath(imageFile.path);
 final RecognizedText recognizedText = await textRecognizer.processImage(inputImage);

i hope it works :)


text:
Q: How to set nestedTransactionAllowed to true in Spring? I have a case where I need to initiate calls to four different services in the same method. According to our business logic all four steps must succeed, rollback otherwise. The problem is that since all the steps occur in the same transaction (via @Transactional annotation) the second call in the method cant process the result of the first one. I have tried Propagation.REQUIRES_NEW on the first call but since it starts a new transaction the changes it makes are committed and not rollbacked whether the other calls succeed or not. At some point it seemed like Propagation.NESTED could do the work but I get a NestedTransactionNotSupportedException which warns me of setting the nestedTransactionAllowed property to true. But I could not found any document about how to do that. Any ideas? And also would appreciate any other suggestion for the problem. Thanks.
Root method:
@Override
    @Transactional
    public GuestUserDto createGuestUser(GuestUserRegisterRequest existingGuestUser) {
        guestUserDeactivationDelegateService.deactivateGuestUser(existingGuestUser);

        UserDto userDto = guestUserRegistrationDelegateService.registerGuestUser(
            guestUserRegisterDtoConverter.convert(existingGuestUser));

        createGuestUserAddress(existingGuestUser);

        guestUserRegisterHistoryService.createRegisterHistory(
            guestUserRegistrationHistoryDtoBuilder.build(userDto.getMemberId(), existingGuestUser));

        return guestUserDtoConverter.convert(userDto);
    }

Deactivation method:
    @Transactional
    public void deactivateGuestUser(GuestUserRegisterRequest existingUser) {
        deactivateSmsVerification(existingUser.getMemberId());

        String emailPlaceholder = existingUser.getMemberId() + existingUser.getEmail();
        userGraphClientService.updateUserStatus(createUserRequest(existingUser.getMemberId()));

        updateGuestUserStatus(existingUser.getMemberId(), emailPlaceholder);
    }

A: Seems that the main cause was Hibernate's flush operations order, as it was giving priority to insert over update. Flushing manually after updating in DAO layer solved the problem.

A: NestedTransactionAllowed can be set in HibernateTransactionManager as follows.
    HibernateTransactionManager manager = new HibernateTransactionManager(sessionFactory);
    manager.setNestedTransactionAllowed(true);
    return manager;

Please refer to https://www.demo2s.com/java/spring-hibernatetransactionmanager-setnestedtransactionallowed-boolean.html


text:
Q: как совместить два скрипта, а то когда оба работают проц едят жестко Подскажите такой момент, есть два бота постящие в вк в разные группы и берущие текст из разных файлов (пример одного ниже, второй отличается adres='C:\si2.txt' и api.wall.post(owner_id='-20', message=data)), как их в один запихать и как по возможности снизить нагрузку на процессор, а то мой G4500 (3.5GHz) на 100% загружен только этими двумя скриптами? (сильно не пинайте опыта очень мало)
import vk

token = "9455e5"
session = vk.Session(access_token=token)
api = vk.api.API(session, v='5.80', land='ru')
adres='C:\si1.txt'
position = 0
with open(adres) as fh:
    while True:
        fh.seek(position)
        data = fh.read()
        position = fh.tell()
        if data:
            api.wall.post(owner_id='-17', message=data)

A: методом тыка нашел решение
 with open(adres1) as fh1, open(adres2) as fh2:
    while True:
        fh1.seek(position1)
        fh2.seek(position2)
        data1 = fh1.read()
        data2 = fh2.read()
        position1 = fh1.tell()
        position2 = fh2.tell()
        if data1:
            api.wall.post(owner_id='-17', message=data1)
        if data2:
            api.wall.post(owner_id='-16', message=data2)


text:
Q: How to cancel navigation in a django view when an error occurs I would like to do the following:

*

*I am displaying view1, with template1. There is a link to view2, rendering template2

*The user clicks the link

*When processing view2, an error occurs

*Now come the interesting part: I want to cancel rendering of view2, activate an error message, and display the previous view1/template1 (a kind of redirection, but not quite) But in view2 I do not know that I was coming from view1, and I also probably do not have the context that I had when view1 was rendered

How can I re-render view1, with the error message genarated in view2, so that the user the only new thing that sees is that error message? The full template1 should be rendered as before, including any form values that the user has entered.
This is similar to form validation, but would happen in the destination view instead of the form view.
Is this at all doable, or am I trying to do something completely impossible?

A: There doesn't seem to be a way to "abort" a view, but you can get the behavior you want with the following pattern:

from django.contrib import messages
from django.shortcuts import redirect

def view1(request):
    if request.method == 'GET':
        initial_data = request.session.get('post_data', {})
        form = MyForm(initial=initial_data)
        ...

def view2(request):
    ...
    if error:
        request.session['post_data'] = request.POST
        messages.add_message(request, messages.ERROR, "Oops!")
        return redirect(request.META.get('HTTP_REFERER', '/'))

See this stack post for why preserving the POST data is painful and alternative ways of doing so.


text:
Q: From a big json variable to objects I have a rather large json stream from which I want to pull data and turn this data into objects, or a dictionary maybe.
I've managed to, for a start pull 4 lists out of the data: admin_fname, admin_sname, admin_type, and admin_email.
Now I have 4 lists of equal length, and I want to further mangle this data so I get objects containing the fname, sname, type and e-mail of an an admin.
I've tried the following:
data = response.json()
admins = [item['admin_user'] for item in data['orgs']]
admin_fname = [item['firstname'] for item in admins]
admin_sname = [item['surname'] for item in admins]
admin_type =  [item['type'] for item in admins]
admin_email =  [item['primary_email'] for item in admins]

admin_data = {}

for (a, b, c, d) in zip(admin_fname, admin_sname, admin_type, admin_email):
    admin_data[admin_fname].append()
    admin_data[admin_sname].append()
    admin_data[admin_type].append()
    admin_data[admin_email].append()

But, maybe not surprisingly, I get the error "TypeError: unhashable type: 'list'"
Can someone tell me a better way of combining elements of all 4 lists/sets into coherent objects?

A:
I have a rather large json stream from which I want to pull data and turn this data into objects, or a dictionary maybe.

I think this is the direction to go
from dataclasses import dataclass
from typing import List

data = [{'admin_fname': 'Jack', 'admin_sname': 'Ken', 'admin_type': 'the_type', 'admin_email': 'kk@some.com'},
        {'admin_fname': 'Dan', 'admin_sname': 'Borg', 'admin_type': 'the_type', 'admin_email': 'zz@some.com'}]

@dataclass
class Admin:
    admin_fname: str
    admin_sname: str
    admin_type: str
    admin_email: str

admins: List[Admin] = [Admin(**entry) for entry in data]
print(admins)

output
[Admin(admin_fname='Jack', admin_sname='Ken', admin_type='the_type', admin_email='kk@some.com'), Admin(admin_fname='Dan', admin_sname='Borg', admin_type='the_type', admin_email='zz@some.com')]

A: You have two common problems here. How to represent a single data point, and how to store those data points.
Representing a single data point
You have a large range of options, but I'm just going to highlight 3:
Tuple
You can treat your object as a set of values in a specific order. You already have this with this line:
for (a, b, c, d) in zip(admin_fname, admin_sname, admin_type, admin_email):

With some better naming:
for (fname, sname, type, email) in zip(admin_fname, admin_sname, admin_type, admin_email):

Or using the tuple:
for admin in zip(admin_fname, admin_sname, admin_type, admin_email):

And you can access each of these fields with indexing like this:
email = admin[3]

However, knowing which data is which index can get difficult after some time.
Dictionary
You can represent each data point as a dictionary. You just need to assign each field to a key:
for (fname, sname, type, email) in zip(admin_fname, admin_sname, admin_type, admin_email):
    admin = {
        "fname": fname,
        "sname": sname,
        "type": type,
        "email": email,
    }

And then, you can access each field with the key:
email = admin["email"]

However, string keys are still quite error prone
Create a class
The most OOP way of doing this would be to create a class:
class Admin:
    def __init__(self, fname, sname, type, email):
        self.fname = fname
        self.sname = sname
        self.type = type
        self.email = email

And then create an object:
for (fname, sname, type, email) in zip(admin_fname, admin_sname, admin_type, admin_email):
    admin = Admin(fname, sname, type, email)

and you can access each field as you do on objects:
email = admin.email

Using a data class is also a good option, as @balderman suggested
Storing the data
Now, how do you store this data:
List
Most straight forward, is to put it back in a list of the same order.
With tuples:
admins = [t for t in zip(admin_fname, admin_sname, admin_type, admin_email)]

With dictionaries:
admins = [{"fname": fname, "sname": sname, "type": type, "email": email} for (fname, sname, type, email) in zip(admin_fname, admin_sname, admin_type, admin_email)]

With object:
admins = [Admin(fname, sname, type, email) for (fname, sname, type, email) in zip(admin_fname, admin_sname, admin_type, admin_email)]

You can then access each individual point with an index
Dictionary
You can store all your data in a dictionary. However, at that point you need to decide on a unique key to represent each datapoint. For your purposes, that is probably not the best idea.


text:
Q: Redirect https to http for certain pages I want to redirect https requests to http for all but login and register pages.
So https:// example.com would redirect to http:// example.com but example.com/user/login should always redirect to https://example.com/user/login.
How do I do that in my .htaccess file?

A: You can detect if the current request uses https using the %{HTTPS} variable in mod_rewrite. This is either on or off. Please note that the redirect you want will not have the intended behaviour for post requests, since the redirected url will always be requested using get without the post-body.
RewriteEngine on

RewriteCond %{HTTPS} =on
RewriteCond %{REQUEST_URI} !^/user/(login|register)$
RewriteRule ^(.*)$ http://example.com/$1 [R,L]

RewriteCond %{HTTPS} =off
RewriteRule ^user/(login|register)$ https://example.com/user/$1 [R,L]

Change the R flag to R=301 after testing the redirect works as expected.


text:
Q: Unable to remove hash tags from domain name I have a one page site with five anchor links in it. When I open the site, the address bar displays domain.com/#numberofpage
I could not find a solution to remove the hash tags display, maybe I am using incorrect keywords to find this.
Could you please help to solve this?

A: var url = window.location.href;
$('#change').on('click', function() {
 var arr = url.split('?');
 arr.pop();
 window.location.href = arr[0];
});

But that would also go to to domain.com if you don't the page to actually go anywhere.
Therefore You will have to add hash # if you want to prevent page from reloading.
The css-tricks.com has an excellent screencast on that, have a look at: Best Practices with Dynamic Content


text:
Q: Showing vector various feature (location) in QGIS layer menu In QGIS (I'm using 3.16), I would like to know how to display, in the layer menu, the many feature/location included in a vector file (KML)
My KML vector includes 15 features (polygons), but navigating between each is complicated. I have to enter the attribute table, select the feature, and right-click Zoom to feature
Is there a  way to show the content of the vector file in the Layers panel in QGIS so it would have a little arrow next to it I can press and display/hide/zoom to each individual features?
I cant seem to find this option anywhere.

A: Not exactly what you are looking for, and because it is a new feature it is not in the version you are using, but maybe useful if you can update.
In QGIS 3.26 you can select features from categorized symbols in the Layers panel:

A: Go2NextFeature plugin allows you to pan or zoom to each feature in the layer quickly:
https://plugins.qgis.org/plugins/go2nextfeature/


text:
Q: Swift bind to Objective-C boolean value I've got a button shuffleButton that you can click to toggle shuffling.
Since I like to store that property when the app is closed I've bound a custom property selected, which is a Bool, from the shuffleButton to the user defaults.
shuffleButton.bind("selected", toObject: NSUserDefaultsController.sharedUserDefaultsController(), withKeyPath: "values.shuffle", options: nil)

This only works one way though. If I set the user default property the button updates.
NSUserDefaults.standardUserDefaults().setValue(true, forKey: "shuffle")

// test it out
println(NSUserDefaults.standardUserDefaults().valueForKey("shuffle"))
=> 1
println(shuffleButton.selected)
=> true

But if I update the selected property on the button the user default is not updated.
shuffleButton.selected = true

// test it out
println(NSUserDefaults.standardUserDefaults().valueForKey("shuffle"))
=> 0
println(shuffleButton.selected)
=> true

Any idea why? Is the Swift Bool value not being bridged properly to Objective-C?

A: Try using setBool to set bool value because bool is not an object,thats why iOS providing this method to save bool value.
You no need to bridge shuffleButton.selected will accept the swift bool value, everything is rewritten in swift language (check the class reference) following sample is working fine
    let defs = NSUserDefaults.standardUserDefaults();
    var k = true;
    defs.setBool(k, forKey: "bool");
    defs.setDouble(2.5, forKey: "foo");
    defs.synchronize();
    var ud = defs.doubleForKey("foo");
       var bo = defs.boolForKey("bool");
    println("default = \(ud) bool =\(bo)");
    shuffleButton.selected = bo;

A: When you update(Change Value) SuffleButton then also update your NSUserdefault.
  shuffleButton.selected = true

 NSUserDefaults.standardUserDefaults().setBool(shuffleButton.selected as Bool!, forKey: "shuffle")
 NSUserDefaults.standardUserDefaults().synchronize()


text:
Q: Cannot convert return expression of type 'AnyObject' to return type 'NSComparisonResult' I have a Swift based iOS application. I am trying to use one of the Swift sort methods to sort my array of objects by the "createdAt" NSDate property.
My array has a bunch of PFObject - these objects have different properties including an NSDate property called "createdAt".
All I want to do, is to order the array so that the objects which are the oldest, are sent to the bottom of the array.
Here is my code:
let sortedArray = (self.statusData.copy() as! NSArray).sortedArrayUsingComparator { (obj1, obj2) -> NSComparisonResult in

  if (((obj1 as! PFObject).createdAt?.compare((obj2 as! PFObject).createdAt!)) == NSComparisonResult.OrderedDescending) {
      return obj2
  }

  else {
      return obj1
  }
}

However when I try to return the objects, I get the following error:

Cannot convert return expression of type 'AnyObject' to return type
  'NSComparisonResult'

I don't understand whats wrong, why can't I just return the date comparison result which is determined my if statement?
Thanks for your time, Dan.

A: Your problem is that it's expecting a return type of NSComparasonResult and you're returning anAnyObject. However, you are already getting an NSComparasonResult in your existing code. Therefore, simply replace all of that with this:
let sortedArray = (self.statusData.copy() as! NSArray).sortedArrayUsingComparator { (obj1, obj2) -> NSComparisonResult in
    return (obj1 as! PFObject).createdAt?.compare((obj2 as! PFObject).createdAt!)
}


text:
Q: Match strings (multiple lines) in a webpage with preg_match() or preg_match_all()
Possible Duplicate:
How to parse and process HTML with PHP?

I have the following HTML output I want to match the data from it, tried with preg_match() and preg_match_all() with no success.

Jane Doe

            101 Marisa Cir

            Staten Island NY, 10309

I want to match the "address data" as:

Jane Doe, 101 Marisa Cir Staten Island NY, 10309

I fetch the page with CURL. I tried with something like this with no success:
preg_match('~(.*?[^<])

~i', $str, $showme);

A: [^<] will be saying match anything which is not <, so it won't accept the two
 at the end of each line. What happens if you try just:
preg_match('~(.+?)

~i', $str, $showme);

If you want to remove those
 tags afterwards you can replace them out.

A: You need to have the s modifier, as described here.  It makes it so that the dot matches new lines.  Because your text is over multiple lines, you need the s modifier.  You can use a regex like this:
preg_match_all('~"top">(.*?)
(.*?)
(.*?)

$~s', $text, $matches);

And that should work.  See the codepad example here.


text:
Q: $nP(|X|>n)\to0$ as $n\to\infty$, show $\frac{2}{n}\int_{0}^nxP(|X|>x)dx\to0$ If we have $nP(|X|>n)\to0$ as $n\to\infty$.
Can we show that $\frac{2}{n}\int_{0}^nxP(|X|>x)dx\to0$ as $n\to\infty$?

A: First note that $$xP(|X| > x) \leq (\lfloor x\rfloor + 1)P(|X| > \lfloor x\rfloor) = \lfloor x\rfloor P(|X| > \lfloor x\rfloor) + P(|X| > \lfloor x\rfloor)$$
which is the sum of two terms that each go to $0$ as $x\to \infty$, hence $xP(|X| > x) \to 0$ as $x \to \infty$.
Let $\epsilon > 0$.  Then there is some $N$ such that $x > N$ implies $xP(|X| > x) < \epsilon$, so let $n > N$ and write
$$\begin{align*}\frac{2}{n} \int_0^n xP(|X| > x)\,dx &= \frac{2}{n} \int_0^N xP(|X| > x)\,dx + \frac{2}{n} \int_N^n xP(|X| > x)\,dx \\ & \leq \frac{2}{n}\int_0^N xP(|X|>x)\,dx + \frac{2}{n}\int_N^n\epsilon\,dx \\ &\leq \frac{2}{n}\int_0^N xP(|X|>x)\,dx + 2\epsilon\end{align*}$$
Let $n\to \infty$ to see $$\limsup_{n\to\infty} \frac{2}{n}\int_0^n xP(|X|>x)\,dx \leq 2\epsilon$$
and since $\epsilon > 0$ was arbitrary, $\limsup_{n\to\infty} \frac{2}{n}\int_0^n xP(|X|>x) \,dx = 0$.
Finish by noting that $\frac{2}{n}\int_0^n xP(|X|>x)\,dx \geq 0$.


text:
Q: Pipe or Service in Angular? I need to provide simple array of data with years.
What will be right to create: pipe or typically service class?
Iameging, that it is pipe. Then can I iterate this pipe in ngFor like this:
ngFor="item of pipe()"?

A: You should create an array in this case, neither pipe nor a service.
You can create an array by calling a function with the name pipe() though, that would return an array with your specified data.


text:
Q: Translating HTML/JS/CSS to Ruby on Rails At the moment I have created a webpage that makes use of HTML, CSS, and Javascript but I need to implement ruby on rails next in order to do back end stuff as well as it's what my boss told me to utilize. Now I have never utilized Ruby on Rails so any guidance will be greatly appreciated.
Now I know that CSS has pre-processors such as SASS and others but how exactly do I utilize these. I also understand the basic structure of Rails in that there are different controllers and each one corresponds to different things.
Basically I would just like some guidance on how to implement a Ruby on Rails framework.
If you need any other information, I would be glad to oblige you with it.

A: Okay, so there's nothing bad at being a beginner level of a developer on anything. The fact that you want to learn and get better at it is more important. So, you'd want to the following things:

*

*First of all, you need to set your environment. This would depend on your machine configurations. Once you have your environment ready, you can proceed further.

*Get to know Rails better. Get adept at using Ruby on Rails.This is going to be your primary back-end stuff. You can start reading about it here: http://rubyonrails.org/, here: http://guides.rubyonrails.org/getting_started.html and here: http://www.tutorialspoint.com/ruby-on-rails/

*Figure what database you'd like to pair it up with. Practice a little with the db queries and see you're able to filter whatever data you want to. Most often, MySql, SQLite and PostgreSql work best with RoR. But then again, One of the tenets of Rails is you shouldn't really care what database you're using: that's all abstracted for you.

*Integrate RoR with your front-end (Javascript). This is usually pretty straight-forward. You can use rails on your front-end too (for eg., you can use rails forms instead of pure html forms). You can read more about it here: http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html

*Add CSS styles to your html.erb files. This works like any other .html files. You may or may not use SASS. Ruby on Rails works fine even with pure CSS. You can also have CSS libraries like Bootstrap. (Isn't that cool! :P). You can learn more about integrating Saas with RoR here: https://www.youtube.com/watch?v=dKe2sP-NAxQ

*Another important note to keep in mind would be to write RSpec tests at each step to confirm that your code is working fine and is not effecting any other section of code. You can read more about it here: http://rspec.info/ and http://betterspecs.org/.

And that's it, you are good to go! :)


text:
Q: CotntentProvider mime type clarification Is there any difference, from client's perspective, whether provider serves data with item or dir type? Does the framework use this information for optimization? Can you give examples of code where mime type matters? Could I just use dir mimetype for any case?
P.S. I know that dir = collection and item = row. And I read the doc. Still, as a developer, I can't understand why should I bother differentiating item from dir. Isn't it just enough to use dir?


text:
Q: How to add extra filter options to an Ajax PHP search using mysql Based on this example http://www.w3schools.com/php/php_ajax_database.asp
i have made some search and found this sample which looks what i need
The HTML

<form>
Select a User:
<select name="users" id="users">
<option value="1">Marko</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>

Select an age:
<select name="age" id="age">
<option value="1">1</option>
<option value="40">40</option>
<option value="41">41</option>
<option value="42">42</option>
</select>

<input type="text" name="c" id="c" value="2016-06-01">

<input type='button' value='Refresh Data' onclick="showUser(document.getElementById('users').value,document.getElementById('age').value,document.getElementById('c'))">
</form>

Person info will be listed here.

and PHP
<?php
$q=$_GET["q"];
$a=$_GET["a"];
$c=$_GET["c"];

$con = mysql_connect('localhost', 'username', 'password');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("databasename", $con);

$sql="SELECT * FROM data WHERE id = '".$q."' and website  = '".$a."' and date  = '".$c."'";

$result = mysql_query($sql);

echo "

Firstname
Lastname
Age
Hometown

";

while($row = mysql_fetch_array($result))
  {
  echo "
";
  echo "" . $row['date'] . "	";
  echo "" . $row['imp'] . "	";
  echo "" . $row['rev'] . "	";
  echo "" . $row['cpm'] . "	";
  echo "
";
  }
echo "
";

mysql_close($con);
?>

How can i add the date picker to the search, for the moment it works only with two <select> but i want to be able to add a Start date & End date
I tried adding <input type="text" name="c" id="c" value="2016-06-01"> but could not figured out where the mistake is

A: you need to add the c variable as a parameter of your showuser function.
function showUser(str,age, c)


text:
Q: Can a customer be loyal or regular? I read a lot about the difference between customer and client. There have been a myriad of answers, and the most common thing I could find is the one that matches Hellion's answer here:

Client -  ongoing relationship with the seller.
If you go to the store to buy a box of matches, you're just a customer, but if you always go to that store because you know you'll get good service and good prices, you're a client.

Now the question
I have heard many people say:

Take care of him, he's our regular customer

But...

Can a customer be loyal or regular?

If they can be, they are no more customers but clients!
Furthermore, is this sentence correct (or redundant)?

He's our regular client!

A: The line between "customer" and "client" has certainly blurred, but I think there is still a leaning towards a customer being someone who purchases, and a client being someone with an ongoing, more personal relationship with the business in question, and usually more in relation to services than products. Rarely would an architect describe their clients as "customers", while a retail store describing "clients" is likely to be a more high-end store, or one that wants to elevate the value of their "customers", or otherwise be speaking in wider terms: perhaps Walmart head office would talk about "clients", while Walmart store staff would talk about "customers". The choice is a free one, but there remain subtle differences that inform the speaker's choice of wording, based on the earlier, much stronger distinctions.
I'm not sure exactly what you mean by asking "Can a customer be loyal or regular?", but I will point out that there is a difference in value again: a regular customer would be someone who frequents a store, while a loyal customer would be someone who stands up for the store, for example, they continue to frequent the store despite the store going through hard times and having to reduce stock while raising prices. This might drive away regulars, but the particularly loyal will stick by them!
A loyal customer could certainly be "upgraded" to a client, to the store owner's mind, in that there is an implied relationship between the customer and the staff, and a stronger desire for staff to "look after" the customer. A casual customer, or even a regular one, might continue to be regarded as a "customer".

A: Client and customer are no longer distinguished in the way they once were.
As recently as fifty years ago, client was still by and large reserved for people who sought advice from 'professionals' such as attorneys and architects. At that time client still reflected, even if only very dimly, the original Latin sense of the word as "one who is under the protection of" a patron. A client was someone who benefited from the professional's learning and knowledge, while a customer was someone who had a purely commercial relationship with a tradesperson.
In this context, the term client acquired an honorific character. It flattered the person rendering services because it imputed a 'professional' degree of expertise; it also flattered the person who purchased the services because it imputed a degree of wealth and status—a person who routinely consults professionals is clearly someone above the common run of customers. And it happily set both at some distance from the vulgarity of commerce.
In consequence, from the last half of the 19th century, businesses of all sorts started referring to their customers as clients—'exclusive' tailors and hairdressers, grocers, insurance agents, even bookmakers (now calling themselves 'turf accountants'). And since it is mostly businesspeople who talk about the relationship between buyer and seller, that use has gradually extended into ordinary speech.
The upshot is that today there is no difference whatever between customers and clients—they are the same people. Instead, customer is used when you wish to focus on the financial aspect of the relationship, client when you wish to focus on the personal service rendered.

A: "customer"=someone who buys goods or services from a store,company etc.
"regular customer"is correct.It means he often does his shopping from there.
"client"=someone who pays for services or advice from a professional person,such
as a lawyer or architect ,or from a company or organization.
If loyal is used ,it means that he supports or likes their services or ideas for
advice .


text:
Q: Override @ngrx/data, @ngrx/entity Actions, Reducer, Effects I'm new to @ngrx/data and trying to understand how I can override the reducer & actions.
My current problem could be solved in other ways like adding an extra method, reducer & action but I  would probably need this answer in the future.
The problem is that my delete call should just set the item to "hidden" in the store and not to delete it.
This is the set-up I'm using: https://stackblitz.com/edit/ngrx-data-tutorial


text:
Q: timestamp from Incoming SMS android How can I get time stamp of incoming sms. Here is my code.
 public void onReceive(Context context, Intent intent) {
    Log.i("SMS Reciever", "smsReceiver: SMS Received");
    Bundle bundle = intent.getExtras();
    if (bundle != null) {
        Log.i("SMS Reciever", "smsReceiver : Reading Bundle");
        Object[] pdus = (Object[])bundle.get("pdus");
        for (int i = 0; i < pdus.length; i++) {
        SmsMessage sms = SmsMessage.createFromPdu((byte[])pdus[i]);
        SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
        String phoneNumber = currentMessage.getDisplayOriginatingAddress();
        String senderNum = phoneNumber;
        String message = currentMessage.getDisplayMessageBody();
        Log.i("SmsReceiver", "Send From: "+ senderNum + "; message: " + message);

A: try as to get Timestamp from Incoming SMS :
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
 // get Timestamp
long timstamp=currentMessage.getTimestampMillis();

A: Soon as you receive an SMS on your device, Broadcast receiver handles it, as you've codded it. so to get time at which SMS is received, you may use:
long smsReceiveTime = System.currentTimeMillis();

after your
String message = currentMessage.getDisplayMessageBody();

and same way, for date:
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());


text:
Q: Selecting row with highest ID based on another column In SQL Server 2008 R2, suppose I have a table layout like this...
+----------+---------+-------------+
| UniqueID | GroupID | Title       |
+----------+---------+-------------+
|    1     |    1    | TEST 1      |
|    2     |    1    | TEST 2      |
|    3     |    3    | TEST 3      |
|    4     |    3    | TEST 4      |
|    5     |    5    | TEST 5      |
|    6     |    6    | TEST 6      |
|    7     |    6    | TEST 7      |
|    8     |    6    | TEST 8      |
+----------+---------+-------------+

Is it possible to select every row with the highest UniqueID number, for each GroupID.  So according to the table above - if I ran the query, I would expect this...
+----------+---------+-------------+
| UniqueID | GroupID | Title       |
+----------+---------+-------------+
|    2     |    1    | TEST 2      |
|    4     |    3    | TEST 4      |
|    5     |    5    | TEST 5      |
|    8     |    6    | TEST 8      |
+----------+---------+-------------+

Been chomping on this for a while, but can't seem to crack it.
Many thanks,

A: SELECT *
FROM   (SELECT uniqueid,  groupid,  title,
               Row_number()
                 OVER ( partition BY groupid ORDER BY uniqueid DESC) AS rn
        FROM   table) a
WHERE  a.rn = 1

A: Since you have not mentioned any RDBMS, this statement below will work on almost all RDBMS. The purpose of the subquery is to get the greatest uniqueID for every GROUPID. To be able to get the other columns, the result of the subquery is joined on the original table.
SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  GroupID, MAX(uniqueID) uniqueID
            FROM    tableName
            GROUP   By GroupID
        ) b ON a.GroupID = b.GroupID
                AND a.uniqueID = b.uniqueID

In the case that your RDBMS supports Qnalytic functions, you can use ROW_NUMBER()
SELECT uniqueid,  groupid,  title
FROM
(
SELECT uniqueid,  groupid,  title,
        ROW_NUMBER() OVER (PARTITION BY groupid
                           ORDER BY uniqueid DESC)  rn
FROM   tableName
) x
WHERE  x.rn = 1

*

*TSQL Ranking Functions
The ROW_NUMBER() generates sequential number which you can filter out. In this case the sequential number is generated on groupid and sorted by uniqueid in descending order. The greatest uniqueid will have a value of 1 in rn.

A: With  SQL-Server as rdbms you can use a ranking function like ROW_NUMBER:
WITH CTE AS
(
    SELECT UniqueID, GroupID, Title,
       RN = ROW_NUMBER() OVER (PARTITON BY GroupID
                               ORDER BY UniqueID DESC)
    FROM dbo.TableName
)
SELECT UniqueID, GroupID, Title
FROM CTE
WHERE RN = 1

This returns exactly one record for each GroupID even if there are multiple rows with the highest UniqueID (the name does not suggest so). If you want to return all rows in then use DENSE_RANK instead of ROW_NUMBER.
Here you can see all functions and how they work: http://technet.microsoft.com/en-us/library/ms189798.aspx

A: SELECT *
FROM the_table tt
WHERE NOT EXISTS (
    SELECT *
    FROM the_table nx
    WHERE nx.GroupID = tt.GroupID
    AND nx.UniqueID > tt.UniqueID
    )
    ;

*

*Should work in any DBMS (no window functions or CTEs are needed)

*is probably faster than a sub query with an aggregate

A: Keeping it simple:
select * from test2
where UniqueID in (select max(UniqueID) from test2 group by GroupID)

Considering:

create table test2
(
UniqueID numeric,
GroupID numeric,
Title varchar(100)
)

insert into test2 values(1,1,'TEST 1')
insert into test2 values(2,1,'TEST 2')
insert into test2 values(3,3,'TEST 3')
insert into test2 values(4,3,'TEST 4')
insert into test2 values(5,5,'TEST 5')
insert into test2 values(6,6,'TEST 6')
insert into test2 values(7,6,'TEST 7')
insert into test2 values(8,6,'TEST 8')


text:
Q: C# Keep form draggable when show another form using ShowDialog method I have three projects (proj1, proj2, pro3). The proj1 (winforms) is where I integrate the others projects. The proj2 (in wpf, not important for this question, I thinks) have a window like  a menu of notifications which I want be always on top and be draggable. The proj3 (wpf too) have some windows with owner relations.
Proj1:
public FormGeral()
{
    InitializeComponent();
    StartMenu();
}

private void StartMenu()
{
    var wpfwindow = new Proj2.WindowController(this.pProperties, true);
    ElementHost.EnableModelessKeyboardInterop(wpfwindow);
    wpfwindow.Closed += wpfwindow_Closed;
    this.Activate();
}

private void buttonX_Click(object sender, EventArgs e)
{
   var wpfwindow = new Proj3.WindowInvoices(this.pProperties);
   ElementHost.EnableModelessKeyboardInterop(wpfwindow);
   wpfwindow.Show();
   wpfwindow.Closed += wpfwindow_Closed;
 }

In proj3, the WindowInvoices have a button like that:
private void ButtonAddInvoice_Click(object sender, RoutedEventArgs e)
        {
            WindowAddEditInvoice window = new WindowAddEditInvoice(this.PProperties, idModulo, null, true, null);
            window.Owner = this;
            window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            window.ShowDialog();
        }

When I first click to open WindowInvoices on Proj3, the menu on Proj2 works nice, on top and draggable. But when I open WindowAddEditInvoice on Proj3, the menu window on Proj2 isn't draggable. Pay attention to the use of Show or ShowDialog methods.
What is the best way to implement this behavior?


text:
Q: Android Passing Data I need some advice on an application I am writing for a android using eclipse. I am writing an application that adds 2 numbers and passes the data back to the first activity using an intent. I am not sure if I use intent.putExtra ( num1 +num 2), any advice would be greatly appreciated. Thanks-

A: Suppose u r going from Activity A to Activity B and u want to return something back to Activity A, then here is an example. Hope it helps :
Code to go to Activity B o button click :
button1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent intent=new Intent(MainActivity.this,SecondActivity.class);
            startActivityForResult(intent, 2);
            //2 is the request code. u can choose ur own.
        }
    });

also in the same activity override onActivityResult method :
@Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data)
   {
             super.onActivityResult(requestCode, resultCode, data);

              // check if the request code is same as what is passed  here it is 2
               if(requestCode==2)
                     {
                        Int x = data.getIntExtra ("num1");
                        Int y = data.getIntExtra ("num2");

                     }
 }

And in your Activity B
button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Bundle b = new Bundle();
                b.putIntExtra("num1", int1);
                b.putIntExtra("num2", int2);
                Intent i = new Intent();
                i.put(b);
                finish();//finishing activity
            }
        });

A: You need this in your first activity:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == RESULT_OK){
            int result=data.getIntExtra("result");
        }
        if (resultCode == RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}//onActivityResult

And this in your class that does the math:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",sumOfNumbers);
setResult(RESULT_OK,returnIntent);
finish();

A: You can start the Activity that adds the 2 numbers with startActivityForResult() and then implement the onActivityResult() callback to receive the result.
In the Activity that adds the 2 numbers you can set the result with setResult(resultCode, Intent):
Intent returnIntent = new Intent();
returnIntent.putExtra("result", sum);
setResult(RESULT_OK,returnIntent);
finish();

Check out the Android docs: http://developer.android.com/training/basics/intents/result.html

A: You'll want to use the onActivityResult function of the parent Activity class.
int RESULT_CODE_CHILD_ACTIVITY = 1;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode)
    {
        case (RESULT_CODE_CHILD_ACTIVITY) :
        {
            if (resultCode == Activity.RESULT_OK)
            {
                int yourInt = data.getIntExtra("yourInt", -1);
            }
            break;
        }
    }
}

And you'll want to override the onDestroy function of your child activity to pass the data back.
@Override
public void onDestroy()
{
    Intent resultIntent = new Intent();
    int yourInt = 5 + 4;
    resultIntent.putExtra(yourInt, "yourInt");
    setResult(Activity.RESULT_OK, resultIntent);
    super.onDestroy();
}


text:
Q: find unused properties in eclipse I have set of classes and (struts)jsp files which uses Message bundle. I want to find properties which are not used in project.One simple way would to search for each property (in given project) and if 0 result, delete it.
In eclipse there is a function like
Source > Find Broken Externalized Strings
I don't think it works. Not sure what its for. I get message
"no nls property files with corresponding accessor of class found in selection"

A: It seems like Eclipse expects to find the class that it generates in the "Externalize Strings..." command:
package com.foo.bar;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class Messages {
    private static final String BUNDLE_NAME = "com.foo.bar.messages"; //$NON-NLS-1$

    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);

    private Messages() {
    }

    public static String getString(String key) {
        try {
            return RESOURCE_BUNDLE.getString(key);
        } catch (MissingResourceException e) {
            return '!' + key + '!';
        }
    }
}

Actually, after digging a little deeper, I found that Eclipse really wants the following:
private static final String BUNDLE_NAME = "com.foo.bar.messages"; //$NON-NLS-1$

public static String getString(String key) {
    ...
}

The package "com.foo.bar" must contain the file "messages.properties". You can run "Find Broken Externalized Strings" on any source file (or on the package) that you add these lines to.


text:
Q: Handle qooxdoo inline widget events in jQuery I've embedded a qooxdoo widget (the table) within an existing web app using inline integration (http://qooxdoo.org/documentation/0.8/ui_inline).
Is it possible to raise an event in the widget that can be handled externally within the main web app? Specifically I want to raise a "row selected" event when the user selects an item in the table.
Thanks,
Paul

A: afaik the table selection model has the event "changeSelection".
tableInstance.getSelectionModel().addListener("changeSelection", yourListener, yourContext);

With this event you can get the necessary infos within your listener method and fire an event to a DOM element which any JS library can use to listen to.
qx.event.Registration.fireEvent(document.body, "rowSelected", qx.event.type.Event);

You can fire the event at every DOM element you like to. In your case you can use jQuery to listen to the event and get the infos.
Hope that helps you further.
Regards,
  Alex


text:
Q: Relaunch iOS app without user interface when application in background? how to relaunch iOS app without user interface when application in background?
I know notification but in any notification user must click alert view button to relaunch or open app.

A: There is no way to do this.
User must involve for doing this.

A: You can't, as everyone else has said. You can do background stuff though, but this is limited in various ways:

For iOS apps, it is crucial to know whether your app is running in the
  foreground or the background. Because system resources are more
  limited on iOS devices, an app must behave differently in the
  background than in the foreground. The operating system also limits
  what your app can do in the background in order to improve battery
  life and to improve the user's experience with the foreground app. The
  operating system notifies your app whenever it moves between the
  foreground and background. These notifications are your chance to
  modify your app's behavior.

-- http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html

A: So you want to launch your app programmatically, without user interaction ? I do not think there's a way to do it, due to iOS limitation, sorry.

A: It is impossible in general case on stock device.
It depends what you mean by "user interaction".
I had a case for one app(smth like server) where user can do anything with device but do not able to touch screen, because device was placed in special box.
I found a way to use Siri.
I enabled option "Hey, Siri" and user can re/launch app with voice commands.


text:
Q: How to automatically execute code in terminal So i built this really simple game in c language, where you are a ship and need to avoid a bullet rising up the screen. Once I run it in terminal, every time I want to move the ship I enter a (left) s(straight) or d(right). I was wondering if there was a way to not be forced use the enter key after every move and rather have the bullet gradually rise up like one space a second or something automatically.
The code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <assert.h>
#define height 20
#define width 15

int main (int argc, char *argv[]) {
    printf("Beginning Game\n");
    printf("Press 's' to start\n");
    char move = 0;
    int count = 6;
    int turn = 0;
    int row = 0;
    int col = 0;
    int left = 0;
    int right = 14;
    srand(time(NULL));
    int shootcol =  rand() % (width - 3) + 2 ;
    int shootrow = height + 1;
    int shoot2col = rand() % (width - 3) + 2 ;
    int shoot2row = height + 15;

while (move != 'e') {
    printf("\n");
    scanf(" %c", &move);
    if (move == 's') {
        turn++;
    }
    else if (move == 'a') {
        count--;
        turn++;

    } else if (move == 'd') {
        count++;
        turn++;

    }
    row = 0;
    col = 0;
    printf("TURN: %d\n", turn);
    while (row < height) {
        while (col < width) {
            //printf("%d", col );
            if (((row == shootrow) && (col == shootcol)) || ((row == shoot2row) && (col == shoot2col))) {
                printf(":");

            } else if (col == left) {

                printf("|");

            } else if (col == right) {
                printf("|");

            } else if (row < 5) {
                printf(" ");

            } else if (row == 5) {

                if (col < count) {
                    printf(" ");
                } else if (col == count) {
                    printf("|");

                } else if (col == count + 1) {
                    printf("-");

                } else if (col == count + 2) {
                    printf("|");

                } else if (col >= count + 3)    {
                    printf(" ");
                }
            } else if (row == 6) {

                if (col < count) {
                    printf(" ");
                } else if (col == count) {
                    printf("\\");

                } else if (col == count + 1) {
                    printf(" ");

                } else if (col == count + 2) {
                    printf("/");

                } else if (col >= count + 3)    {
                    printf(" ");
                }

            } else {
                printf(" ");

            }
            col++;

        }
        col = 0;
        printf("\n");
        row++;

    }
    shootrow--;
    shoot2row--;
    if ((count == left) || (count == right - 2)) {
        printf("YOU LOSE!!\n");
        move = 'e';
    } else if ((shootrow == 5) || (shootrow == 4)) {
        if ((count == shootcol) || (count == shootcol - 2 ) || (count == shootcol - 1)) {
            printf("YOU LOSE!!\n");
            move = 'e';
        } if ((count == shoot2col) || (count == shoot2col - 2 ) || (count == shoot2col - 1)) {
            printf("YOU LOSE!!\n");
            move = 'e';
        }

    } if (shootrow <= 0) {
        shootrow = height - 1;
        shootcol =  rand() % (width - 3) + 2 ;
    } if (shoot2row <= 0) {
        shoot2row = height - 1;
        shoot2col = rand() % (width - 3) + 2;
    }

}

return 0;
}

A: The simplest way is using the conio library
#include <conio.h>
#define DELAY 300    // define here the amount of milliseconds to sleep

If you are using linux or mac
#include <unistd.h>

If you are using Windows
#include <windows.h>

and this is how the beginning of your loop would look like
while (move != 's')
    scanf(" %c", &move);

move = ' ';

while (move != 'e') {
    printf("\n");

    //Sleep(DELAY);    // windows only sleep 's' lowercase for linux
    usleep(DELAY);     // for mac

    if (_kbhit())
    {
        move = _getch();
    }

    if (move == 's') {
        turn++;
    }


text:
Q: Heroku custom exception page is it possible - and in this case how - to have a custom html page when an exception happens on production environment in Heroku?
Right now there is a centered white box with red text:
"We're sorry, but something went wrong.
We've been notified about this issue and we'll take a look at it shortly."
Thanks,
Augusto

A: Custom error page is possible in heroku , as far as I know there is a heroku plugin/add-on for it
Check this link https://devcenter.heroku.com/articles/error-pages


text:
Q: How to sort documents based on $in order? I have array of ObjectIds like the following:
var list = [{_id: ObjectId(1)}, {_id: ObjectId(2)}, {_id: ObjectId(3)}];
I need to query these documents by the following query:
Post.find({_id: {$in: list}}).exec(function (err, posts) {
    console.log(posts);
});

But unfortunately the order of posts is random. What is the best way to make proper order based on list array?

A: for that problem we have two options:

*

*Sort client side

*Sort using aggregation framework as per this answer
db.x.aggregate:([{ $sort:{ list:1 }}])


text:
Q: How to work out modular arithmetic quickly for cryptography I am not so good at Mathematics so please kindly forgive my stupidity.
Basically, I am learning modular arithmetic for cryptography and so I am struggling in understanding how to do big modular arithmetic calculation without a calculator.
So for example, how would I do this question: 6^56 mod 19?
I get that you need to convert the power 56 into binary - so that would be 0111000. So like 2^32 + 2^16 + 2^8.
I then understand you have to do like:
6^8 mod 19 then 6^16 mod 19 and 6^32 mod 19.
I've been told I can use the chinese remainder theorem - but I want to know how to do this all.
Any help would be absolutely great! I like this stuff but I have been struggling a bit.

A: What you mention you have to perform is the fast exponentiation algorithm.  However, usually one performs reductions  that rest on Fermat's little theorem (or Euler's theorem if the modulus is composite). Here, it is particularly efficient:
As $6$ and the modulus are coprime, we  know the $6^{18}\equiv 1\pmod{19}$, so that
$$6^{56}\equiv 6^{56\bmod 18}=6^2\pmod{19},$$
therefore $\;6^{56}\equiv 36\equiv-2\:$ (or $17)\pmod{19}$.


text:
Q: Recibo de un php un "responseText" vacío Tengo este código en un .js
function mandarMain(secc){

    const seccionPrincipal = document.getElementById("mainPage");
    var dentro = seccionPrincipal.innerHTML;

    let blankSpace = document.createElement("p");
    blankSpace.innerHTML = "______________________________________________________________";
    blankSpace.style.cssText = "text-align: center; color: #D7DF01;";

    switch(secc){

        case "Inicio":

        break;

        case "Teatro":

            let encabezadoT = document.createElement("p");
            encabezadoT.innerHTML = "Teatro";
            encabezadoT.style.cssText = "text-align: center; font-family: castella;";

            if(!dentro.includes("Teatro")){

                while(seccionPrincipal.firstChild){
                    seccionPrincipal.removeChild(seccionPrincipal.firstChild);
                }

                seccionPrincipal.appendChild(encabezadoT);

                var conectaT = new XMLHttpRequest();
                conectaT.open( "GET", "obtenerTeatro.php", false );
                conectaT.send(null);

                console.log(conectaT.responseText);
            }

        break;
    }

}

Al final del case "Teatro", mando a la consola el responseText del XMLHttpRequest (para poder ver su contenido) y me aparece vacío. Como información adicional, la función es llamada desde un archivo .html, por un evento "onclick", y cuando abro el url directamente en mi navegador (el url de la página donde está el archivo obtenerTeatro.php") si me muestra la cadena que quiero mandar de regreso, ¿por qué no recibo nada entonces en el responseText?

A: esto ocurre porque el código sigue trabajando incluso si la respuesta de tu PHP aun no a llegado, (así funciona JavaScript, es síncrono) y recordemos que las peticiones no son instantáneas, se demoran en llegar, lo que debes hacer es agregarle funciones a los eventos, con addEventListener a por ejemplo load, que es el evento de cuando se completa la petición. y allí llamar a funciones o manipular el código con las respuestas, y luego por ultimo llamar al metodo send(), entonces una vez se complete le peticion se ejecutara todo lo que esta dentro del  conectaT.addEventListener("load", function() {  }) en todo caso esto es super anticuado, hoy en dia se usa Ajax o fetch
case "Teatro":

    let encabezadoT = document.createElement("p");
    encabezadoT.innerHTML = "Teatro";
    encabezadoT.style.cssText = "text-align: center; font-family: castella;";

    if (!dentro.includes("Teatro")) {

        while (seccionPrincipal.firstChild) {
            seccionPrincipal.removeChild(seccionPrincipal.firstChild);
        }

        seccionPrincipal.appendChild(encabezadoT);

        var conectaT = new XMLHttpRequest();
        conectaT.open("GET", "obtenerTeatro.php", false);

        conectaT.addEventListener("load", function() {
            if (conectaT.status < 400)
                console.log("éxito",conectaT.responseText)
            else
                console.log("error",conectaT.statusText)
        });
        conectaT.send(null);

    }

    break;

    }

break;


text:
Q: When debugging java, "Unable to open 'blah.java': resource is not available" I'm running VSCode (v1.26.1) with the Java Extension Pack (v0.3.0) for remote debugging.  When execution hits a breakpoint, VSCode does not open the file, though it correctly displays the filename in the call stack:

Instead, it displays the error:

I have the following in my launch.json:

Adding the sourcePaths property got VSCode to display the filename in the call stack for the line of code with the breakpoint.  It previously displayed Unknown Source. But it still can't open the file.  It appears that sourcePaths has only enabled VSCode to "sort of" find the source file.
Does anyone know what I need to do to get it to open the file when it hits the breakpoint (or when I click on the file in the call stack)?
Note: This question is different than this question in that I'm using Java Extension Pack's Debugger for Java and not the deprecated javaVSCode that was being used by the asker of that question.


text:
Q: Replace Linux GRUB, boot Windows by default with Windows Boot Manager, keeping Linux installed I've installed Ubuntu 20.04 as a dual boot after Windows 10. Now, when the laptop starts or restarts, it boots into Linux by default after showing the GRUB menu.
But I want to boot Windows normally by default, like before using Windows Boot Manager, replacing Linux Grub, but also want to keep Linux installed,
I want to boot Linux from BIOS Boot Manager only when needed.
Please help me.
Edit: I know that the boot order can be changed and can make Windows boot default in the Linux GRUB menu, but I don't want the GRUB menu to be shown while booting to Windows, as it takes some seconds more to boot Windows, since I'll boot Windows more and Linux less.
Probably solution 1: (this method works, but I'm not sure what this actually does, want more reliable solution)
From Windows:

*

*Settings → Recovery → Advanced Startup → Restart Now
Or Press Shift while restarting Windows to access the "Advanced Startup" menu.

*Troubleshoot → Command Prompt:
MOUNTVOL Z: /S
BCDBoot C:\Windows

Update 1: This will disable Windows Recovery Environment. Enable WinRE by:

*

*Windows Key+R

*Ctrl+Shift+Enter

*Yes

*Reagentc / Enable

This will enable Windows Recovery Environment again.


text:
Q: pytest error: ImportError: cannot import name 'Expression' from '_pytest.mark' I'm getting this error:
conftest.py:95: in <module>
    from framework.scheduler import PytestScheduler
framework/scheduler.py:33: in <module>
    from _pytest.mark import Expression, MarkMatcher
E   ImportError: cannot import name 'Expression' from '_pytest.mark' (/usr/lib/python3/dist-packages/_pytest/mark/__init__.py)

could it possibly be my version of pytest? How do I know which version should I use?
The file /usr/lib/python3/dist-packages/_pytest/mark/__init__.py exists so it's installed.

A: sudo pip install --upgrade attrs==21.2.0
sudo pip install --upgrade pytest==6.2.4

fixed for me


text:
Q: Grouping options together in Jquery I have two selections. Which are IT and Management. Both of them has one of the same option. How can I group them together?
How can I do that? I actually new in Jquery
As you can see the IT and Management had both the same option which is Analyst. How should I code to ensure that the Analyst is declared one time but can be used in both IT and Mangement
Code:

$(document).ready(function() {
  $("#select1").change(function() {
    if ($(this).data('options') == undefined) {
      $(this).data('options', $('#select2 option').clone());
    }

    var id = $(this).val();
    var options = $(this).data('options').filter('[value=' + id + ']');
    $('#select2').html(options);
  });

  $("#select1").change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="select1" id="select1">
  <option value="3"></option>
  <option value="1">IT</option>
  <option value="2">Management</option>
</select>
<select name="select2" id="select2">
  <option value="3"></option>
  <option value="1">Programmer</option>
  <option value="1">Technician</option>
  <option value="1">Analyst</option>
  <option value="2">HR</option>
  <option value="2">Secretary</option>
  <option value="2">Analyst</option>
</select>

A: As I understand it, you want different options to be populated in the second dropdown, depending on the selection in the first. And, you want to use the "same" option (Analyst) in both the first and second box. Here's one way you could do it:
HTML
<select name="select1" id="select1">
    <option value="it">IT</option>
    <option value="management">Management</option>
</select>
<select name="select2" id="select2">
    <!-- options will be loaded dynamically -->
</select>

JavaScript
// hashtable of all roles
// (keys could be strings or ints, depending on your style and data)
var roles = {};
roles['code'] = 'Programmer';
roles['tech'] = 'Technician';
roles['analyst'] = 'Analyst';
roles['hr'] = 'HR';
roles['secretary'] = 'Secretary';
roles['boss'] = 'Boss';

// store the keys we want for each option group
var groups = {};
groups['it'] = ['code', 'tech', 'analyst'];
groups['management'] = ['hr', 'secretary', 'analyst'];

function changeOptionGroup(groupKey) {
    // clear out the current options
    $("#select2").empty();

    // load the correct ones
    groups[groupKey].forEach(function (value, index) {
        $("#select2").append($("<option />")
            .val(value)
            .text(roles[value]));
    });
}

$(document).ready(function () {
    // when the first box changes, update the second
    $('#select1').change(function () {
        changeOptionGroup($(this).val());
    });

    // fire on page load
    $('#select1').change();
});

Explanation

*

*First, we populate roles with all of the possible options we want to use in the second box. Each one is stored with a key and a value.

*Then, we can make a groups object and store an array of the keys we want to see in each group. The group has a key, too - note how I made the keys here (it and management) the same as the values of the options in the select1 dropdown. That'll be useful in a minute.

*The changeOptionGroup() function takes a groupKey parameter, clears out the second box, and then uses a loop to add the correct options to the second box depending on the group we've selected. groups[groupKey] accesses the groups object and retrieves the array of role keys we want. .text(roles[value]) looks up a specific role in the roles object (value is provided by the loop).

*Finally, we can wire all this up in .ready(). This is pretty simple: just a event binding to .change() to call changeOptionGroup with the currently selected option's value passed in. We also need to fire the event on page load (otherwise, it won't work until the first time the user changes the selection).

JSFiddle: http://jsfiddle.net/do9kq54r/2/


text:
Q: Copy a subset of column data from one table to another I have two tables with identical schema.  Let's name them TestTable and TestTableTemp.  I need to copy just two columns from TestTableTemp to TestTable without disrupting other data.  The rows in TestTable are a subset of those in TestTableTemp.   Let's say the columns that I need to copy are named Column1 and Column2 and that they have identical primary keys reference by column primaryKey.

In mysql I believe this could be done as such or something similar:
UPDATE TestTable, TestTableTemp
SET TestTable.Column1 = TestTableTemp.Column1, TestTable.Column2 = TestTableTemp.Column2
WHERE TestTable.primaryKey = TestTableTemp.primaryKey

Sqlite does not allow for multiple tables to be defined on the update statement as can been seen in their reference data here: http://www.sqlite.org/lang_update.html
The best I could come up with is such:
UPDATE TestTable SET
Column1 = (select TestTableTemp.Column1 from TestTableTemp, TestTable where TestTable.primaryKey = TestTableTemp.primaryKey),
Column2 = (select TestTableTemp.Column2 from TestTableTemp, TestTable where TestTable.primaryKey = TestTableTemp.primaryKey)
WHERE EXISTS(select * from TestTableTemp where TestTable.primaryKey = TestTableTemp.primaryKey"

This gives me a syntax error near "."  I am guessing this is because I cannot reference TestTable in the scalar expressions.
Can anyone point me in the right direction?  Any help is much appreciated.
EDIT:
I cleaned up the second query a bit.  It seems to just set the Column1 and Column2 to the first row from that column from TestTableTemp.

A: Your original query for comparison:
UPDATE TestTable, TestTableTemp
   SET TestTable.Column1 = TestTableTemp.Column1
     , TestTable.Column2 = TestTableTemp.Column2
 WHERE TestTable.primaryKey = TestTableTemp.primaryKey

Here is the working query (I just slightly changed your version):
http://sqlfiddle.com/#!5/f3a19/9
UPDATE TestTable
SET

  Column1 = ( SELECT TestTableTemp.Column1
              FROM   TestTableTemp
              WHERE  TestTableTemp.primaryKey = TestTable.primaryKey )

 ,Column2 = ( SELECT TestTableTemp.Column2
              FROM   TestTableTemp
              WHERE  TestTableTemp.primaryKey = TestTable.primaryKey )

WHERE EXISTS( SELECT NULL
              FROM   TestTableTemp
              WHERE  TestTableTemp.primaryKey = TestTable.primaryKey )
;


text:
Q: On click button Check and Uncheck multiple radio buttons via Jquery
As per the image I want to check and uncheck radio button as all present and all absent. I have written some code but it works only once.
$(document).on('click', '#btn_all_absent', function(e){

                $("input:radio[class^=present]").each(function(i) {
                    $(this).attr('checked',false);
                });

                $("input:radio[class^=absent]").each(function(i) {
                    $(this).attr('checked',true);
                });
            });

            $(document).on('click', '#btn_all_present', function(e){

                $("input:radio[class^=absent]").each(function(i) {
                    $(this).attr('checked',false);
                });

                $("input:radio[class^=present]").each(function(i) {
                    $(this).attr('checked',true);
                });
            });

Please suggest me where I am wrong.

A: Your code is working well for this.

<!DOCTYPE html>

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

      <button id="btn_all_present"></button>
      <input type="radio" class="present" />
      <input type="radio" class="present" />
      <input type="radio" class="present" />
      <input type="radio" class="present" />
      <input type="radio" class="present" />
      <input type="radio" class="present" />
      <input type="radio" class="present" />

    <button id="btn_all_absent"></button>

      ABSENT
      <input type="radio" class="absent" />
      <input type="radio" class="absent" />
      <input type="radio" class="absent" />
      <input type="radio" class="absent" />
      <input type="radio" class="absent" />
      <input type="radio" class="absent" />
      <input type="radio" class="absent" />

A: It worked for me like this.
$(document).on('click', '#btn_all_absent', function(e){
                $("input:radio[class^=present]").prop('checked', false);
                $("input:radio[class^=absent]").prop('checked', true);
            });

            $(document).on('click', '#btn_all_present', function(e){
                $("input:radio[class^=absent]").prop('checked', false);
                $("input:radio[class^=present]").prop('checked', true);
            });