text:
Q: Computing 7-day retention numbers in pandas I have a dataframe with two columns--date and id. I'd like to calculate for each date the number of id's on that date which reappear on a later date within 7 days. If I were doing this in postgres, it would look something like:
SELECT df1.date, COUNT(DISTINCT df1.id)
  FROM df df1 INNER JOIN df df2
    ON df1.id = df2.id AND
       df2.date BETWEEN df1.date + 1 AND df1.date + 7
GROUP BY df1.date;

What is problematic for me is how to translate this statement into pandas in a way that is fast and idiomatic and etc.
I've already tried for one-day retention by simply creating a lagged column and merging the original with the lagged dataframe. This certainly works. However, for seven-day retention I would need to create 7 dataframes and merge them together. That's not reasonable, as far as I'm concerned. (Especially because I'd also like to know 30-day numbers.)
(I should also point out that my research led me to https://github.com/pydata/pandas/issues/2996, which indicates a merge behavior that does not work on my install (pandas 0.14.0) which fails with error message TypeError: Argument 'values' has incorrect type (expected numpy.ndarray, got Series). So there appears to be some sort of advanced merge/join behavior which I clearly don't know how to activate.)

A: If I understand you correctly, I think you can do it with a groupby/apply. It's a bit tricky. So I think you have data like the following:
>>> df

        date  id    y
0  2012-01-01   1  0.1
1  2012-01-03   1  0.3
2  2012-01-09   1  0.4
3  2012-01-12   1  0.0
4  2012-01-14   1  0.2
5  2012-01-16   1  0.4
6  2012-01-01   2  0.2
7  2012-01-02   2  0.1
8  2012-01-03   2  0.4
9  2012-01-04   2  0.6
10 2012-01-09   2  0.7
11 2012-01-10   2  0.4

I'm going to create rolling forward count within an 'id' group of the number of times that id shows up in the next 7 days including the current day:
def count_forward7(g):
    # Add column to the datframe so I can set date as the index
    g['foo'] = 1

    # New dataframe with daily frequency, so 7 rows = 7 days
    # If there are no gaps in the dates you don't need to do this
    x = g.set_index('date').resample('D')

    # Do Andy Hayden Method for a forward looking rolling windows
    # reverses the series and then reverses back the answer
    fsum = pd.rolling_sum(x[::-1],window=7,min_periods=0)[::-1]
    return pd.DataFrame(fsum[fsum.index.isin(g.date)].values,index=g.index)

>>> df['f7'] = df.groupby('id')[['date']].apply(count_forward7)
>>> df

        date  id    y  f7
0  2012-01-01   1  0.1   2
1  2012-01-03   1  0.3   2
2  2012-01-09   1  0.4   3
3  2012-01-12   1  0.0   3
4  2012-01-14   1  0.2   2
5  2012-01-16   1  0.4   1
6  2012-01-01   2  0.2   4
7  2012-01-02   2  0.1   3
8  2012-01-03   2  0.4   3
9  2012-01-04   2  0.6   3
10 2012-01-09   2  0.7   2
11 2012-01-10   2  0.4   1

Now if you want to now "calculate for each date the number of id's on that date which reappear on a later date within 7 days" just count for each date where f7 > 1:
>>> df['bool_f77'] = df['f7'] > 1
>>> df.groupby('date')['bool_f77'].sum()

2012-01-01    2
2012-01-02    1
2012-01-03    2
2012-01-04    1
2012-01-09    2
2012-01-10    0
2012-01-12    1
2012-01-14    1
2012-01-16    0

Or Something like the following:
>>> df.query('f7 > 1').groupby('date')['date'].count()

date
2012-01-01    2
2012-01-02    1
2012-01-03    2
2012-01-04    1
2012-01-09    2
2012-01-12    1
2012-01-14    1


text:
Q: ngx-intl-tel-input node module changing the styles I am using ngx-intl-tel-input module in my form to add user phone with country code. Below are the node modules I used to in my Angular 8 project.
ngx-intl-tel-input : ^14.1.0
bootstrap : ^4.4.1
ngx-bootstrap : ^5.6.1

As the node module needs the dependency of both bootstrap and ngx-bootstrap to work properly.
ISSUE:

*

*When I use the both bootstrap module, the ngx-intl-tel-input
component works properly but the css styles for other pages affects
causes the alignment issue.

*If I remove the bootstrap modules, the alignments of other page works
well but in the ngx-intl-tel-input, when I select the country from
the dropdown list, the list not closing.
Could someone help me resolve this issue or any workaround to close the list on selecting the country  from the list.

A: Remove the bootstrap 4.4.1 dependency and add this piece of CSS to emulate the same behaviour:
.iti {
  box-sizing: border-box;

  .iti__flag-container .dropdown-menu.country-dropdown {
    display: none;
  }

  .iti__flag-container.open .dropdown-menu.country-dropdown {
    display: block;
    inset: 100% auto auto 0px;
    transform: translateY(0px);

    position: absolute;
    z-index: 1000;
    float: left;
    min-width: 10rem;
    margin: .125rem 0 0;
    font-size: 1rem;
    color: #212529;
    text-align: left;
    list-style: none;
    background-color: #fff;
    background-clip: padding-box;
    border-radius: .25rem;
  }

  .tooltip {
    display: block;
    pointer-events: none;
    position: absolute;
    z-index: 1070;
    margin: 0;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    font-style: normal;
    font-weight: 400;
    line-height: 1.5;
    text-align: start;
    text-decoration: none;
    text-shadow: none;
    text-transform: none;
    letter-spacing: normal;
    word-break: normal;
    word-spacing: normal;
    white-space: normal;
    line-break: auto;
    font-size: .875rem;

    & .arrow {
      position: absolute;
      display: block;
      width: .8rem;
      height: .4rem;

      &:before {
        position: absolute;
        content: '';
        border-color: transparent;
        border-style: solid;
      }
    }
    &.show {
      opacity: 0.9;
    }
  }

  .bs-tooltip-top {
    padding: .4rem 0;

    &.tooltip .arrow:before {
      top: 0;
      border-width: .4rem .4rem 0;
      border-top-color: #000;
    }

    & .arrow {
      bottom: 0;
    }
  }

  .tooltip-inner {
    max-width: 200px;
    padding: .25rem .5rem;
    color: #fff;
    text-align: center;
    background-color: #000;
    border-radius: .25rem;
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Failed to properly display some elements When I used snipped it didn't quite show it as it is in reality but the idea is that i try to make a div to display something like this..but I failed. I mention that I need to put that image into a div because I take it using php to switch between a red arrow pointed down and this one. But in order to put it into snippet I used a online source. The problem is that I cannot even dispay the dotted line (.target) between them.

.target {
  background-color: transparent;
  border-right: 2px dotted black;
  color: black;
  height: 50px;
  width: 3px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

0

Clicks

vs 0 prev. 7 days

A: The .target takes up space between columns so they won't stay next to each other. You need to set position: absolute for it to take it out of the grid flow. Then position it accordingly. (Mind that inside this snippet the effect won't be visible because the available space is so limited that the default col-xs-12 class won't take over col-sm-6 for columns.

.target {
    background-color: transparent;
    border-right: 2px dotted black;
    color: black;
    height: 50px;
    width: 3px;
    position: absolute;
    left: 50%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

0

Clicks

vs 0 prev. 7 days

A: Make another column for div.target.

0

Clicks

vs 0 prev. 7 days

And Your CSS
.target {
  border-right: 2px dotted black;
  color: black;
  height: 100px;
  width: 1px;
}

See Here Example :  http://codepen.io/ihemant360/pen/wWgoMW


text:
Q: I'm not able to triangulate a regular point cloud I easily tessellated two parametric 3D surfaces (both convex surfaces).
These are the two tessellated parametric surfaces:

Now, my intention is to join both in a single solid. But I'm obtaining this:

enter image description here
I'm using Qhull to create the Delaunay triangulation and it seems that works well for the 1st convex surface, but not for back surface. :(
This is my current code (parts taken from ZivS )
#include "Qhull.h"

using namespace orgQhull;

void myQhull::Qhull::runQhull3D(const pcl::PCLPointCloud2& pointCloud, const char* args)
{
    std::cout << "runQhull vertices" << std::endl;
    numVertices = 0;
    std::stringstream verticesSS;
    m_externalPoints = new PointCoordinates(3,"");  //3 = dimension
    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
    pcl::fromPCLPointCloud2(pointCloud, *cloud);
    std::vector<double> allPoints;

    for (unsigned int i = 0; i < cloud->size(); i++) {
        allPoints.push_back(cloud->at(i).x);
        allPoints.push_back(cloud->at(i).y);
        allPoints.push_back(cloud->at(i).z);
        verticesSS << cloud->at(i).x << " " << cloud->at(i).y << " " << cloud->at(i).z << "\n";
        numVertices++;
    }
    vertices += verticesSS.str();

    m_externalPoints->append(allPoints); //convert to vector<double>
    runQhull(*m_externalPoints, args);
}

void myQhull::Qhull::runQhull(const PointCoordinates &points, const char *qhullCommand2)
{
    std::string triangles;
    std::stringstream ss;
    numSimplices = 0;
    int numFaces = 0;

    std::cout << numVertices << std::endl;
    std::cout << "runQhull facets" << std::endl;

    orgQhull::Qhull qHull(points.comment().c_str(), points.dimension(), points.count(), &*points.coordinates(), qhullCommand2);
    QhullFacetList facets = qHull.facetList();
    for (QhullFacetList::iterator it = facets.begin(); it != facets.end(); ++it)
    {
        if (!(*it).isGood()) continue;
        QhullFacet f = *it;
        QhullVertexSet vSet = f.vertices();
        auto coord = f.hyperplane().coordinates();

        numFaces = vSet.size();

        ss << numFaces;
        for (QhullVertexSet::iterator vIt = vSet.begin(); vIt != vSet.end(); ++vIt)
        {
            QhullVertex v = *vIt;
            QhullPoint p = v.point();
            double * coords = p.coordinates();
            ss <<  " " << p.id() << " ";
        }
        ss << "\n";
        numSimplices++;

    }

    simplices +=  ss.str();
    std::cout << numSimplices << std::endl;

}

void myQhull::Qhull::saveOff(std::string file)
{
    std::cout << "Saving qhull.off" << std::endl;
    std::ofstream offFile;
    offFile.open(file);

    offFile << "OFF\n";
    offFile << numVertices << " " << numSimplices << " 0";
    offFile << vertices;
    offFile << simplices;
    offFile.close();

}

void myQhull::Qhull::run(const pcl::PCLPointCloud2& pointCloud)
{
    Qhull qhull;
    qhull.runQhull3D(pointCloud, "Qt");
    qhull.saveOff("qhull.off");

}

Also, I used greedy_projection from OpenCV but without any success. It is  able only to perform the two surfaces tessellation without joining them.
Any idea why this is happening?

A: Finally I found the solution.
Adding "d" to qhull.runQhull3D(pointCloud, "d Qt") generates the correct Delaunay triangulation for upper and lower surface.
Therefore, as they are regular meshes I, manually, create the edge connecting vertices from the two surfaces.
Thank you.


text:
Q: Script for verifying RDP log on functionality on linux At the moment we're having a few issues with terminal servers being up and running but unable to log on. (This is caused by a third-party application and it's being troubleshooted as we speak)
These issues forces us in to testing the RDP functionality manually way more often then we'd like to, hence why I'd like a script to do it for me.
So, a script that can return true or false with predefined credentials would be a blessing, anyone got any ideas? I could probably build an application myself if someone were to point me in the right direction.


text:
Q: Swift: how can I use an 'AnyClass' variable to define what type is inside an array? The following code should explain what I want to do reasonably clearly. Of course, this produces a compile time error.
What is the correct way to do what the below code intends?
protocol FilterableDataSource {

    var dataClass: AnyClass { get }
    var data: [dataClass.dynamicType] { get }

}

A: You can't use generics with protocols, but if you try, Swift gives you a hint - associated types. Code rarely explains intent clearly, but I'm guessing what you want to achieve is along the lines of...
protocol FilterableDataSource {
    typealias T
    var data: [T] { get }
}

class MyData { }

class MyClass: FilterableDataSource {
    typealias T = MyData
    var data: [MyData] { return [MyData]() }

}

print(MyClass().data.count)

A: I would use AnyObject instead of AnyClass. Then you can just cast it into whatever you want.

A: I believe what you want to do is define a typealias requirement in your protocol.
protocol FilterableDataSource
{
    typealias DataClass : AnyObject
    var data: [DataClass] { get }
}

class PersonDataSource:FilterableDataSource
{
   typealias DataClass = Person
   var data[Person]  = []

}

So instead of requiring your filterable data sources to devine a variable containing the class, you require them to define a typealias for the elements of the data[] variable.  Ideally your data classes have a common ancestor other than AnyObject which you can use as the typealias restriction.


text:
Q: Subset SAM/BAM file in R I have a BAM file with lots of reads.
I can load it into R with scanBam from Rsamtools.
However, I only need a subset of reads.
I have a character vector with the qnames I am interested in.
scanBam returns a list with 1 element which is a list with 13 elements which contain data for all the thousands of reads.
How can I subset this object by qname preserving the structure?
I was not able to find anything in the manual or online.

A: It's probably more convenient to input the data with GenomicAlignments::readGAlignments, including the qname by specifying param=ScanBamParam(what="qname") as an argument. You could then subset with %in%. Here's a more complete example, using one of the ExperimentData packages
library(GenomicAlignments)
library(RNAseqData.HNRNPC.bam.chr14)

fname <- RNAseqData.HNRNPC.bam.chr14_BAMFILES[1]
want <- c("ERR127306.11930623", "ERR127306.24720935",
    "ERR127306.23706011", "ERR127306.22418829", "ERR127306.13372247",
    "ERR127306.20686334", "ERR127306.11412145", "ERR127306.4711647",
    "ERR127306.7479582", "ERR127306.12737243")
aln <- readGAlignments(fname, param=ScanBamParam(what="qname"))
aln[mcols(aln)$qname %in% want]

BAM files are of course big, and the qnames are a big part of that; it often makes sense to iterate through the file in chunks. This is enabled (in the current Rsamtools) with yieldReduce, where one provides BamFile with yieldSize set to a reasonable (e.g., 1M) number of reads, a MAP function to input a chunk of data and process it (e.g., filtering the unwanted reads), an (optional) REDUCE function to concatenate results, and an (optional) DONE function to indicate when the iteration is done. The solution looks like (yieldSize is artificially small, to allow illustration  with the sample data):
bfl <- BamFile(fname, yieldSize=100000)  ## larger, e.g., 1M-5M
MAP <- function(bfl, want) {
    ## message("tick")
    aln <- readGAlignments(bfl, param=ScanBamParam(what="qname"))
    if (length(aln) == 0)
        NA                          # semaphore -- DONE
    else
        aln[mcols(aln)$qname %in% want]
}
REDUCE <- c
DONE <- function(x) identical(x, NA)
result <- yieldReduce(bfl, MAP, REDUCE, DONE, want=want)

One could adopt a similar approach using scanBam, but the data structure (list-of-lists) is more complicated to deal with:
x <- scanBam(fname, param=ScanBamParam(what=c("qname", "pos")))
keep <- lapply(lapply(x, "[[", "qname"), "%in%", want)
result <- Map(function(elts, keep) {
    lapply(elts, "[", keep)
}, x, keep)

This could also be used with yieldReduce.
If you're interested in creating a new bam file with the filtered reads, then
filter_factory <- function(want) {
    list(KeepQname = function(x) x$qname %in% want)
}
filter <- FilterRules(filter_factory(want))
dest <- filterBam(fname, tempfile(), filter=filter,
                  param=ScanBamParam(what="qname"))
readGAlignments(dest)

A: I ended up using subset(DataFrame(scanBam(bam_file)[[1]]),qname %in% qname_vector).
This does not keep the exact same structure (list of list) but all the information is kept and easily accessible.


text:
Q: Outlook javascript add-in does not run when email is encrypted I'm providing an add-in in Outlook on the Web, but I'm seeing unexpected behavior when I encrypt my email.
Details are described below.
■Expected behavior
The result dialog is displayed when the "displayDialogAsync" method is executed.
■Current behavior
The result dialog is not displayed even though the "displayDialogAsync" method is executed,and an email was sent.
■Steps to reproduce

*

*Download the official sample.
  https://github.com/OfficeDev/Outlook-Add-in-On-Send/blob/master/outlook-add-in-on-send/Contoso%20Message%20Body%20Checker.xml/

*Rewrite the contents of the "app.js" file to the source code of  following"index.js"

*Run the "yarn start" command in your local environment.

*Install the add-in with the manifest file.

*Write an Email.

*Click "Encrypt".

*Click "Send" button.

This problem always occurs.
Please tell me how to solve this problem.
I share this result on video and source code.
■video
https://drive.google.com/file/d/1h3oJSZxObmOXwBw5Z1rjG92U36d9zSFz/view?usp=sharing
■source code
index.js
/*
 * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
 * See LICENSE in the project root for license information.
 */

var mailboxItem;

Office.initialize = function (reason) {
    mailboxItem = Office.context.mailbox.item;
}

// Entry point for Contoso Message Body Checker add-in before send is allowed.
// <param name="event">MessageSend event is automatically passed by BlockOnSend code to the function specified in the manifest.</param>
function validateBody(event) {
  Office.context.ui.displayDialogAsync(
  "https://localhost:3000/index.html",
    {
      height: 65,
      width: 40,
      displayInIframe: true,
      asyncContext: event,
    },
      (asyncResult) => {
        asyncResult.value.addEventHandler(Office.EventType.DialogEventReceived,
        (processMessage) => {
          asyncResult.value.close()
          asyncResult.asyncContext.completed({ allowEvent: false })
        }
      )
    }
  )
}


text:
Q: How can I navigate to a path with percentage sign in react-router? I am trying to navigate to a page which may contain a percentage (%) sign in the url. e.g "www.domain.com/edit/name%"
if (some condition is met then redirect) {
  let encodedString = encodeURIComponent(this.state.identifier);

  console.log(encodedString);

  return <Redirect push to={`/edit/${encodedString}`} />
}

and in the component we redirected to:
if (params && params.identifier) {
  this.setState({
    identifier: decodeURI(params.identifier)
  });
}

From the console.log(); I can clearly see that encodedString provided that this.state.identifier is name% is name%25. However, when the condition for redirecting is met, I immediately get this error URIError: Pathname "/edit/name%" could not be decoded. This is likely caused by an invalid percent-encoding.
Is there a way for me to redirect to the uri in the case that the /:identifier has a percentage sign?


text:
Q: memcpy complex struct in a buffer i'm relatively newer in C and i have some problems to memcpy a struct in a buffer;
I have this struct:
`typedef struct {
        uint8_t size_of_payload;
        uint8_t command;
        unsigned char* payload;

}__attribute__((packed)) mystruct``

and i want to copy in a tx_buffer[SIZE] the values of this struct, including the value pointed by payload.
payload point to an array of char with a size equals to the size_of_payload .
memcpy(&tx_buffer,&mystruct,sizeof(mystruct));

copies only the value of payload address.
It is possible do this?

A: Well it isn't possible to do it in one simple call. You will have to do it 'manually'.
memcpy can only copy one memory region to an other. Your source memory region isn't structured the way you want it at the destination, so will have to do it manually.
Let's first copy the first two fields
memcpy(&tx_buffer+0*sizeof(uint8_t),&mystruct.size_of_payload, 1*sizeof(uint8_t));
memcpy(&tx_buffer+1*sizeof(uint8_t),&mystruct.command, 1*sizeof(uint8_t));

What we do here, is copy the first element to position zero of tx_buffer, and the second to position 1 byte after that.
For the string we don't know the length. We could find it and do a memcpy, but there is a convenient alternative:
strcpy(&tx_buffer+2*sizeof(uint8_t), mystruct.payload)

A: This whole setup seems a bit strange to me. Why the need to "flatten" the structure? Or if the need is justified, why was this structure layout chosen? Anyway, will try to exemplify (what I consider) the easiest way (which from other criteria wouldn't be the best).
Since the structure contains a member which is a pointer (a level of indirection), it can't be done in one go. In this particular case (as the pointer is the last member), the approach is to:

*

*Copy the contents of the struct till the pointer member

*Copy the contents of the dereferenced pointer member (based on the size member)

Note that for more complex structures, with alternating pointer and regular members, you'd need one memcpy call for the 1st member(s) of the same type + one additional call for each consecutive member types (normal -> pointer, pointer -> normal, pointer -> pointer).
code00.c
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>

#define BUF_DIM 0xFF  // Make sure it's large enough

typedef struct {
    uint8_t size_of_payload;
    uint8_t command;
    unsigned char *payload;
} __attribute__((packed)) Data;

size_t dataSize(const Data *pData)
{
    if (pData == NULL)
        return 0;
    return offsetof(Data, payload) + pData->size_of_payload;
}

size_t copyData(const Data *pData, uint8_t *pBuf)
{
    size_t sz = dataSize(pData);
    if (sz == 0)
        return 0;
    size_t ofs = offsetof(Data, payload);
    memcpy(pBuf, pData, ofs);
    memcpy(pBuf + ofs, pData->payload, pData->size_of_payload);
    return sz;
}

int main()
{
    unsigned char array[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'c', 'd' };
    Data data = { sizeof(array), 123, array };
    uint8_t buf[BUF_DIM] = { 0 };
    copyData(&data, buf);
    size_t ds = dataSize(&data);
    printf("Size: %ld\nBuf:\n", ds);
    for (size_t i = 0; i < ds; ++i)
        printf("0x%02X(%c) ", buf[i], buf[i]);

    printf("\nDone.\n");
    return 0;
}

Output:

(qaic-env) [cfati@cfati-5510-0:/mnt/e/Work/Dev/StackOverflow/q071451221]> ~/sopr.sh
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[064bit prompt]> ls
main00.c
[064bit prompt]> gcc -o main00.exe main00.c
[064bit prompt]> ./main00.exe
Size: 16
Buf:
0x0E() 0x7B({) 0x30(0) 0x31(1) 0x32(2) 0x33(3) 0x34(4) 0x35(5) 0x36(6) 0x37(7) 0x38(8) 0x39(9) 0x41(A) 0x42(B) 0x63(c) 0x64(d)
Done.

A: Use a flexible array member.  You'll have much simpler code:
typedef struct {
        uint8_t size_of_payload;
        uint8_t command;
        uint8_t payload[];
} mystruct;

Allocate a structure:
mystruct *allocMyStruct( uint_8 command, uint8_t size, uint8_t *payload )
{
    mystruct *m = malloc( sizeof( *m ) + size );
    m->size_of_payload = size;
    m->command = command;
    memcpy( m->payload, payload, size );

   return( m )
}

Copy:
mystruct *m = ...
 .
 .
 .
// copy *ALL* the fields and the payload
memcpy( txBuffer, m, sizeof( *m ) + m->size_of_payload );

Free a structure:
mystruct *m = ...
 .
 .
 .
free( m );

The only drawback to a flexible array member is you can't allocate them as local or static variables.
You can't do
mystruct m;

when you're using flexible array members.
But compared to having a uint_t *payload pointer in the structure that pretty much has to be allocated dynamically, in reality there's no flexibility lost.
There's no reason not to use a flexible array member in a case like this.


text:
Q: How to draw a line with arrow using touch in unity? I was looking to draw a line which contains an arrow mark.How to show it with arrow on head is a problem.Is it possible to do without line renderer?
Attaching a link here to show the drawing of line on screen.Draw Arrow.If I swipe to the right the arrow head points to right with hand held on screen I can change my position of arrow head.Once I release the arrow position is fixed.
I have worked out to draw a line between two points.Code given below.
if (Input.GetTouch(0).phase == TouchPhase.Began)
    {

        //--Clearing the list and adding first touch to list--
        fingerPositions.Clear();
        fingerPositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition));
        Debug.Log("Made first touch");
        click = true;
    }

    if (Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        isSwiping = true;

    }

    if (Input.GetTouch(0).phase == TouchPhase.Ended && isSwiping == true)
    {
        //--Adding the last touch to the list--
        fingerPositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition));
        //currenline is GameObject
        currenline = Instantiate(linePrefab, fingerPositions[0], Quaternion.identity);
        getAllLines.Add(currenline);
        //NewLine is a LineRenderer
        NewLine = currenline.GetComponent<LineRenderer>();

        Debug.Log("Finger count = "+fingerPositions.Count);

        NewLine.SetPosition(0, fingerPositions[0]);
        NewLine.SetPosition(1, fingerPositions[1]);

        isSwiping = false;
    }

A: In you line prefab add a triangle sprite which is anchored to the end edge of the prefab. If it's a child it'll keep it's orientation so you just have to create the line and arrow will follow.


text:
Q: Change tooltip color in oj-chart The oj-chart documentation for tooltipTemplate says, that the parentElement property of $current can be used to change the tooltip border or background color: https://www.oracle.com/webfolder/technetwork/jet/jsdocs/oj.ojChart.html#tooltipTemplate
However, I can't find any example of this in the documentation. Where in a tooltipTemplate can this be done?


text:
Q: How to upload a file to a slack channel using a bot I have a slack bot and the token starting with xoxb is used to upload a file to a channel.
I am using below format
curl -F token="${SLACK_TOKEN}" -F file=e2e.sh -F channel="${SLACK_CHANNEL}" -F  as_user=true https://slack.com/api/files.upload

This throws
{"ok":false,"error":"no_file_data"}

A: You are missing the @ in your file=e2e.sh argument to let curl know you want to transmit a file. The following should do the trick:
curl \
  -F token="${SLACK_TOKEN}" \
  -F file=@e2e.sh \
  -F channel="${SLACK_CHANNEL}" \
  -F as_user=true \
  https://slack.com/api/files.upload

p.s. Breaking a long curl into multiple lines can help you see things more clearly ;)


text:
Q: Use a variable reference "inside" another variable I'm sure it is relatively simple, I just don't know how to do it.
#!/usr/bin/ksh
set `iostat`
myvar=6

I want to something like echo ${$myvar} which i want interpreted as ${$myvar} -> ${6} -> value

A: You can do this with eval, built-in to many fine shells, including ksh:
#!/usr/bin/ksh
set $(iostat)
myvar=6
eval "echo \${$myvar}"

The trick is to double-quote the string you feed to eval so that $myvar gets substituted with "6", and to backslash the outer dollar-sign, so that eval gets a string "$6".
I got "%user" for the output, but I tried it on a multi-processor RHEL machine.

A: Indirect variable reference
Modern advanced shells have a method to reference the value of a variable whose name is stored in another variable. Unfortunately the method differs between ksh, bash and zsh.
In mksh ≥R39b, you can make myvar a nameref:
typeset -n myvar=6
echo "$myvar"

This doesn't work in ATT ksh93 because it doesn't support namerefs to positional parameters. In the case where you have a variable containing a variable name, you can use this method.
foo=bar
typeset -n myvar=foo
echo "$myvar"  # prints bar

In bash ≥2.0, you can write
echo "${!myvar}"

In zsh, you can write
echo ${(P)myvar}

In older shells, including ksh88 and pdksh, your only recourse when you have a variable containing another variable name and want to use the value of this variable eval, as explained by Bruce Ediger. This solution works in any Bourne/POSIX shell.
eval "value=\${$myvar}"
echo "$value"

Using an array
This is the best method here: it's simpler and more portable.
For your use case, in any shell with arrays (all ksh variants, bash ≥2.0, zsh), you can assign to an array variable and take the element you wish. Beware that ksh and bash arrays start numbering at 0, but zsh starts at 1 unless you issue setopt ksh_arrays or emulate ksh.
set -A iostat -- $(iostat)
echo "${iostat[5]}"

If you want to copy the positional parameters to an array variable a:
set -A a -- "$@"

In ksh93, mksh ≥R39b, bash ≥2.0 and zsh, you can use the array assignment syntax:
iostat=($(iostat))
echo "${iostat[5]}"

A: As indicated by Gilles (who provided the bash part of the answer), also not invalidating Bruce Ediger's (on how to do it portably with eval), here's how to do it with nameref in recent mksh (and AT&T ksh93, except – as @Gilles commented – namerefs cannot refer to positional parameters in AT&T ksh, only to named parameters):
#!/bin/mksh
set -- $(iostat)
nameref myvar=6
echo $myvar

Added the -- after set for improved resistence, too.

A: Another use of arrays
Haven't used either ksh or any variant for some time, so I'm not sure if ksh(or bash) has a similar capability.  My primary shell is zsh.  I use arrays when handling output from commands like iostat because they produce multiple lines, and not all lines are the same format/length.
#! /bin/zsh
IOStatOutput=("${(@f)$(iostat)}") # Produces one element per line

The above also bypasses the use of positional parameters. Now, if you want to generate, say, an array of devices:
for Element in {7..${#IOStatOutput}} # Devices listed in elements 7 thru the last
do
    DevList+=( ${${=IOStatOutput[Element]}[1]} )
done

I find smaller chunks much easier to handle. You may or may not need to use indirect variable reference, depending on your code.  Knowing how it works is still a good thing to know.  I use it myself.


text:
Q: excel vba copy data from query to other sheet Hello I got this data in excel (see picture), the data is imported from a .csv file. I want to exctract all the rows with the same name (Z-column) to diffrent sheets. for example: new sheet 'P7' contains all the rows where Z = P7. The table can be variable in length and I dont know how many points (P7,P6) there are going to be in the table. Any help appreciated!

A: I wouldn't normally look at this because you haven't shown what code you've tried so far.  Having said that, it's an interesting little problem that I looked at as a coding exercise.  The following uses a dictionary to get unique values from column D and uses the keys to both create new sheets and set the filter to copy the data.  Let me know how it goes.
Option Explicit
Sub test()
Dim d As Object, x, LngRow As Long, i As Long
Dim ws1 As Worksheet, ws2 As Worksheet

Set ws1 = Sheets("tempoary_csvData")
Set d = CreateObject("scripting.dictionary")

x = Application.Transpose(Range("D5", Cells(Rows.Count, "D").End(xlUp)))

For LngRow = 1 To UBound(x, 1)
    d(x(LngRow)) = 1
Next

For Each x In d.Keys
    If x <> "" Then
        With ThisWorkbook
                Set ws2 = .Sheets.Add(After:=.Sheets(.Sheets.Count))
                For i = 1 To Worksheets.Count
                    If Worksheets(i).Name = x Then
                        MsgBox "The sheet " & x & " already exists - macro stopped"
                        Exit Sub
                    End If
                Next i
            ws2.Name = x
        End With

        With ws1.Cells(4, 1).CurrentRegion
            .AutoFilter 4, x
            .Copy Sheets(x).Cells(1, 1)
        End With
    End If
Next x

ws1.AutoFilter.ShowAllData

End Sub


text:
Q: How to add multiple google cloud datasources using spring I have two sql datasources already working locally, but I want to deploy it to two google cloud app-engines (I have it working with one right now). What do I need to change in my application-properties to define a second google instance/database?
I already have links set up in my pom for connections called sql.instance.second and sql.database.second. I don't know how to define spring.cloud.gcp.sql... for a second app-engine. Another option I have is to not run it locally at all but just define a cloud instance when I'm defining the datasources and then define a driver for each, but I'm not too sure how to do that either.
spring.cloud.gcp.sql.instance-connection-name=@sql.instance.first@
spring.cloud.gcp.sql.database-name=@sql.database.first@

primary.datasource.jdbc-url = @mysql.host.first@
primary.datasource.username = @mysql.user.first@
primary.datasource.password = @mysql.pass.first@

secondary.datasource.jdbc-url = @mysql.host.second@
secondary.datasource.username = @mysql.user.second@
secondary.datasource.password = @mysql.pass.second@

A: I was able to get it working by getting rid of this dependency first
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-gcp-starter-sql-mysql</artifactId>
</dependency>

Then changing my application.properties to this
primary.datasource.driverClassName=com.mysql.jdbc.GoogleDriver
primary.datasource.jdbc-url = @mysql.host.first@
primary.datasource.username = @mysql.user.first@
primary.datasource.password = @mysql.pass.first@

secondary.datasource.driverClassName=com.mysql.jdbc.GoogleDriver
secondary.datasource.jdbc-url = @mysql.host.second@
secondary.datasource.username = @mysql.user.second@
secondary.datasource.password = @mysql.pass.second@

And deleting
spring.cloud.gcp.sql.instance-connection-name=@sql.instance.first@
spring.cloud.gcp.sql.database-name=@sql.database.first@

Change the url of @mysql.host.first@ in my pom.xml to
<mysql.host.first>jdbc:google:mysql:...</mysql.host.first>


text:
Q: Scope issues in angular modal popup I have a modal popup on my page. The modal popup use bootstrap angular library.
Inside the body of the modal I have a text box with ng-model attribute, and on the press of ok button I want to use that text box value.
<input type="text" data-ng-model="ProjectName" class="form-control"  tab-index="1" required />

But when I log the value to console, I dont get that value.
$scope.ok = function () {
   console.log($scope.ProjectName);
  };

I have created a plunkr link for debugging this. Please advice.

A: You have a number of issues.
Firstly, you didn't define the scope property on the modal. By default, the scope is set as  child of the $rootScope.
 var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalInstanceCtrl,
      size: size,
      scope: $scope,
      resolve: {
      }
    });

Secondly, you should set the ng-model to be the property of an object, otherwise angular will automatically create the property for you on the child scope.
Controller
var ModalDemoCtrl = function ($scope, $modal, $log) {
  $scope.model = {};
   ...
}

Markup
<div class="modal-body">
    <input type="text" ng-model="model.ProjectName" />
</div>

See this plunkr for working sample: http://plnkr.co/tbVHl27D2pXia19kOjob


text:
Q: DJANGO как сделать запрос к двум таблицам/моделям, не связанных внешними/foreign ключами Как возможно вывести в HTML сводные данные в одну таблицу из двух таблиц/моделей данных  не связанных внешними ключами (Наподобие в SQL: FROM po INNER JOIN table_1 ON table_1.id= table_2.id)
class Teacher(models.Model):
    people_id = models.IntegerField()     # --- > поле совпадает с Obrazovanie
    name = models.CharField(max_length=80)
    age = models.IntegerField()

    def __str__(self):
        return self.name

class Obrazovanie(models.Model):
    people_id = models.IntegerField()     # --- > поле совпадает с Teacher
    name = models.CharField(max_length=40)
    second_name = models.CharField(max_length=40)
    name_university = models.CharField(max_length=40)
    date_birth = models.DateField(null=True)

    def __str__(self):
        return self.name

Как сделать запрос/sql в (Django Model) одновременно к двум моделям данных ???

A: ---> Пример sql-запроса напрямую к базе данных/таблице без использования моделей данных
from django.db import connection

with connection.cursor() as cursor:
    cursor.execute("SELECT * from teacher и тд")
    row = cursor.fetchall()
    logger.info(f"{row=}, {type(row)}")


text:
Q: Pass a `chr` type argument and update the content of a nested function to return in R? For a nested function such as
fun_parent <- function(var) {
  fun_child <- function(x) {
    x + var
  }
  return(fun_child)
}

How can I customize the content of the returned function fun_child based on the input var?
For example,
test <- fun_parent(var = "y")
print(test)

Desirable output:
function(x) {
  x + y
  }
<environment: xxxxxx>

Actual (undesirable) output:
function(x) {
    x + var
  }
<environment: 0x7f7f20126b70>

Any help would be greatly appreciated!
Edit: As you may have guessed, the question described above is a simplified version of the actual question I had. The comment by Dan Adams prompted me to redefine my question. Then I realized that it would be hard to explain what I was really looking for without providing some context. So here is another reproducible example, still greatly simplified from my actual question, but with extra information.
Say I want to apply a model to a group of datasets using purrr::map(), and to construct the model based on user input:
set.seed(1234)

df_demo <- data.frame(
  x1 = rnorm(100),
  x2 = rnorm(100),
  x3 = rnorm(100),
  y = rnorm(100),
  sex = factor(rep(c("f", "m"), each = 50))
  )

func <- function(var) {
  mod <- function(data) {
    lm(y ~ var, data = data) # var is supplied by users
  }

  output <- df_demo |>
    dplyr::group_by(group) |>
    tidyr::nest() |>
    dplyr::mutate(
      model = purrr::map(data, mod),
      tidy = purrr::map(model, broom::tidy)
    ) |>
    tidyr::unnest(tidy)

  return(output)
}

test <- func(var = "x1")

I also tried a variation of the version above:
df_demo <- ...

func <- function(var) {
  output <- df_demo |>
    dplyr::group_by(group) |>
    tidyr::nest() |>
    dplyr::mutate(model = purrr::map(data,
        function(data, ...) {
          lm(y ~ var, data = data)
        }),
      tidy = purrr::map(model, broom::tidy)
      ) |>
    tidyr::unnest(tidy)

  return(output)
}
test <- func(var = "x1")

Both versions failed to achieve the result I wanted.
An error was returned instead.
At first I thought it was because the input var = "x1" could not be passed into fun or into the nested function mod. That's when I posted the original question at the beginning of this post.
After seeing Dan Adams' comment, I tried to approach the question differently. Instead of supplying var = "x1", I turned the entire formula into a parameter, like this:
# func <- function(var) {
func <- function(formula) {
  output <- df_demo |>
    dplyr::group_by(group) |>
    tidyr::nest() |>
    dplyr::mutate(model = purrr::map(data,
        function(data, ...) {
          # lm(y ~ var, data = data)
          lm(formula, data = data)
        }),
      tidy = purrr::map(model, broom::tidy)
      ) |>
    tidyr::unnest(tidy)
  return(output)
}
# test <- func(var = "x1")
test <- func(formula = y ~ x1)

Lo & Behold, this worked!
> test
# A tibble: 4 × 8
# Groups:   group [2]
  group data              model  term        estimate std.error statistic p.value
  <fct> <list>            <list> <chr>          <dbl>     <dbl>     <dbl>   <dbl>
1 f     <tibble [50 × 6]> <lm>   (Intercept)   0.0675     0.170     0.398 0.692
2 f     <tibble [50 × 6]> <lm>   x1            0.0763     0.160     0.477 0.636
3 m     <tibble [50 × 6]> <lm>   (Intercept)  -0.106      0.124    -0.855 0.397
4 m     <tibble [50 × 6]> <lm>   x1            0.384      0.128     3.01  0.00419

This solution is not quite the same as the original one I had envisioned. However, it does seem more straightforward.
BTW, I am really overwhelmed (in a good way) by how quickly people responded to my original question with some brilliant ideas. I must admit that some of them seemed way over my head. Nevertheless, I am going to carefully review them and try my best to select one as the solution to my original question.

A: If you need to pull a value from the object list based on a name given as a character, then the get function suffices.
 fun_parent <- function(var) {
     force(var)
     fun_child <- function(x) {
         x + get(var)
     }
     return(fun_child)
 }
 test <- fun_parent(var = "y")
 print(test)

#function(x) {
#        x + get(var)
#    }
#
#<environment: 0x5654f87a1ae8>
Y=6
test(4)
#[1] 10
z=10

test <- fun_parent(var = "z")
print(test)
#function(x) {
#        x + get(var)
#   }
#<bytecode: 0x5654f7eac430>
#<environment: 0x5654f7637bb8>
test(4)
#[1] 14

The value of z is not stored in the test function, only the name is.
 z = 20
 test(4)
[1] 24

But is you want to see how that happens you need to look at the environment itself since the body was not evaluated:
> test
function(x) {
        x + get(var)
    }
<bytecode: 0x5654f7eac430>
<environment: 0x5654f7637bb8>
> environment(test)$var
[1] "z"

I was a bit surprised that substituting "x" for the value of var succeeded, but I wasn't suprised that using an object name that I knew was in my workspace did work:
> environment(test)$var <- "x"
> test(4)
[1] 8
> x     # only existed in the parameter list but was stored in the environment
Error: object 'x' not found
> environment(test)$var <- "y"
> test(4)
[1] 10

user554330
correctly points out that the name of the object to which var points could be changed. If you wnat to lock in the name you would need to evaluate the "gotten" name:
fun_parent <- function(var) {
     fun_child <- function(x) {
         x + force(get(var))
     }
     return(fun_child)
 }
 test <- fun_parent(var = "y")
 print(test)
#function(x) {
#       x + force(get(var))
#    }
#<environment: 0x565514c4ae38>
 test(4)
#[1] 10
 fy <-  fun_parent(var = "y")
 fz <-  fun_parent(var = "z")
 y=10
 z=20
 fy(4)
#[1] 14
 fz(4)
#[1] 24
 ls( environment(fy) )
#[1] "fun_child" "var"
 environment(fy)$var
#[1] "y"
  environment(fz)$var
#[1] "z"

A: I asked a related but not identical question here. Here are two options using bquote:
f <- function(varname) {
  removeSource(eval(bquote(function(x) x + .(as.name(varname)))))
}
f("y")

function (x)
x + y
<environment: 0x1128976b0>

op <- options(keep.source = FALSE)
g <- function(varname) {
  eval(bquote(function(x) x + .(as.name(varname))))
}
options(op)
g("y")

function (x)
x + y
<environment: 0x110491580>


text:
Q: Two forms and one viewmodel I have two forms in one page. Both have there own properties and there own submit actions, but have some of properties in common in both forms.
Is there a way to build a view with two forms using a single viewmodel that share properties to both forms in the View?
Actually I have the fields duplicated and I have to duplicate the change of the values in both fields using jquery.
Thanks.

A: you can use HtmlPrefix to achieve this.

*

*I have created a model as
public class TestModel
{
  [Required]
  public int Id { get; set; }
  [Required]
  public string Name { get; set; }
}

*In Controller we need to have one GetMethod but two post method for each form, but with different BindPrefix
public ActionResult TestLoad()
{
    TestModel model = new TestModel();
    return View(model);
}

public ActionResult TestA([Bind(Prefix = "A")]TestModel model)
{
    return View("TestLoad",model);
}
public ActionResult TestB([Bind(Prefix="B")]TestModel model)
{
    return View("TestLoad",model);
}

*In the view. Here also we need to Specify binding prefix

    @{Html.ViewData.TemplateInfo.HtmlFieldPrefix="A";}
    @{Html.RenderPartial("PartialA");}

    @{Html.ViewData.TemplateInfo.HtmlFieldPrefix="B";}
    @{Html.RenderPartial("PartialB");}

*Both partial view are exactly same , except that they post data to different actions (as defined in controller)

*Now if you run the project you should get appropriate output.


text:
Q: Transfer data between objects of same structure but different type I have two derived classes.
public Class A : BaseClass
{
    public static somecomplextype Criteria { get; set; }
}

public Class B : BaseClass
{
    public static somecomplextype Criteria { get; set; }
}

I have only access to derived classes and not the base class.
Now I have a another class
public Class SomeClass
{
   public SomeClass()
   {
       //I need a logic for the below to happen...
       B.Criteria = (B) A.Criteria //throws invalid cast exception
   }
}

The problem is transferring the data between A.Criteria to B.Criteria...
Since the cast throws exception..
I wanted to know if there is another way.

A: The problem I specified is rather simple. I just wanted to transfer the data from one derived type object to another derived type object of same base since I don't have access to base class.
Since the object was big, I was required to write a long data transfer logic for the data transfer between them.
So I was looking for a simple solution like a cast(which won't work in my case).
I have found a roundabout way to transfer data between them. Pasting the code here FWIW
if A.Criteria and B.Criteria are the objects, I wanted data of A to be passed to B. After all the suggestions above. I came up with a round about way.
string json = JsonConvert.SerializeObject(A.Criteria);
return JsonConvert.DeserializeObject(json, typeof(B.Criteria)) as B.Criteria;


text:
Q: Is it possible to Restrict Image size and upload only of certain size I am uploading file using the above code, the code works fine .
My question is, is it possible to restrict image to 75 kb only during image upload ??
In case it exceeds 75 kb, I dont want to throw an exception, but continue upload with what I got
private void writeToFile(InputStream uploadedInputStream,String uploadedFileLocation) {
    try {
        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
        int read = 0;
        byte[] bytes = new byte[1024];
        out = new FileOutputStream(new File(uploadedFileLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

A: public final static int MAX_SIZE = 75000;

private void writeToFile(InputStream uploadedInputStream,String uploadedFileLocation) {
    try {
        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
        int read = 0;
        int size = 0;
        byte[] bytes = new byte[1024];
        out = new FileOutputStream(new File(uploadedFileLocation));
        while (size < MAX_SIZE && (read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
            size += read;
        }
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

A: There are various way to do it . if you are Using Struts then Edit Strtus.xmland Use where value Denotes File Size limit
<constant name="struts.multipart.maxSize" value="30000000" />

Servlet
@MultipartConfig(
location="/tmp",
fileSizeThreshold=1024*1024,    // 1 MB
maxFileSize=1024*1024*5,        // 5 MB
maxRequestSize=1024*1024*5*5    // 25 MB
)

or
<max-file-size>20848820</max-file-size>

Java
final static int MAX_SIZE = 50000;//Max Limit of File

A: You can use below code to calculate file size in kb.
 long fileSize = file.length()/1024;
 System.out.println("fileSize="+fileSize);
 if(fileSize==75){

  }else{

    }


text:
Q: Standalone GeoWebCache drop some parts of features in tiles I have a local GeoServer with standalone GeoWebCache to serve vector tiles in PBF file format. The layer displays country borders in the world but the problem is in different tiles some parts of polygons missed and have not shown. You can see the difference between the two following images.

The geoserver logs these line but I cannot find any layer group named web:
2020-05-05 17:14:22,133 DEBUG [filter.GeoServerSecurityContextPersistenceFilter$1] - SecurityContextHolder now cleared, as request processing completed
2020-05-05 17:14:36,404 DEBUG [geoserver.wps] - Removing statuses matching [[[ NOT [ completionTime IS NULL ] ] AND [ completionTime Before 2020-05-05T17:09Z ]] AND [[ NOT [ lastUpdated IS NULL ] ] AND [ lastUpdated Before 2020-05-05T17:09Z ]]]
2020-05-05 17:15:15,606 DEBUG [security.IncludeQueryStringAntPathRequestMatcher] - Checking match of request : 'Path: /web/wicket/bookmarkable/org.geoserver.web.admin.logpage, QueryString: filter=false'; against '/web/'
2020-05-05 17:15:15,606 DEBUG [security.IncludeQueryStringAntPathRequestMatcher] - Matched Path: /web/wicket/bookmarkable/org.geoserver.web.admin.logpage, QueryString: filter=false with /web/
2020-05-05 17:15:15,609 DEBUG [geoserver.ows] - Could not find a layer group named web
2020-05-05 17:15:15,609 DEBUG [geoserver.ows] - Could not find a layer group named web
2020-05-05 17:15:15,609 DEBUG [geoserver.ows] - Could not find a layer group named web
2020-05-05 17:15:15,609 DEBUG [geoserver.ows] - Could not find a layer group named web
2020-05-05 17:15:15,610 DEBUG [org.geoserver] - Thread 142 locking in mode READ
2020-05-05 17:15:15,610 DEBUG [org.geoserver] - Thread 142 got the lock in mode READ


text:
Q: How to measure correlation and do heatmap for a dataset having both categorical and numerical variables. Target is categorical dataset for sexual violence in Bangladesh
How to measure correlation and get heatmap for such type of dataset having both numerical nad categorical variable? Target is categorical variable. Please provide me the necessary code.


text:
Q: ajax post to fit webApi signature How to write jquery ajax post (or put) to match the following .Net webApi signature:
    public bool PostValue(Guid id, string Field, string Value)
    {
        return true;
    }

 $.ajax({
            url: "/api/item/PostValue/" + id,
            contentType: "text/json",
            dataType: "json",
            type: "POST",
            data: {
                'Field': 'bar',
                'Value': 'nolibri'
            },
            success: function (result) {
                //
            }
        });

A: Since your Ajax request is a post statement you have to add a [HttpPost] header to your method
[HttpPost]
public bool PostValue(Guid id, string Field, string Value)
{
   return true;
}

EDIT:
Also you have to edit your data in your ajax request:
$.ajax({
url: "/api/item/PostValue/",
contentType: "text/json",
dataType: "json",
type: "POST",
data: {
   'id' : id
   'Field': 'bar',
   'Value': 'nolibri'
},
success: function (result) {
   //
   }
});


text:
Q: Does SABRE provide REST API for Air Seat booking and ticket? Currently I am working on WEB Application that using SABRE REST API calls to search and book a flight. At SABRE DEV STUDIO I visit the REST and SOAP API Calls section.
I am confuse about SABRE REST API calls because there are no any reservation/booking REST API call, how can I book seat using REST API. Same for the ticketing.

A: REST API is still a new product so not every functionality is offered at the moment.
You can reserve seats and issue tickets with SOAP API.


text:
Q: How to select multiple items from a table based on certain cumulative amount? I have a table name "foods", there have various foods with different calories. For example bellow:
Table: foods
id    name      calories
-----------------------
1     beef      200
2     tomato    400
3     carrot    500
4     nuts      800

what I want: I want to select multiple foods from the table based on calorie amount when the sum of callories reach to a certain amount, I want to stop query there and echo the result. For example, when I will want 600 calories, result will show for the first two food 200+400=600. when I will want calorie limit will be 1000, it will take any two or more foods those calories amount reach to 1000 or near 1000.
I have tried with following code to make it ; but it does not work.
SELECT * FROM foods WHERE SUM(calories)=1000

A: You can use a variable in order to calculate cumulative sum:
SELECT id, name, calories
FROM (
   SELECT id, name, calories,
          @cumSum:= @cumSum + calories AS cumSum
   FROM foods, (SELECT @cumSum:=0) var
   ORDER BY id ) t
WHERE cumSum <= 600

The subquery calculates the cumulative sum and stores its value in @cumSum variable. The outer query can then use calculated column cumSum to filter out results having a cumulative sum greater than 600.
Output:
id  name    calories
----------------------
1   beef    200
2   tomato  400

Fiddle Demo here


text:
Q: Create variadic template function to measure and execute other function I am currently trying to implement a function that will take as input any other function and a valid set of input values for that function and return the result of the function as well as printing how long it took to execute it.
Here is what I have until now:
template<typename T, typename... Tail>

T measureAndExecute(const function<T(Tail...)> f, Tail... tail) {
    high_resolution_clock::time_point time1 = high_resolution_clock::now();
    T res = f(tail...);
    high_resolution_clock::time_point time2 = high_resolution_clock::now();
    auto duration = duration_cast<milliseconds>(time2 - time1).count();
    cout << duration << " milliseconds" << endl;
    return res;
}

And I try to run it with something like this:
int res = measureAndExecute(function<int(vector<int>&, vector<bool>&, unsigned long)> fibonacci, terms, calculated, n-1);

Which is a function to find a term in the Fibonacci series.
When I try to run it I get the following error:
error: expected '(' for function-style cast or type construction

Can somebody please give me a way forward or ideas on how to proceed?

A: This is a very naive way to do benchmarking. I suggest you take a look here for more advanced stuff. Nevertheless if you wanna stick to it you should change to:
template<typename F, typename... Tail>
auto measureAndExecute(F f, Tail&&... tail) -> typename std::result_of<F(Tail&&...)>::type {
  std::chrono::high_resolution_clock::time_point time1 = std::chrono::high_resolution_clock::now();
  auto res = f(std::forward<Tail>(tail)...);
  std::chrono::high_resolution_clock::time_point time2 = std::chrono::high_resolution_clock::now();
  auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(time2 - time1).count();
  std::cout << duration << " milliseconds" << std::endl;
  return res;
}

A: I agree with @101010 that this is a unusual way of benchmarking a software.
That said, here is a solution that works also with functions havingvoid return type (the example  in the question wouldn't have worked with them):
#include<type_traits>
#include<iostream>

struct Check {
    Check(): time1{std::chrono::high_resolution_clock::now()} {}

    ~Check() {
        std::chrono::high_resolution_clock::time_point time2 = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(time2 - time1).count();
        std::cout << duration << " milliseconds" << std::endl;
    }

    std::chrono::high_resolution_clock::time_point time1;
};

template<typename F, typename... Tail>
typename std::result_of<F(Tail&&...)>::type measureAndExecute(F f, Tail&&... tail) {
    Check check;
    (void)check;
    return f(std::forward<Tail>(tail)...);
}

int f(int i) { return i; }
void g() { }

int main() {
    measureAndExecute(f, 42);
    measureAndExecute(g);
}

The basic idea is to create an instance of Check and exploit its lifetime to measure the time.
EDIT
As mentioned in the comments, a refinement of measureAndExecute would be:
template<typename F, typename... Tail>
typename std::result_of<F&&(Tail&&...)>::type measureAndExecute(F &&f, Tail&&... tail) {
    Check check;
    (void)check;
    return std::forward<F>(f)(std::forward<Tail>(tail)...);
}


text:
Q: warning real time permission have not been properly installed ubuntu studio controls I added the PPA https://help.ubuntu.com/community/UbuntuStudio/BackportsPPA

*

*and it uninstalled ( i don't know why ) studio controls image of my PC screen. I reinstalled it, and now it looks like this when I open Studio Controls. And it does not automatically start Jack when im starting the system anymore.

I use Ubuntu Studio 21.10. However if I press "start of restart jack" it runs again, even though the warning is still there.
Let me know ( if you can/ want to ) help me. I do not have the greatest experience using Linux, but I have searched google thin to find an answer.
Hope to hear from you.
Oh and if you need any info of some sort, let me know :)


text:
Q: Node Express Render Dom Elements I am trying to create a League of Legends Account lookup website, and I am trying to learn how to render the HTML properly. I have a large object containing the information for many different matches in it. I want to create a DOM element for each match in the match History, and then populate that element with the information contained in the object. How can I do this in a dynamic fashion. I will not always know how many matches will be in the object.
 match0: {
    champion: 76,
    gameStartTime: 1600413655154,
    gameDuration: 1347,
    playerList: {
      Team_100_JUNGLE: [Object],
      Team_100_MIDDLE: [Object],
      Team_100_BOTTOM: [Object],
      Team_100_SUPPORT: [Object],
      Team_100_TOP: [Object],
      Team_200_MIDDLE: [Object],
      Team_200_JUNGLE: [Object],
      Team_200_BOTTOM: [Object],
      Team_200_SUPPORT: [Object],
      Team_200_TOP: [Object]
    },
    result: 'Loss',
    team_100_total_kills: 15,
    team_200_total_kills: 23
  },

This is what each match looks like inside the match History Array. There could be 1 of these objects in the array, or 1000. How can I do this? Do I need to completely restructure the way I am going about this? Send Help.

A: In my oppinion your best choise is to use somekind of templating engine, you can predefine a DOM Structure (template) then throw your Data Object (json at best) at it and it will render the template with all the data provided by your Data Object.
Handlebarsjs is my choise but there are a lot of alternatives, hope it helps if you need further help let me know
https://handlebarsjs.com/
EDIT: I sadly did not work with EJS but i try to explain it with an Handlebars example. The "matchhistory.hbs" is your example template which you could use to display all your matches. This happens through the #each it will loop through all your data that you provide it with. In the webserver you just have to render it and send it back to the user requesting https://example.com/matchhisorty for example.
As for your current problem you dont have create the DOM the rendner will do that for you.
Express webserver(index.js):

//This is only temporary, you need to call the lol api so you got the newest data
//Call the api in the router.get('/matchhistory')

let matchhistory = [
match0: {
    champion: 76,
    ...
    result: 'Loss',
    team_100_total_kills: 15,
    team_200_total_kills: 23
  },
  match1: {
    champion: 76,
    ...
    result: 'Loss',
    team_100_total_kills: 15,
    team_200_total_kills: 23
  },
]

router.get('/matchhistory', function(req, res, next) {
  let raw = matchhistory; //Here you can make your api call to get the matchhistory data
  let parsedata = JSON.parse(raw); //Parse it to json
  res.render('matchhistory', { title: 'Posts - Canime', pod_cards: home.pod.cards , naventry: home.nav.naventry}); //Send back the rendered Page
});

matchhistory..hbs

    {{#each matchhistory}}

            {{this.champion}}

    {{/each}}


text:
Q: SELECT with INNER JOIN, GROUP BY and LIMIT I have a three tables about movies. First one is movie, second one is actor and last one is movie_actor_mapping. I wrote an query that select data from table movie and group actors for each movie. And my query select all actors from actor table but I have to select only first 4 actors. How can I modify my select to do it?
SELECT title, year, poster, rating, group_concat(a.name separator ', ') as actors
FROM movie m
INNER JOIN movie_actor_mapping ma ON m.movie_id = ma.movie_id
INNER JOIN actor a ON a.actor_id = ma.actor_id
WHERE m.rating IS NOT NULL
GROUP BY m.movie_id
ORDER BY m.rating DESC;

A: You can hack it around by substringing group_concat output to first 3 results, e.g.:
select m.name as movie, substring_index(group_concat(a.name SEPARATOR ','), ',', 3) as actors
from movie m
join movie_actor ma on m.id = ma.movie_id
join actor a on ma.actor_id = a.id
group by m.id
order by m.id, a.id;

This would give you 3 actors per movie.
Here is the SQL Fiddle.


text:
Q: remove input size from html with preg_replace I am using Simple HTML DOM Parser and with this I am able to get all input tags from object snippet is below
foreach ($InputObj->find('input') as $e) {

    $inputTag =  $e->outertext;

   // now I want to check if input element have size attribute then remove it with preg_replace
   $inputTagsSizeStrip = preg_replace('~\<input[^\s]*size=\'|\"[^\'|\"]~is', "" , $inputTag);
}

but no success....
any help will be appriciated...

A: There is no reason to use regular expressions here.  You already have the DOM, just do the necessary manipulation:
foreach ($InputObj->find('input') as $e) {
  if ($e->hasAttribute('size')) {
    $e->removeAttribute('size');
  }
}

A: you are already in input tag so no need to go for input tag to search for the size use this preg it will find the size and remove it
 foreach ($InputObj->find('input') as $e) {
       $inputTagsSizeStrip = preg_replace('~(size=(\"|\')[^\'|\"]*(\"|\'))~is', $changeSrc , $inputTagsSizeStrip);
 }

it will definitely work


text:
Q: 'object' does not contain a definition for 'Skip' and no extension method 'Skip' accepting a first argument of type 'object' - In Razor When trying to do some operation on array object i am getting the following error.

'object' does not contain a definition for 'Skip' and no extension
  method 'Skip' accepting a first argument of type 'object' could be
  found (are you missing a using directive or an assembly reference?)

cc and gg are list of items (List)
here is the code
@if (cc.Count > 6)
{
    gg = cc.Skip(6).ToList();
    cc = cc.Take(6).ToList();
}

A: Have you got a reference to System.Linq ?
using System.Linq;

Bit confused why cc.Count isn't throwing an error though...

A: Please try rebuilding your project.


text:
Q: Memory Limit Exceed error in python sum=0
n=int(input())
x = list(map(int, input().rstrip().split()))
for i in range(n):
    str1=str(2**x[i])
    if(len(str1)>2):
        str1[len(str1)-2 :]
    else:
        str1
    sum+=int(str1)
print(sum%100)

Input
3
1 2 3
Output
14
Constraints
 1<=n<=10^7
 0<=x<=10^18

This code is working  fine for small values,like n=4 & x=8,7,6,4 and output is=64.but not for the given constraints.

A: Well... since you do
2**x[i]

which results in an integer value, that will most definately fail when x get's large enough.
You can do the math:
Assuming your computer has 8GB of main memory, that would be 8*8*1024^3=68719476736 bits of memory. So the single largest value that would span your entire(not possible to get this large, but I just want to highlight what the physical limit is here) memory, would be 2**68719476736 which lies somewhere between 2^(10^10) to 2^(10^11)
So as it stands, I think your code cannot work for numbers this large.


text:
Q: Restore type before console loads functionality This might be a far stretch- but I used to be able to start my rails console, and while it's loading (since it has to boot everything and we use some large apps- so it takes a while) I could begin typing the first line of code in. When it finishes loading, it catches up and has everything I had been typing loading in.
That sounds like a silly feature, and I hardly know how to even describe it, but I recently got a new machine and that functionality is gone.
I find it super frustrating, as it can take 5-8 seconds sometimes to load the console (I know there are other issues there) and I REALLY appreciated having the head start functionality.
Hopefully somebody knows what's going on here, as I'd really like to get that fixed. :)

A: Finally found the solution, and it was actually related to another console issue I was running into.
The issue was that the readline gem was not installed prior to Ruby.
The solution was:
# Reinstall Readline
brew uninstall readline
brew install readline
# Reinstall current version of Ruby
rbenv uninstall 2.3.0
rbenv install 2.3.0
bundle install

This resolved both the typing before the console finished loading, and re-enabled my access to the history in previous sessions.


text:
Q: Should I use @2x or -hd? I am confused on the differences between using @2x or -hd
Is one more efficient or quicker than the other?
I am using Cocos2D.

A: I'm pretty neither is quicker than the other
In my case, since I like using Cocos together with UIKit, I use the -hd suffix for all the Cocos related images (textures and such), and @2x for images that will be used with UIKit.

A: @2x is used before CCDirector is loaded..so the @2x is a must for the loading screen and icons
if the CCDirector is already loaded (aka..you're in game) you can use either @2x or -hd but if i remember corectly -hd is slightly slower and you have to enable retina display in app delegate... remove comments of:
if (![director enableRetinDisplay:YES]) CCLOG(@"Retina Display Not supported");

you don't need to enable retina display if you're using @2x

A: Like the other poster, I've never heard of an "-hd" suffix for image names in iOS.
Where did you see that? App names for retina devices or for the iPad sometimes have -hd as part of the name, but as far as I know there's no formal meaning to a "-hd" suffix in iOS.
You should set up your program to use standard images. To support Retina devices, you should save 2 versions of each image, "anImage.png", and "anImage@2x.png", where the one with the @2x suffix is twice as big in height and in width.


text:
Q: JMeter load testing with JUnit from Selenium IDE I have problem with JMeter not picking up my JUnit test.
What I did:

*

*got JMeter and extracted

*created JUnit test through Selenium IDE and exported as JUnit4(WebDriver)

*try that test runs when executed (in IntelliJ)

*created JAR of the class file

*placed JAR into jmeter.home/lib/junit

*started jmeter

*created new thread

*added new sampler for JUnit request

However when I check "Classname" drop down my test is not listed there.
Does anyone know why test is not recognised by JMeter?

A: check whether scripts exported using junit4.
If yes, then select "search for junit4 annotations" check box. surely it will display.

A: After creating Junit jar file . Place the jar file in the
jmeter.home\lib not in jmeter.home/lib/junit.
   After that Restart Jmeter.
   Now add thread group to jmeter and Junit Request sampler.
   Observe that the Classname apperas in the drop down list


text:
Q: Difference version of this app already installed in OnPrem (SP 2019) I have created an SPFx extension and deployed it to the app catalog in On-Prem (SP 2019). For some of the time, when I install the app to the site it throws an error "Difference version of this app already installed", but I did not install the app to that erroring site. When I installing the same app to different site collection it was installing. I have checked the Recycle bin (Admin, Secondary recycle bin) also. There is no reference to my app on the site. Can anyone please help!!!!

A: Check via powershell if maybe you will to find the app instance on this site.
You can do it like this
Get-SPAppInstance -Web https://localhost

Or using pnp powershell (of course you need to first connect to site before running this command with connet-PnPOnline command)
Get-PnPApp -Scope Site

I hope this will be of any help. If you will get the app instance then you can remove it Frome site also using powershell.

A: Go to error site collection-> Site Contents, then find the SPFx extension app and remove it. Then remove it in Recycle bin and Second-Stage Recycle Bin.
You can also update the version number in the package-solution.json file, re-package and re-deploy.


text:
Q: Android - how to return to different previous activities I have several activities/pages in my app. From the first activity, I can open a second activity. In this second activity a game is played. Once this game ends, a new activity starts. In that new activity, I have a button that finishes it, using finish(), which returns me to the activity with the game. I also have a button that is to return it to the very first activity. Here is a diagram to clarify:

When I use finish() to go back to the Game Activity, the game is in an endstate. I want to reset all variables and widgets, but I do not know how to check if I entered this page via calling finish() in the Final Activity.
Q1: How can I check if I entered an activity as a result of finishing another?
I also have another question- what method can I use in button2 to finish not only the final activity but also all previous activities on the stack (except for the first activity, so in this case it would be Final Activity and Game Activity), in order to return to the first activity? In other answers on stackoverflow, I have found suggestions to use FLAG_ACTIVITY_CLEAR_TOP, but if I were to do that, I could no longer also return to Game Activity with button1.
Q2: How can I return to the first activity, while still allowing me to use finish() to return to other activities?

Code I use to go back to previous activity:
// called from button1's onClick
public void goBack(View button1){
    finish();
}

And for going back to the first activity:
public void toFirstActivity(View button2){
    Intent previousPage = new Intent();
    previousPage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    finish();
}

A:
Q1: How can I check if I entered an activity as a result of finishing
  another?

You can easily use a global boolean flag such as "activityFinished", when you call finish() on Final Activity, you set it to true. and in onResume() of your activities, check if activityFinished == true, if so do your stuff and reset the flag to false.

Q2: How can I return to the first activity, while still allowing me to
  use finish() to return to other activities?

I don't understand why FLAG_ACTIVITY_CLEAR_TOP is a problem for you. You only set the intent as FLAG_ACTIVITY_CLEAR_TOP to go back to your very first activity after you have pressed button 2, don't you? How does this have something to do with your button 1's action?
Update:
try this code
Intent a = new Intent(this,FirstActivity.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);


text:
Q: In which directory should I save uploaded files for MERN Stack? I'm using the Mern stack, but I'm having an issue as to where to save uploaded files. Let me explain.
I have a form that sends over a formdata which includes a .jpg image.
On Node/express side, I receive it well. But now I'm stuck.
I'm using express-fileupload package which attaches an mv function that allows me to store my file in a directory.
In my endpoint, I have this snippet:
const img1= req.files.image1;
const img1Name = img1.name;
img1.mv("NOT-SURE-WHERE-TO-MAKE-MY-DIRECTORY"+img1Name, (err) => {
    if (err) {
        return res.status(500).json({message: 'Could Not mv file'});
    } else {
        return res.status(200).json({message: 'mv done'});
    }
})

Where do I create the directory to store the .jpg image?

*

*Do I create it in the client's src? or client's public?

*Or, do I run the npm-run-build command to create my build folder and then point my mv function to save the file in there?

A: create a static file middleware in node app.js file to public directory then @ public/images
If not try using multer it is much easier to upload Files


text:
Q: Unexpected change in data-layout happens when applying numpy FFTs I was trying to interface Python with C, and at some point I had to pass some numpy arrarys after being Fourier transformed. I was in pure despair, literally, for a whole week, facing a bug that was making no sense. In the end, I found out that the bug was introduced by a change in data-layout (strides) of the numpy array caused by the np.fft.fft operation.
Let me demonstrate it below:
See the following example with 1d FFTs over a 2d numpy array.
This is just a copy-paste of the python interpreter on my Linux PC:
Python 3.8.8 (default, Apr 13 2021, 19:58:26)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> input = np.zeros((101,50), dtype=np.complex64)
>>> input.real = np.random.uniform(size=(101,50)).astype(np.float32)
>>> input.imag = np.random.uniform(size=(101,50)).astype(np.float32)
>>> input.shape
(101, 50)
>>> input.strides
(400, 8)
>>> output = np.fft.fft(input, axis=0)
>>> output.shape
(101, 50)
>>> output.strides
(16, 1616)

Here I basically create a 2d numpy array of single-precision complex floats, and then apply FFTs over axis=0. Look at the strides of the input and the output array!!! The shapes are the same but the strides differ.
I have no idea what kind of FFT algorithm is this!
Had I used scipy.fftpack.fft for this operation, the strides would be as expected:
>>> import scipy.fftpack
>>> output = scipy.fftpack.fft(input, axis=0)
>>> output.shape
(101, 50)
>>> output.strides
(400, 8)

So, in the numpy case, it seems like a virtual FFT operation... where instead of FLOPS, some elements reordering is being performed.
I solved my problem using scipy, but I'm curious to learn more. Does anyone have some comments?


text:
Q: A null pointer exception of connecting hybris database using flexiblesearch service because of getJaloResult() error A null pointer exception occurred when trying to connect to hybris database using hybris flexible search service seemingly due to getJaloResult() method.
I need to retrieve certain data from hybris commerce database. I tried to use hybris flexible service to do that by using defaultFlexibleSearchService.search() method, but I got a null pointer exception. It seems that the exception occurred when search() method tries to call getJaloResult() method. I have no clue about the solution - thanks for any hints.
My class definition code is here
package de.hybris.platform.integrationservices.audit;
import java.util.stream.Stream;
import com.sun.tools.javac.util.List;
import de.hybris.platform.audit.TypeAuditReportConfig;
import de.hybris.platform.audit.view.AuditViewService;
import de.hybris.platform.audit.view.impl.ReportView;
import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
import de.hybris.platform.servicelayer.search.FlexibleSearchService;
import de.hybris.platform.servicelayer.search.RelationQuery;
import de.hybris.platform.servicelayer.search.SearchResult;
import de.hybris.platform.servicelayer.search.impl.DefaultFlexibleSearchService;
import de.hybris.platform.integrationservices.model.IntegrationObjectModel;

public class IntegrationObjectAudit implements AuditViewService
{
    private DefaultFlexibleSearchService defaultFlexibleSearchService;

    public IntegrationObjectAudit() {
        defaultFlexibleSearchService = new DefaultFlexibleSearchService();
    }

    public List<IntegrationObjectModel> searchModel(){
        String query = "SELECT {PK} FROM {IntegrationObject}";
        FlexibleSearchQuery flexibleSearchQuery = new FlexibleSearchQuery(query);
        flexibleSearchQuery.setCount(1);

        de.hybris.platform.servicelayer.search.SearchResult<IntegrationObjectModel> resListIntegrationModel = this.defaultFlexibleSearchService.search(query);
        List<IntegrationObjectModel> resList = (List<IntegrationObjectModel>) resListIntegrationModel.getResult();
        return resList;
    }
}

A: Didnt notice it was posted days back. Hope you already resolved it. Still adding my answer as it may be helpful for others.
What I see you are not injecting flexibleSearchService bean in IntegrationObjectAudit. And as flexibleSearchService bean is not injected, its causing NullPointerException when you call any function on it.
You can fix it as following (spring bean injection concept)

*

*Either you should create a setter function and inject it by spring xml

*Or use @Resource or @Autowire annotation for same

public class IntegrationObjectAudit implements AuditViewService
{
    @Resource
    private DefaultFlexibleSearchService flexibleSearchService;

     .....

Hope it helps. Let me know please.


text:
Q: Trying to display all employees in a table that are over the age of 40 - Oracle Not sure how to write a query to display all employees that are aged 40 or above
Not sure where to go from here
select First_Name, Last_Name, Birth_Date from Employees
where (sysdate - Birth_Date);

A: Age is determined by when someone is born.  In Oracle the safest method is add_months, so:
where birth_date < add_months(sysdate, -12 * 40)

You can also specify this as:
where birthdate < sysdate - interval '40' year

This would generally work, but interval arithmetic can cause problems when leap years are involved.


text:
Q: How deep I can go with asking inner field I am learning Python and I can't understand 2 things.
I have this code.
class Test:
    def __init__(self, field):
        self.field = field

t = Test("field")
t.field_2 = t
print(t.field_2.field_2.field_2.field_2.field)

In the last line I can't understand how deep can I go.
As I understand as memory is not infinitive - I can't go deerep always.

A: Actually, you can. To demonstrate this:
while t != None:
    t = t.field_2
    print(t.field)

This will run forever.
You reuse the same object, so that the memory doesn't grow. field_2 just stores pointer to the object (an address in the memory) rather than the object itself, and that's why it works.

A: It's like a circle. You can make infinitely many loops while still staying in a finite space.


text:
Q: BX-SLIDER not showing the content in popup window initially BX-SLIDER not showing the content in popup window initially after resizing the window it works normal.

A: I'm guessing you want to use the bx slider reload function. You can use it in your jQuery code after DOM ready:
var slider = $('.bxslider').bxSlider({});
slider.reloadSlider();

edit: http://bxslider.com/examples/reload-slider


text:
Q: Java Dialog Box Icons What do you need to add to select various icons for dialog boxes? Also how do you use a custom icon?
Thanks!

A: Do you mean JDialogs? If so, you're looking for this page from the Java Tutorials. Copied below are the samples from that page, without the screenshots; see the last one for how to use a custom icon:
//default title and icon
JOptionPane.showMessageDialog(frame,
    "Eggs are not supposed to be green.",
    "Message");

//custom title, warning icon
JOptionPane.showMessageDialog(frame,
    "Eggs are not supposed to be green.",
    "Inane warning",
    JOptionPane.WARNING_MESSAGE);

//custom title, error icon
JOptionPane.showMessageDialog(frame,
    "Eggs are not supposed to be green.",
    "Inane error",
    JOptionPane.ERROR_MESSAGE);

//custom title, no icon
JOptionPane.showMessageDialog(frame,
    "Eggs are not supposed to be green.",
    "A plain message",
    JOptionPane.PLAIN_MESSAGE);

//custom title, custom icon
JOptionPane.showMessageDialog(frame,
    "Eggs are not supposed to be green.",
    "Inane custom dialog",
    JOptionPane.INFORMATION_MESSAGE, icon);

In that last example, icon is an object of type Icon. Here's the Javadoc for that version of showMessageDialog().


text:
Q: Override the variable from parent class in Django Models I have a model ChildModel and it has two parent classes ActivatorModel and TimeStampedModel
Below are the three models:
The two base classes
class ActivatorModel(models.Model):
    """
    ActivatorModel

    An abstract base class model that provides activate and deactivate fields.
    """

    INACTIVE_STATUS = 0
    ACTIVE_STATUS = 1

    STATUS_CHOICES = (
        (INACTIVE_STATUS, _('Inactive')),
        (ACTIVE_STATUS, _('Active')),
    )
    status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=ACTIVE_STATUS)
    activate_date = models.DateTimeField(blank=True, null=True, help_text=_('keep empty for an immediate activation'))
    deactivate_date = models.DateTimeField(blank=True, null=True, help_text=_('keep empty for indefinite activation'))
    objects = ActivatorModelManager()

    class Meta:
        ordering = ('status', '-activate_date',)
        abstract = True

    def save(self, *args, **kwargs):
        if not self.activate_date:
            self.activate_date = now()
        super().save(*args, **kwargs)

class TimeStampedModel(models.Model):
    """
    TimeStampedModel

    An abstract base class model that provides self-managed "created" and
    "modified" fields.
    """

    created = CreationDateTimeField(_('created'))
    modified = ModificationDateTimeField(_('modified'))

    def save(self, **kwargs):
        self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True))
        super().save(**kwargs)

    class Meta:
        get_latest_by = 'modified'
        abstract = True

The class using the above base models

class ChildModel(ActivatorModel, TimeStampedModel):
    child_id = models.CharField(
        max_length=36, primary_key=True, default=uuid.uuid4
    )
    display_name = models.CharField(blank=True, max_length=100, null=True)
    status = models.CharField(max_length=20, null=True, blank=True, default='Active')

The issues is whenever I try to save some character type value in ChildModel.status, it throws an error
invalid input syntax for integer.

How to properly override the variable status and have it the properties defined in the ChildModel?


text:
Q: Auto-rsync when saving file on VIM not working because rsync prompts password I'm configuring VIM to execute a rsync after saving a file, synchronizing my server with my dev laptop. It doesn't work because rsync prompts for my password, even if I've already set up a public key login. How to fix this?

A: If you are using ssh-connection with rsync, you can always set up a passwordless connection for it. [Here][1] are some nice tutorials. It can be done on windows too, via PuTTY, PLink, Pageant, etc. Read the docs.

A: Instead of using vim for this, how about using incron? It ships with most modern Linux distributions and will sync any changes, not just those you do in vim.

A: Explicitly define which ssh-key you are to use with ssh -i:

*

*:nnoremap <expr> <D-s> ':w!<cr>' . ':!rsync -r -e ssh -i /home/user/.ssh/id_rsa ~/Folder/* user@my_ssh_server.com:~/Folder/ &<cr>' . ':!osascript ~/applescripts/chromereload.scpt &<cr>'
Or you could you try to set your shell variable to interactive, i.e. use ~/.bashrc++ (man bash). Not really sure if it has any effect.

*

*:set shell=/bin/bash\ -i
And/or define an alias in your ~/.bashrc if needed. Maybe combine it with whatever chromereload.scpt does.

*

*alias vimsync='rsync -r -e ssh -i /home/user/.ssh/id_rsa ~/Folder/* user@my_ssh_server.com:~/Folder/'
More information:
vim -- not recognizing aliases when in interactive mode?

A: I haven't tried this but it should work:
Put this into your ~/.ssh/config file:
ControlMaster auto
ControlPath ~/.ssh/cm_socket/%r@%n:%p
ControlPersist 300
KeepAlive yes
ServerAliveInterval 60
Create the directory ~/.ssh/cm_socket and ssh into the server from another terminal. Now when you ssh into the server again it should use the same socket and no password is required, so your rsync command should work without password.


text:
Q: Access to media folder Which permission is required to read/write files inside folder
/storage/emulated/0/Android/media/packagename/
in Android 11 and Android 13?
It is not for my app, for the folder of another app.
Do you have a little example (some lines of code) for me?


text:
Q: Error Graph X Caused by: java.lang.NoSuchMethodError: scala.Product.$init$(Lscala/Product;)V I have been playing with use classes but I am continuously getting the error above when I try to implement them. This is my code:
import org.apache.spark.graphx._
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

class EdgeProperties()
case class WriterWriterProperties(weight: String, edgeType: String) extends EdgeProperties
object GraphXAnalysis2 {

val edgeWeightedWriterWriterCollaborated = "in/Graphs/Graph4_WriterWriter/EdgesWeightedWriterWriter_writerscollaborated.csv"
    val vertexWriterWriter = "in/Graphs/Graph4_WriterWriter/Vertices.csv"
    val conf = new SparkConf().setAppName("Music Graph Application").setMaster("local[1]")
    val sc = new SparkContext(conf)

 val WriterWriter: RDD[(VertexId, String)] = sc.textFile(vertexWriterWriter).map {
      line =>
        val row = line.split(",")
        (row(0).toLong, row(2))
    }

val edgesWriterWriterCollaborated: RDD[Edge[EdgeProperties]] = sc.textFile(edgeWeightedWriterWriterCollaborated).map {
      line =>
        val row = line.split(",")
        Edge(row(0).toLong, row(1).toLong, WriterWriterProperties(row(2), row(3)): EdgeProperties)
    }

val graph4 = Graph(WriterWriter, edgesWriterWriterCollaborated)

Am I declaring the class wrongly, using it wrong or putting it in the wrong position? Thank you so much as I am completely new to this.


text:
Q: Windows RAM Test Program I'm recently getting blue screen of death on my Windows XP machine. I suspect that the culprit is the RAM I've just installed. Is there any program that I can use the test whether my RAM is good or not, on Windows XP?
I am looking at program that does not require me to boot from external device such as floppy disk or CD ROM. The program should run just like normal without requiring me to restart the machine.

A: I've used MemTest, which runs under Windows, but I've never quite had faith in it; partly for the reasons other people have mentioned, but also partly because I've never seen used in anger (i.e. on RAM that actually turned out to be faulty) - so I cant vouch for it's effectiveness.
Like many others, I rely mainly on MemTest86+ (boot from CD). I know you might find it inconvenient, but with 4GB+ in many machines these days, and given that you need to run through several passes to be thorough, checking the RAM properly is an overnight job.
Having just upgraded to an i7 mobo, CPU and DDR3 RAM, the first thing I did was test the RAM on the first night. As it happens, the RAM appeared faulty, so each night, I ran another test with various combinations of sticks and various BIOS settings to confirm the extent of the problem. When I return the RAM under an RMA, I'll get charged an admin fee if the RAM isn't found to be really faulty - so it's important to make sure I get my facts right - hence the more laborious route of multiple, overnight memtest86+ runs... It's worth it in the longer run.

A: I would recomment to use Memtest86+ anyway. Yes, it requires you to boot from external device (they have pre-built CDs) but I think that there is no other proper way to test RAM otherwise--Windows XP won't give full access to the RAM for the testing programme.

A: What you are asking for is impossible.
As pointed out by phoebus, it's impossible to fully test the RAM while Windows is running.Among other things, Windows will reserve part of the RAM exclusively for itself, hence no other program will be able to access and test it.
Also, Windows (like all modern OS) uses virtual memory, so a testing program cannot write to a specific hardware memory address (because access is blocked by the OS); it can only ask the OS for memory and access that memory, and it has no control about where that memory lies. So the testing program might be testing the same memory over and over...
So you'll have to reboot from a CD-ROM or other media with e.g. memtest86 on it.

A: http://hcidesign.com/memtest/ free.. don't know how good, I use memtest86


text:
Q: Summernote Editor not Initializing on Page I am trying to use summernote in my web app, after i followed the steps provided here http://summernote.org/getting-started/#installation
When i test in browser, it only shows the resize handle at the bottom of the editor, toolbars are not loaded at all. I dont know if there is anything outside the steps provided by the sunnernote instructions. Pls help me out cos am stock here, i dont want to use another editor. Thanks for stopping by..

A: Thanks for reporting. Could you try below link again?
http://summernote.org/getting-started/#installation
Actually I'm creator of summernote. I updated library path with protocol.
If It's still not working, save below contents with index.html and open it with browser again.
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title></title>

  <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
  <link href="http://netdna.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.css" rel="stylesheet">

  <link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.7.0/summernote.css" rel="stylesheet">

Hello Summernote

A: PROBLEM SOLVED
I had the bootstrap.js refrenced before jquery.min.js,
all i did was to reference jquery before any other .js file

A: enter link description here
It helped me but it will help you too

  <button id="btnToggleStyle" class="btn btn-primary">Toggle Corrected Styles</button>


text:
Q: What is the minimal area of a fully-fledged Dyson sphere? A Dyson sphere is a hypothetical megastructure made up of a finite number of thin sun-shades in free-fall orbit around a central star. The goal is to harvest as much of the sun's radiation power as possible. In this regard, let's agree that a Dyson sphere is "fully-fledged" iff all rays emanating from the star's center must intersect one of the sphere's shades (at all times). Suppose in addition that all shades must keep a distance of at least $R$ from the star's center (in order not to evaporate, say). What is the minimal surface area of shade-material that must be allocated in creating such a fully fledged Dyson-sphere?
To have my question well-posed, I should briefly discuss the rules of motion in orbital mechanics. For the occasion, let me state them as follows: a single sun-shade $S(t)\subset \mathbb{R}^3$ is a relatively open subset of a sphere $\partial B(0,d) \subset \mathbb{R}^3$ which is contained within a ribbon $r(\varepsilon,C)\subset B(0,d)$ of a (small) thickness $\varepsilon$ around a great circle $C$ of the sphere $\partial B(0,d).$ $S(t)$ changes with time $t$ through rigid rotation along the great circle $C$ with rotation speed $v=1/\sqrt{d}$.
As such, the question of the minimal required surface area $A_{\varepsilon}$ retains a dependence on the thickness-parameter $\varepsilon$. Obviously, $\varepsilon \to A_{\varepsilon}$ is a decreasing function so that for the purpose of my question, it is expeditious to ask what $A:=\lim_{\varepsilon \to 0+} A_{\varepsilon}$ might be.
Allow me also to briefly discuss a few obvious bounds: clearly we always have that $A\geq 4\pi R^2$. On the other hand, by arranging a number of circular ribbons in the way of the picture below(*), it is clear that $A \leq 2\pi^2 R^2$: in this setup, at all time around 36% of the shade-area is in the shadow cast by other shades.

Picture courtesy by wikipedia commons
(*) The picture does not do a perfect job of depicting the configuration that I'm referring to. Specifically, the ribbons in the picture approach each-other closest at distinct locations in space, while I rather am referring to a configurations where these ribbons are great circles going from a shared north pole to a shared south pole (with slightly different radii to avoid collision at these poles) along the meridians suggested by this pair of poles.


text:
Q: FileUpload error in the server hi
I have a FileUpload and I save a picture and this is the error
Access to the path 'D:\Hosting\0000000\html\images\APgt_logo.jpg' is denied.
an my local is working well
whats the problem?
this is the code
new_row["Product_imag"] = FileUpload1.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("/images/"+ FileUpload1.FileName.ToString()));

A: The user that is running the Web Service process (ie w3wp.exe) doesn't have sufficient rights on the folder you are trying to write to.
Either you have to set write rights in IIS, or you have to adjust the security in the file system. Or both.
You need to provide more information if you want help with that.

A: This is a permissions problem on your web server.
When you run the project locally, the local web server is executing using your permissions which has write access to the directory in question.
When running on the server, the user the app pool is executing under does not have permission to write to the directory.  This is normal as it usually shouldn't.
You might ask this over at serverfault.com to get some good recommendations on how to do this in a secure manner.


text:
Q: typing in a for loop react+typescript? i have this interface of a Todo:
export interface InitialTodoLoadingState {
  toggleComplete: boolean;
  updateText: boolean;
  deleteTodo: boolean;
}
export interface Todo {
  complete: boolean;
  _id: string;
  text: string;
  loading: InitialTodoLoadingState;
}

i am trying to loop an array of todos objects like this:
const processing = todos // check if processing operations e.g.: toggle complete
      .map((todo: TodoInterface) => {
        for (let loadProp in todo.loading) {
          if (todo.loading[loadProp]) return true; // ERROR HERE
          return false;
        }
      })
      .some(process => !!process);

I am getting an error saying:
Element implicitly has an 'any' type because type 'InitialTodoLoadingState' has no index signature.

how do i implement typescript here? I don't want to use any

A: To remove the error, add an index signature (see here):
export interface InitialTodoLoadingState {
  toggleComplete: boolean;
  updateText: boolean;
  deleteTodo: boolean;
  [key: string]: boolean;
}


text:
Q: Electron not working with web speech API? mounted() {
 window.SpeechRecognition = window.webkitSpeechRecognition ||
 window.SpeechRecognition;
 let finalTranscript = "";
 let recognition = new window.SpeechRecognition();

 recognition.interimResults = true;
 recognition.maxAlternatives = 10;
 recognition.continuous = true;

recognition.onresult = event => {
  let interimTranscript = "";
  for (
    let i = event.resultIndex, len = event.results.length;
    i < len;
    i++
  ) {
    let transcript = event.results[i][0].transcript;
    if (event.results[i].isFinal) {
      finalTranscript += transcript;
    } else {
      interimTranscript += transcript;
    }
  }

  console.log(finalTranscript + interimTranscript);
};
recognition.start();
}

cant get web speech API to work in my electron app, same code works well in the browser. Any possible reasons? I am using vue js with electron and the speech part is called when a component mounts.

A: As you may already know, Electron is built on top of the Chromium open-source browser.
This discrepancy between the browser and Electron stems from the fact that Chromium does not include the Google API keys necessary to run certain webservices (e.g. Speech, Geolocation), while Chrome does (source: Chromium Browser vs. Google Chrome).
As of today, there exists a GOOGLE_API_KEY environment variable that adds a API key for your app, but it only works for the Geolocation webservice. You can verify this in the Electron source code, where this variable is only hooked into the ElectronBrowserClient::GetGeolocationApiKey() function.
For now, your best bet would be to look into implementing those under-the-hood Google APIs directly.


text:
Q: Unexpected Screen in Laravel Vue3 example Learning by example from
https://laraveldaily.com/post/laravel-8-vue-3-crud-composition-api
and finishing the following step:
<x-app-layout>
    <x-slot name="header">
        ...
    </x-slot>

                    <router-view />

</x-app-layout>

Running npm run dev I am landing on a false screen. The text says "After logging into your Laravel Breeze, we should see this" Where would I log into "my" Laravel Breeze? (URL shows http_://localhost:5173/)
enter image description here This is what is to be expected
But I am landing on
enter image description here false screen
I checked routing, but I don't find a mistake.
web.php:
<?php

use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

Route::view('/{any}', 'dashboard')
    ->middleware(['auth'])
    ->where('any', '.*');

require __DIR__.'/auth.php';


text:
Q: route specific audio to different output I have a bluetooth headset that I like to use for calls (Skype / Hangouts from a tab in Chrome) but I also want to have music from the Spotify app playing on my laptop speakers.
On PC I'd got things set up so the audio routed how I wanted (headset was the default communications device, speakers as the general default), but on macOS I can't work out a way to do it - it seems that it's all or nothing to an output device, and I can't select the headset for Skype, WebEx,and Chrome tabs (all of them, or just ones I can identify by, eg, title) and keep Spotify using speakers