text:
Q: Is it considered a good/bad practice to configure tomcat for deploying certain apps? Disclaimer: I've never used the technique which is described below. That's why there may occur some mistakes or misunderstandings in its description.
I heard that some teams (developers) use 'pre-configured' tomcat. As I understand they add different jars to tomcat \lib folder and do something else.
Once I've read a thread in a java forum where one developer wrote something about recompilation (or reassembly?) of tomcat for certain needs.
Just yesterday I heard a dialog where one developer sayd that his team-mates were not able to deploy the project until he would give them configured tomcat version.
So, I wonder, what is it all about and why do they do it? What benefits can they gain from that?

A: Open source projects, always have been an space for customizations (I believe, that's something of its charm), and I think it's acceptable to modify Tomcat for very specific in-house requirements.
But in general I would recommend to avoid a solution that requires hard modifications of open source tools -probably there is another way to do what you want using the existing ; )  (this do not apply for general accepted changes i.e. community Addons, bug fixes, and all the stuff you publish in the project spaces that are accepted and made part of the final solution).
About external lib, I would mentioned them in the project README as platform requirements. so to have a pre-configured server it's not that crazy. in fact it can save you some time, but it's a bonus. you should mention your dependencies somewhere anyway : )
Hope it helps.

A: Using a customized version of Tomcat could make upgrading very difficult. The benefit of having an application that does not require a specially configured server is that you can easily move to a new version or even move to an entirely different app server (e.g. Jetty, GlassFish)
I'd also point out that you do not specify the context of the changes. The special configuration may not have been application specific, but was required for security settings, compatibility with the web server being used, etc. You should talk to the developer's in question and learn more about why they require the specialized configuration.

A: This is the mechanism necessary to provide e.g. JDBC pools and objects over JNDI since that requires it to be in the Tomcat classloader.  That is a necessity.
It may also be used to allow multiple deployments to share the same single jar file instead of having it in each WAR file.  That is in my opinion generally a bad idea which should be avoided unless absolutely necessary.  Keep to standard mechanisms if at all possible.


text:
Q: Grails 'method not allowed' weirdness I have simple controller code like:
// UserController.groovy

class UserController {

    static allowedMethods = [
            signIn:       'GET',
            authenticate: 'POST',
            signOut:      'POST',
            register:     'GET',
            save:         'POST'
    ]

    // ... code omitted

    def register() { }

    def save() {
        render 'ok'
    }
}

Registration form:

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="layout" content="main" />
    <title>Withme: Register</title>

    <g:form mapping="register">

        <g:actionSubmit value="Register" />
    </g:form>

And url mappings:
//UrlMappings.groovy

class UrlMappings {
    static mappings = {
        name register: '/register'(controller: 'user') {
            action = [GET: 'register', POST: 'save']
        }
    }
}

Now for the weird part. When making request with curl all works as expected:
$ curl http://localhost:8080/withme/register -X GET -v -L
... form rendered ...

$ curl http://localhost:8080/withme/register -X POST -v -L
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< Content-Type: text/html;charset=utf-8
< Transfer-Encoding: chunked
< Date: Thu, 08 Aug 2013 07:41:23 GMT
<
* Connection #0 to host localhost left intact
ok* Closing connection #0

Accessing /register with a browser returns form. But when I submit it within a browser, 405 returned!
HTTP Status 405 -

type Status report

message

description The specified HTTP method is not allowed for the requested resource.
Apache Tomcat/7.0.42

Firebug confirms that POST is performed:
POST http://localhost:8080/withme/register | 405 Method Not Allowed | localhost:8080

I have disabled all filters in my application.
I wonder what the difference between curl and browser POST requests? Why grails handles it in a different way? And finally, how to fix it..
Grails 2.2.4 Groovy Version: 2.1.6 JVM: 1.7.0_21 Vendor: Oracle Corporation OS: Mac OS X
Update
I've figured out that request body matters. Sending request with curl without body succeed, but setting body causes request to fail. Good one:
$ curl http://localhost:8080/withme/register -X POST -v -L
* About to connect() to localhost port 8080 (#0)
*   Trying ::1...
* connected
* Connected to localhost (::1) port 8080 (#0)
> POST /withme/register HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5
> Host: localhost:8080
> Accept: */*
>
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< Content-Type: text/html;charset=utf-8
< Transfer-Encoding: chunked
< Date: Thu, 08 Aug 2013 09:39:22 GMT
<
* Connection #0 to host localhost left intact
ok* Closing connection #0

And bad one:
$ curl http://localhost:8080/withme/register -X POST -v -L -d "email=&password=&passwordConfirmation=&firstName=&lastName=&country=&city=&_action_Register=Register"
* About to connect() to localhost port 8080 (#0)
*   Trying ::1...
* connected
* Connected to localhost (::1) port 8080 (#0)
> POST /withme/register HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5
> Host: localhost:8080
> Accept: */*
> Content-Length: 100
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 100 out of 100 bytes
< HTTP/1.1 405 Method Not Allowed
< Server: Apache-Coyote/1.1
< Content-Type: text/html;charset=utf-8
< Content-Length: 977
< Date: Thu, 08 Aug 2013 09:40:31 GMT
<
* Connection #0 to host localhost left intact
<title>Apache Tomcat/7.0.42 - Error report</title>
HTTP Status 405 -

type Status report

message

description The specified HTTP method is not allowed for the requested resource.

Apache Tomcat/7.0.42
* Closing connection #0

Still what's the difference?

A: I've solved strange problem.
Grails renders <g:actionSubmit value="Register" /> as
<input type="submit" value="Register" name="_action_Register">

Note the strange name. Grails deduce it from the value attribute and uses it when choosing what action to call. It causes problem in my case because POST /register should be handled by save action.
Changing it to <input type="submit" value="Register"> solve the problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rooks on a lifeline The short version of this question is:

If $G$ is a graph whose nodes are associated with squares of a chessboard, such that no two nodes in the same row or column of the board are adjacent, we want to associate rooks with the vertices of $G$, such that at most one rook appears in each row and column of the chessboard under the constraint that the vertices containing the rooks induce a connected subgraph of $G$ (thus, the rooks are connected to each other with a lifeline, or lifegraph if you want to be specific).
A maximal configuration of rooks is such that no rooks can be added to the chessboard without violating the constraint that each column/row contain only one rook.
Question: A back-tracking depth first search will find all maximal configutions. Will a back-tracking breadth-first search do the same?

Let's consider an $m \times n$ chessboard that will be inhabited by rooks. As is usual with chess problems in graph theory, each square is represented by a vertex: let $v_{s,t}$ represent the square at row $s$ and column $t$ of the board. Now, let $G$ be an arbitrary graph on the set of vertices $V$ that comprise the squares of the chessboard.
We want to fill the chessboard with rooks (said another way: we want to associate rooks with vertices), such that:

*

*Every row and every column contain at most one rook (more formally, if a rook is associated with a vertex $v_{i,j}$, then no rook will be associated with $v_{i,s}$ for $s \in \{1,\ldots,n\}$) or $v_{t,j}$ for $t \in \{1,\ldots,m\}$),

*The vertices with rooks must induce a connected subgraph of $G$ (hence the reference to a "lifeline" that must connect all rooks).

An example of a chessboard with a single rook (indicated by the black vertex) is shown here

The gray squares show the area covered by the rook - no other rook can be placed on any of the gray squares. Note that I have neglected to color the squares themselves black and white as they should appear on a real chessboard. Edges are indicated by red lines.
Let's consider how we might extend the neighborhood of the black node - call it $v$. There are three vertices adjacent to $v$, but we can only place rooks on at most two of them at a time without violating the constraint that only a single rook cover a given row/column. In fact, there are two ways of placing the rooks, as shown here:

and here (broken link).
A maximal configuration is a valid placement of rooks (according to our constraints) that cannot be extended by the addition of another rook without violating the constraints.
We can enumerate all maximal configurations by performing a back-tracking depth-first search  from each node (i.e. each square on the chessboard). With a depth-first search, we only add one rook to the chessboard at a time.

Suppose that we perform a back-tracking breadth-first search instead. At each step, we add as many rooks the board as possible. Of course there possibly are many different ways of adding as many rooks as possible at each step. This is exactly what is done in the two images above: the maximum number of rooks are added in both possible configurations.
Will this strategy also enumerate all maximal configurations?

A: The answer is that you have gotten too greedy! I give my squares coordinates in R^2. Place vertices on the points (z,z) for integers z with absolute value less than 100 and also at (-2,2), (1,2) and (-1,-2). Place edges between (z,z) and (z+1,z+1) for all z and also place edges between ((-2,2) and (0,0)) , ((-1,-2) and (0,0)) , ((-1,-2) and (1,1)), ((2,1) and (0,0)), ((2,1) and (-1,-1)). So 3 non diagonal vertices and 5 non diagonal edges.
Obviously the best we can do is place rooks on the diagonal from (-100,-100) to (100,100).
Now if you start your search at a vertex on the diagonal at or left of (-1,-1) (resp. at or right of (1,1)) then you won't get to the other side of the diagonal since at (-1,-1) (resp (1,1)) you take the edge to (2,1) (resp (-1,-2)) which cuts you off from (2,2) (resp (-2,-2)). That also explains why you can't start at (2,1) or (-1,-2). If you start at (-2,2) you are cut off from both diagonals as you can't cross (-2,-2) and (2,2). But if you start at the origin, you take the edge to (2,2) which shows you can't start at the origin either.
Thus you got too greedy. Close though, and interesting.


text:
Q: convert array in proper format to show in Google chart i implement google dount chart now I try to set data using ajax. in google don't chart except data like this.
 ['Category', 'Amount'],
 ['Photos',     22],
 ['Videos',      9],
 ['Free Space',  9]

But when I try to make an array like this it's show different format like this.
["title", "receiptAmount", "Expense category", "50"]

so what can I do to convert in above format. i try with so many way to convert this but I didn't get any success on this I show what can I try with the code.
var arrValues = [];
arrValues = ['title', 'receiptAmount'];
for(var i=0; i<data.length; i++)
{
  arrValues.push(data[i]['title'],data[i]['receiptAmount']);
  dataArray = arrValues;
 }
 console.log(dataArray);

Please help me to solve this?

A: You need to push array to array:
var arrValues = [];
arrValues.push(['title', 'receiptAmount']);
for(var i=0; i<data.length; i++) {
    arrValues.push(
        [data[i]['title'], data[i]['receiptAmount']]
    );
}
console.log(arrValues);

A: You need to create array of arrays like this:
// var arrValues = [];
var arrValues = [['title', 'receiptAmount']];
for(var i=0; i<data.length; i++)
{
  arrValues.push([data[i]['title'],data[i]['receiptAmount']]);
  dataArray = arrValues;
 }
 console.log(dataArray);

Hope it helps!


text:
Q: How to use ServerSideVerifications for Expo Admob I am using expo-ads-admob in my app. I set my ad for server side verification but I can't set user_id or custom data for ad in my app.
await AdMobRewarded.requestAdAsync({ servePersonalizedAds: true, additionalRequestParams: {user_id:10}});
How can I use ServerSideVerification for admob with expo? Thanks.


text:
Q: Database migration fails in entrypoint.sh during docker-compose up I am new to Docker and trying to dockerize the project I am working on, which is a simple Symfony API with a MySql database.
I want docker to execute the DB migration php bin/console doctrine:migrations:migrate when it builds the container, so I added an entrypoint to do so:
entrypoint.sh
#create or update db
php bin/console doctrine:migrations:migrate --no-interaction

# start apache
apache2-foreground

Then when I run docker-compose up -d everything works fine but database is not migrated. When I enter the container I can manually execute the doc:mig:mig command but how do I get this done automatically? Am I not understanding the usage of entrypoint properly?
Here is my docker-compose.yaml file (substituted sensitive data)
version: '3.7'
services:
    api:
        build: .
        ports:
            - 8000:80
        links:
            - db
        volumes:
            - C:/Repos/myProjectName/src:/var/www/myProjectName_api/src
    db:
        image: 'mysql:8.0'
        container_name: mysql
        environment:
            MYSQL_USER: myUserName
            MYSQL_PASSWORD: myPwd
            MYSQL_ROOT_PASSWORD: myRootPwd
            MYSQL_DATABASE: dev_myProjectName
        volumes:
            - ./mysql:/var/lib/mysql
        command: ["--default-authentication-plugin=mysql_native_password"]
        ports:
            - "3307:3306"

and my Dockerfile
FROM php:8.1-apache

RUN a2enmod rewrite
RUN apt-get update \
  && apt-get install -y libzip-dev git wget nano --no-install-recommends \
  && apt-get clean \
  && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

RUN docker-php-ext-install pdo
RUN docker-php-ext-install pdo_mysql
RUN docker-php-ext-install zip

RUN wget https://getcomposer.org/download/2.4.2/composer.phar \
    && mv composer.phar /usr/bin/composer && chmod +x /usr/bin/composer
COPY docker/apache.conf /etc/apache2/sites-enabled/000-default.conf
COPY . /var/www/myProjectName_api

RUN chown -R www-data:www-data /var/www/myProjectName_api/var

# Allow Authorization header
RUN echo 'SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1' >> /etc/apache2/apache2.conf

COPY environments/.env.dev /var/www/myProjectName_api/.env.local

WORKDIR /var/www/myProjectName_api

COPY docker/entrypoint.sh /tmp
RUN chmod +x /tmp/entrypoint.sh
ENTRYPOINT /tmp/entrypoint.sh


text:
Q: Conceptual Problems with Iterator I'm trying to write my first iterator class / container type. Basically, I want to be able to iterate though a file, have the file converted to HEX on the fly, and pass the result into the boost::xpressive library. I don't want to do a one shot conversion to a string in RAM, because some of the files I need to be able to process are larger than the expected system RAM (multiple GB).
Here is what my code looks like. I'm using MSVC++ 2008.
Header for Iterator:
class hexFile;

class hexIterator : public std::iterator<std::bidirectional_iterator_tag, wchar_t>
{
    hexFile *parent;
    __int64 cacheCurrentFor;
    wchar_t cacheCharacters[2];
    void updateCache();
public:
    bool highCharacter;
    __int64 filePosition;
    hexIterator();
    hexIterator(hexFile *file, bool begin);
    hexIterator operator++();
    hexIterator operator++(int)
    {
        return ++(*this);
    }
    hexIterator operator--();
    hexIterator operator--(int)
    {
        return --(*this);
    }
    bool operator==(const hexIterator& toCompare) const;
    bool operator!=(const hexIterator& toCompare) const;
    wchar_t& operator*();
    wchar_t* operator->();
};

Implementation for iterator:
#include <stdafx.h>
class hexFile;
hexIterator::hexIterator()
{
    parent = NULL;
    highCharacter = false;
    filePosition = 0;
}
hexIterator::hexIterator(hexFile *file, bool begin) : parent(file)
{
    if(begin)
    {
        filePosition = 0;
        highCharacter = false;
    } else
    {
        filePosition = parent->fileLength;
        highCharacter = true;
    }
}

hexIterator hexIterator::operator++()
{
    if (highCharacter)
    {
        highCharacter = false;
        filePosition++;
    } else
    {
        highCharacter = true;
    }
    return (*this);
}

hexIterator hexIterator::operator--()
{
    if (highCharacter)
    {
        highCharacter = false;
    } else
    {
        filePosition--;
        highCharacter = true;
    }
    return (*this);
}

bool hexIterator::operator==(const hexIterator& toCompare) const
{
    if (toCompare.filePosition == filePosition &&
        toCompare.highCharacter == highCharacter)
        return true;
    else return false;
}

bool hexIterator::operator!=(const hexIterator& toCompare) const
{
    if (toCompare.filePosition == filePosition &&
        toCompare.highCharacter == highCharacter)
        return false;
    else return true;
}
wchar_t& hexIterator::operator*()
{
    updateCache();
    if (highCharacter)
        return cacheCharacters[1];
    return cacheCharacters[0];
}

wchar_t* hexIterator::operator->()
{
    updateCache();
    if (highCharacter)
        return cacheCharacters + 1;
    return cacheCharacters;
}

void hexIterator::updateCache()
{
    if (filePosition == cacheCurrentFor)
        return;
    BYTE rawData;
    DWORD numberRead;
    LONG lowValue = static_cast<LONG>(filePosition);
    LONG highValue = static_cast<LONG>(filePosition >> 32);
    SetFilePointer(parent->theFile, lowValue, &highValue, FILE_BEGIN);
    if (!ReadFile(parent->theFile, &rawData, 1, &numberRead, 0))
        throw std::runtime_error(eAsciiMsg("Error reading from file."));
    static const wchar_t hexCharacters[] = L"0123456789ABCDEF";
    cacheCharacters[0] = hexCharacters[rawData & 0x0F];
    cacheCharacters[1] = hexCharacters[rawData >> 4];
    cacheCurrentFor = filePosition;
}

Header for container
class hexFile {
public:
    HANDLE theFile;
    unsigned __int64 fileLength;
    hexFile(const std::wstring& fileName)
    {
        theFile = CreateFile(fileName.c_str(),GENERIC_READ,FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,NULL,NULL);
        if (theFile == INVALID_HANDLE_VALUE)
        {
            throw std::runtime_error(eAsciiMsg("Could not open file!"));
        }
        BY_HANDLE_FILE_INFORMATION sizeFinder;
        GetFileInformationByHandle(theFile, &sizeFinder);
        fileLength = sizeFinder.nFileSizeHigh;
        fileLength <<= 32;
        fileLength += sizeFinder.nFileSizeLow;
    };
    ~hexFile()
    {
        CloseHandle(theFile);
    };
    hexIterator begin()
    {
        hexIterator theIterator(this, true);
        return theIterator;
    };
    hexIterator end()
    {
        hexIterator theIterator(this, false);
        return theIterator;
    };
};

However, no matter what test case I try, the regex never matches. I'm assuming it's some conceptual problem with my iterator.. it's supposed to be a constant bidirectional iterator in all cases.
Anything I'm missing, or is there an easier way to do this?
Billy3

A: operator++(int) should be defined in terms of operator++(), not the other way around. Try switching them. Same for operator--.

A: This is quite a bit of code to read through; at first glance, I don't see anything.
For implementation notes, this sounds like more of an iostream than an iterator, which with buffering could be significantly faster. Boost has a library to help implement those.
If you want to use an iterator, they also have a library to help with that, it makes sure you get all the methods you need while simplifying the implementation a lot.
For debugging, I'd try for unit tests; that should hopefully point out the problem; start with something small, like a file with two characters, walk through in a debugger to see what's going on, and iterate until you pass everything.

A: Well... turns out I'm a complete idiot.
boost::xpressive::regex_match(fileInstance.begin(), fileInstance.end(), results, internalRegex);
Well... what I meant to do was
boost::xpressive::regex_search(fileInstance.begin(), fileInstance.end(), results, internalRegex);
The iterator never had a thing wrong with it.
Sorry for wasting other's time,
Billy3

A: Try using a Boost::transform_iterator.


text:
Q: How to check IP network block? Here I am checking to see if an IP address falls within a given range, ie: between the lowest IP number and the highest. I tried some found scripts that looped through the array, but they gave false responses. So I broke it down using the code below which worked for 2 days until it fell into the following network range:
IP address = 40.77.167.163
Low = 40.74.0.0
High = 40.125.127.255

function validateIP(ip, low, high)

    validateIP = False
    Dim ipArray, lowArray, highArray, ipTotal

    ipArray = split(ip, ".")
    lowArray = split(low, ".")
    highArray = split(high, ".")

    if CInt(ipArray(3)) >= CInt(lowArray(3)) And CInt(ipArray(3)) <= CInt(highArray(3))then
        validate3 = "1"
    end if
    if CInt(ipArray(2)) >= CInt(lowArray(2)) And CInt(ipArray(2)) <= CInt(highArray(2))then
        validate2 = "1"
    end if
    if CInt(ipArray(1)) >= CInt(lowArray(1)) And CInt(ipArray(1)) <= CInt(highArray(1))then
        validate1 = "1"
    end if
    if CInt(ipArray(0)) >= CInt(lowArray(0)) And CInt(ipArray(0)) <= CInt(highArray(0))then
        validate0 = "1"
    end if

    ipTotal = validate0 & validate1 & validate2 & validate3
    if ipTotal = "1111" then
       validateIP = True
    end if

end function

For some reason that is beyond me, it doesn't work with those values. But it does with smaller blocks.

A: If you're validating IPV4 addresses then it's quite straight forward to convert the ip addresses to numbers and check that a given ip falls between your low and high ranges (converting IPV6 addresses to numbers is a bit more complicated though, especially in VBScript)
Function ipv4ToNumber(ByVal ipv4)

    Dim i, pos, PrevPos, num

    For i = 1 To 4

        pos = InStr(PrevPos + 1, ipv4, ".", 1)
        If i = 4 Then pos = Len(ipv4) + 1
        num = Int(Mid(ipv4, PrevPos + 1, pos - PrevPos - 1))
        PrevPos = pos
        ipv4ToNumber = ((num Mod 256) * (256 ^ (4 - i))) + ipv4ToNumber

    next

End function

Function validateIP(ByVal ip, ByVal Low, ByVal High)

    ip = ipv4ToNumber(ip)
    Low = ipv4ToNumber(Low)
    High = ipv4ToNumber(High)

    If ip >= Low AND ip <= High Then
        validateIP = True
    Else
        validateIP = False
    End If

End Function

validateIP("40.77.167.163","40.74.0.0","40.125.127.255")

Output:

True

EDIT: If any Classic ASP developers are wanting to convert IPV6 addresses to numbers, it isn't possible using VBScript (to my knowledge), but it can be done in MySQL:
Function ipv6ToNumber(ByVal ipv6)

    Dim SQL : SQL = "SELECT CAST(" &_
        "CONV(" &_
            "SUBSTR(" &_
                "HEX(" &_
                    "INET6_ATON('" & ipv6 & "')" &_
                ")" &_
            ",1,16)" &_
        ",16,10" &_
    ")AS DECIMAL(65))" &_
    "*18446744073709551616" &_
    "+CAST(" &_
        "CONV(" &_
            "SUBSTR(" &_
                "HEX(" &_
                    "INET6_ATON('" & ipv6 & "')" &_
                ")" &_
            ",17,16)" &_
        ",16,10" &_
    ") AS DECIMAL(65))"

    'ipv6ToNumber = Execute using MySQL and return the number

End Function

Or use server-side javascript:
<script language="javascript" type="text/javascript" runat="server">

    function ipv6ToNumber(ip) {

        ip.replace("::",":0:0:0:")

        var parts = [];
        ip.split(":").forEach(function(it) {
            var bin = parseInt(it, 16).toString(2);
            while (bin.length < 16) {
                bin = "0" + bin;
            }
            parts.push(bin);
        })
        var bin = parts.join("");

        var dec = bigInt(bin, 2).toString();

        return dec;

    }

</script>


text:
Q: after"" node exampleScript.js "" ,cant write in cmd i got 2 scripts in folder "my",and in folder node_modules is mongodb folder installed.
code 1 :
   var mongo=require("mongodb");
var host= "127.0.0.1";
var port=mongo.Connection.DEFAULT_PORT;
var db= new mongo.Db("nodejs-introduction",new mongo.Server(host,port,{}), {safe: false})
db.open(function(error){

    console.log("we are connected" + " "+ host + ":" + port);

db.collection("user",function(error,collection){

    console.log("we got collection");

   collection.insert({
   id:"1",
   name:"Lauris Skraucis",
   twitter:"LauroSkr",
   email:"skciz@gmail.com",

},function(){

    console.log("sucessfully inserted Lauris")
});

collection.insert({
   id:"1",
   name:"Janis Skraucis",
   twitter:"Jask",
   email:"jask_dosiba@inbox.lv",

},function(){

    console.log("sucessfully inserted Janis")
});

});

});

and 2nd file
var mongo=require("mongodb");
var host= "127.0.0.1";
var port=mongo.Connection.DEFAULT_PORT;
var db= new mongo.Db("nodejs-introduction",new mongo.Server(host,port,{}));
db.open(function(error){

   console.log("we are connected" + " "+ host + ":" + port);

db.collection("user",function(error,collection){

   collection.find({"id:1"},function(error,cursor){
       cursor.toArray(function(error,users){
             if(users.length==0){
                 console.log("no user");
             }else{

console.log("found user",users[0]);
             }
       });
   });

});

});

after i write in cmd cd C:\Users\X\Desktop\my , then node the 1st file,i get
we are connected 127.0.0.1:27017
we got collection
sucessfully inserted Lauris
sucessfully inserted Janis
after that i cant write anything in cmd

A: because your app is running and waiting any interaction to log your data.
if you want to exit the app :  ctrl+c
if you want to run the app and be able to write in cmd :

*

*open another cmd :)

*run node using a compiler like netbeans or eclipse or even sublime-text


text:
Q: Jenkins - (private subnet) WebHook with Github does not trigger automatic build Problem :
I am working on a CI setup to configure github - Jenkins web hook for triggering builds with code commits on github. Below are the current configuration details

*

*My Jenkins is inside an AWS private subnet

*I have plugin: "GitHub Web Hook" configured with API URL, Username and OAuth token, Test Credentials gives a success message.

*I have "Build when a change is pushed to GitHub" selected under "Build Triggers"

Jenkins job works perfectly with the manual build. But it does not work (automatic build trigger) when a code commit is done on the github.
Need Help on:

*

*How can I debug in detail about this situation, if the "Git hub webhook" configuration test worked, can I say git hub is able to connect to my Jenkins which is in private or it does something else to test ?

*Please rectify / guide on the steps to get it working

A: I'll expand cody.codes comment given this one has sat idle for a while. You can configure a webhook payload delivery service such as smee.io which will intercept the webhooks that GitHub fires.
This Jenkins article outlines the setup instructions in detail, but the simplified overview is:

*

*GitHub event such as an SCM change occurs, and triggers a webhook to be fired to your configured Smee channel

*Smee channel (blue box on the image below) receives this webhook

*Jenkins server is subscribed to your custom smee channel, spots that there is a new event there, and triggers your job.

Jenkins only makes an outbound connection in this setup (which is required to subscribe to your Smee channel) so your Jenkins server can remain behind your firewall.

A: After spending some hectic hours, I have got it to a working state. Below is just a summary of what I have done:

*

*You can do it in two ways, Poll SCM or WebHooks (explained here)

*JenkinsURL/job/job-Name/scmPollLog is the place to check for polling logs

*I have moved my Jenkins into a public subnet (github needs to talk to jenkins)

*Go to https://github.com/settings/tokens and create your access token

*On Jenkins > Manage Jenkins > Configure system > configure GitHub Web Hook,
API URL - "https://api.github.com"   Username - your github user name,
OAuth token which was created above - Test it for success!!

*Navigate to job configuration and under Build Triggers, select "Build when a change is pushed to GitHub"

*Go to https://github.com/yourID/repoName/settings/hooks and Add a webhook

Payload URL - http://jenkinsIP:port/github-webhook/
Content type - application/x-www-form-urlencoded
Secret - none
Which events would you like to trigger this webhook? - Just the push event
Active > Add webhook

You can check commit a change into the github and github shall send a POST request to your jenkins server which will trigger the build. You can check the logs in Recent Deliveries section.

If this same can be done for a private jenkins server like using port forwarding, or any other way. Please update.


text:
Q: Micronaut Declarative HttpClient Timeout I have this declarative client:
@Retryable(attempts = "5", multiplier = "1.2")
@Client("\${client-url}")
@Headers(
    Header(name = USER_AGENT, value = "Micronaut Http Client"),
)
interface MyApiClient {

    @Get("/locations?location={location}")
    suspend fun validationLocation(@QueryValue location: String) : LocationResponse
}

I've set the client timeout to 30s with:
micronaut:
 http:
    client:
      read-timeout: 30s

And randomly I am getting:
Client <package> received HTTP error response: Read Timeout
    2021-08-02T23:09:13.069278169Z io.micronaut.http.client.exceptions.ReadTimeoutException: Read Timeout
    2021-08-02T23:09:13.069283269Z  at io.micronaut.http.client.exceptions.ReadTimeoutException.<clinit>(ReadTimeoutException.java:26)
    2021-08-02T23:09:13.069287569Z  at io.micronaut.http.client.netty.DefaultHttpClient$11.exceptionCaught(DefaultHttpClient.java:2301)
    2021-08-02T23:09:13.069291069Z  at io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:302)
    2021-08-02T23:09:13.069306269Z  at io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:281)
    2021-08-02T23:09:13.069309969Z  at io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:273)
    2021-08-02T23:09:13.069313269Z  at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireExceptionCaught(CombinedChannelDuplexHandler.java:424)
    2021-08-02T23:09:13.069316669Z  at io.netty.channel.ChannelHandlerAdapter.exceptionCaught(ChannelHandlerAdapter.java:92)
    2021-08-02T23:09:13.069319769Z  at io.netty.channel.CombinedChannelDuplexHandler$1.fireExceptionCaught(CombinedChannelDuplexHandler.java:145)
    2021-08-02T23:09:13.069323069Z  at io.netty.channel.ChannelInboundHandlerAdapter.exceptionCaught(ChannelInboundHandlerAdapter.java:143)
    2021-08-02T23:09:13.069326169Z  at io.netty.channel.CombinedChannelDuplexHandler.exceptionCaught(CombinedChannelDuplexHandler.java:231)
    2021-08-02T23:09:13.069329469Z  at io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:302)
    2021-08-02T23:09:13.069332669Z  at io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:281)
    2021-08-02T23:09:13.069335869Z  at io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:273)
    2021-08-02T23:09:13.069339069Z  at io.netty.handler.timeout.ReadTimeoutHandler.readTimedOut(ReadTimeoutHandler.java:98)
    2021-08-02T23:09:13.069342369Z  at io.netty.handler.timeout.ReadTimeoutHandler.channelIdle(ReadTimeoutHandler.java:90)

What can the cause be to this very annoying behaviour?

A: This question seems to concern the same issue: Micronaut ReadTimeoutException
Apparrently the configuration is not injected. You might have to set it programmatically.

A: Apparently removing the suspend from the function and making it return a Single<LocationResponse> made the time-outs disappear.


text:
Q: How to balance between two arrays such as the difference is minimized? I have an array A[]={3,2,5,11,17} and B[]={2,3,6}, size of B is always less than A. Now I have to map from every element B to distinct elements of A such that the total difference sum( abs(Bi-Aj) ) becomes minimum (Where Bi has been mapped to Aj). What is the type of algorithm?
For the example input, I could select, 2->2=0 , 3->3=0 and then 6->5=1. So the total cost is 0+0+1 = 1. I have been thinking sorting both the arrays and then take the first sizeof B elements from the A. Will this work?

A: It can be thought of as an unbalanced Assignment Problem.
The cost matrix shall be the difference in values of B[i] and A[j]. You can add dummy elements to B so that the problem becomes balanced and put the costs associated very high.
Then Hungarian Algorithm can be applied to solve it.
For the example case A[]={3,2,5,11,17} and B[]={2,3,6} the cost matrix shall be:
.   3  2  5 11 17
2   1  0  3  9 15
3   0  1  2  8 14
6   3  4  1  5 11
d1 16 16 16 16 16
d2 16 16 16 16 16


text:
Q: Pick the first timestamp before a gap, but the last one of the day if there is no suitable gap I have a TIMESTAMP column:
dates
2021-06-24 05:47:05
2021-06-24 09:47:05
2021-06-24 13:47:05
2021-06-24 17:47:05

I want to pick the first timestamp of a given day that is 3 hours or more  before the next next timestamp of that same day.
expected output:

2021-06-24 05:47:05

However, if there is no timestamp that is more than 3 hours before any other (on that given day), then the last timestamp of that day should be returned.

A: This is a completely revised answer which is much more efficient than the previous one. The old answer can be seen either by viewing the edit history or as a footnote at the bottom of this post.
A fiddle for all the code below is to be found at the fiddle here.
So, we have our test table:
CREATE TABLE test
(
  the_date TIMESTAMP NOT NULL
);

Populate it - added records for a day with no gaps > 3 hours:
INSERT INTO test VALUES

('2021-06-23 05:47:05'::TIMESTAMPTZ),     -- NO gaps > 3 hours on this date!
('2021-06-23 07:47:05'::TIMESTAMPTZ),
('2021-06-23 09:47:05'::TIMESTAMPTZ),
('2021-06-23 11:47:05'::TIMESTAMPTZ),
('2021-06-23 13:47:05'::TIMESTAMPTZ),
('2021-06-23 14:47:05'::TIMESTAMPTZ),
('2021-06-23 16:47:05'::TIMESTAMPTZ),
('2021-06-23 17:47:05'::TIMESTAMPTZ),

('2021-06-24 05:47:05'::TIMESTAMPTZ),  -- TWO gaps > 3 hours on this date

                                      -- 1st gap > 3 hours

('2021-06-24 09:47:05'::TIMESTAMPTZ),

                                      -- 2nd gap > 3 hours

('2021-06-24 13:47:05'::TIMESTAMPTZ),

('2021-06-24 14:47:05'::TIMESTAMPTZ),  -- added for testing
('2021-06-24 16:47:05'::TIMESTAMPTZ),  -- added for testing

('2021-06-24 17:47:05'::TIMESTAMPTZ);

And (demonstrating the logic) then ran the following SQL:
SELECT
  the_date::DATE AS dat,
  the_date AS td,
  LEAD(the_date)
    OVER (PARTITION BY the_date::DATE
           ORDER BY the_date ASC) AS l_td,
  LEAD(the_date)
    OVER (PARTITION BY the_date::DATE
            ORDER BY the_date ASC) - the_date AS diff  -- for demonstration
FROM                                                   -- purposes - see diffs
  test                                                 -- > 3 HOUR - 2 on 24/06
ORDER BY dat, td;

Result:
       dat                      td                   l_td   diff
2021-06-23  2021-06-23 05:47:05+01  2021-06-23 07:47:05+01  02:00:00
2021-06-23  2021-06-23 07:47:05+01  2021-06-23 09:47:05+01  02:00:00
2021-06-23  2021-06-23 09:47:05+01  2021-06-23 11:47:05+01  02:00:00
2021-06-23  2021-06-23 11:47:05+01  2021-06-23 13:47:05+01  02:00:00
2021-06-23  2021-06-23 13:47:05+01  2021-06-23 14:47:05+01  01:00:00
2021-06-23  2021-06-23 14:47:05+01  2021-06-23 16:47:05+01  02:00:00
2021-06-23  2021-06-23 16:47:05+01  2021-06-23 17:47:05+01  01:00:00
2021-06-23  2021-06-23 17:47:05+01  NULL                    NULL
2021-06-24  2021-06-24 05:47:05+01  2021-06-24 09:47:05+01  04:00:00
2021-06-24  2021-06-24 09:47:05+01  2021-06-24 13:47:05+01  04:00:00
2021-06-24  2021-06-24 13:47:05+01  2021-06-24 14:47:05+01  01:00:00
2021-06-24  2021-06-24 14:47:05+01  2021-06-24 16:47:05+01  02:00:00
2021-06-24  2021-06-24 16:47:05+01  2021-06-24 17:47:05+01  01:00:00
2021-06-24  2021-06-24 17:47:05+01  NULL                    NULL
14 rows

We've used the LEAD() window function. Window functions are extremely powerful and I would stongly urge you to put some effort into  learning how to use them - they will repay that effort many times over!

*

*It provides a comparison between the value of the_date and the value following it according to the criteria in the ORDER BY - you can do lots of clever stuff by varying the ORDER BY clause in the LEAD() function itself - that and varying other parameters can be seen here.

*The PARTITION BY the_date::DATE clause is to give separate results for every  date that is in your dataset. Note in particular the NULLs - you can't have a LEAD that spans days thanks to the partitioning, so the LEAD value for the last timestamp on any given day will always be NULL - this relates to the requirements - see below.
Also, note that NULL minus anything is NULL (same for NULL plus...) - we say that NULLs "propagate".
So, now we run this SQL:
WITH leads AS
(
    SELECT
      the_date::DATE AS dat, the_date AS td, LEAD(the_date)
          OVER (PARTITION BY the_date::DATE) AS l_td
    FROM
      test
)
SELECT DISTINCT ON(dat)
    dat AS "The date", td AS "Gap start or last ts"
FROM leads
WHERE l_td - td > INTERVAL '3 HOUR'
   OR l_td IS NULL
ORDER BY dat, td;

Result:
The date    Gap start or last ts
2021-06-23  2021-06-23 17:47:05+01
2021-06-24  2021-06-24 05:47:05+01

The desired outcome! But, what's going on? From here:

PostgreSQL has a really interesting and powerful construct called
SELECT DISTINCT ON. No, this is not a typical DISTINCT. This is
different. It is perfect when you have groups of data that are similar
and want to pull a single record out of each group, based on a
specific ordering.

or, put another way (from the same link):

With DISTINCT ON, You tell PostgreSQL to return a single row for each
distinct group defined by the ON clause. Which row in that group is
returned is specified with the ORDER BY clause.

Or from the PostgreSQL documentation here:

SELECT DISTINCT ON ( expression [, ...] ) keeps only the first row of
each set of rows where the given expressions evaluate to equal. The
DISTINCT ON expressions are interpreted using the same rules as for
ORDER BY (see above). Note that the "first row" of each set is
unpredictable unless ORDER BY is used to ensure that the desired row
appears first. For example:
SELECT DISTINCT ON (location) location, time, report
    FROM weather_reports
    ORDER BY location, time DESC;

retrieves the most recent weather report for each location. But if we
had not used ORDER BY to force descending order of time values for
each location, we'd have gotten a report from an unpredictable time
for each location.
The DISTINCT ON expression(s) must match the leftmost ORDER BY
expression(s). The ORDER BY clause will normally contain additional
expression(s) that determine the desired precedence of rows within
each DISTINCT ON group.

As you can see, this (like window functions) is obviously a very powerful tool in the PostgreSQL programmer's arsenal and is well worth taking the time and the effort to learn.
An interesting alternative approach would be to use the ROW_NUMBER() window function, if say you want the first two gaps or the last record, as follows:
WITH leads AS
(
    SELECT
      the_date::DATE AS dat, the_date AS td,
      LEAD(the_date)
          OVER (PARTITION BY the_date::DATE) AS l_td
    FROM
      test
),
gaps AS
(
    SELECT
      dat, td,
      ROW_NUMBER()
          OVER (PARTITION BY dat ORDER BY td) AS rn
    FROM leads
    WHERE (l_td - td > INTERVAL '3 HOUR')
      OR (l_td IS NULL)
)
SELECT
    dat, td
FROM gaps
WHERE rn <= 2  -- NOTE 2!
ORDER BY dat, td;

Result:
       dat                      td
2021-06-23  2021-06-23 17:47:05+01
2021-06-24  2021-06-24 05:47:05+01
2021-06-24  2021-06-24 09:47:05+01

Note that we now have two records for 2021-06-24.
Finally, and just for the record, the original solution:
WITH long_gaps AS
(
  SELECT dat, MIN(td) AS gap
  FROM
  (
    SELECT
      the_date::DATE AS dat, the_date AS td, LEAD(the_date) OVER (PARTITIION BY the_date::DATE) AS l_td
    FROM
      test
  ) AS t1
  WHERE l_td - td > INTERVAL '3 HOUR'
  GROUP BY dat
),
short_gaps AS
(
  SELECT the_date::DATE AS dat2, MAX(the_date)
  FROM test
  WHERE the_date::DATE NOT IN (SELECT dat FROM long_gaps)
  GROUP BY dat2

)
SELECT dat AS "The date", gap AS "Gap start or last ts" FROM long_gaps
UNION
SELECT * FROM short_gaps
ORDER BY 1;  -- parameter 1 which ORDERs BY the first field in the query

Result:
  The date     Gap start or last ts
2021-06-23   2021-06-23 17:47:05+01
2021-06-24   2021-06-24 05:47:05+01

A performance analysis of the 3 solutions is given at the bottom of the fiddle - it shows that the DISTINCT ON solution is significantly more performant than the others - however the ROW_NUMBER() has the potential to be more flexible! However, a word of warning - a performance analysis on a very small dataset on  a server over which we have no control, nor any idea of what's happening elsewhere is potentially flawed - I would advise that you benchmark with reasonable datasets on your own hardware.
In future, when you are asking questions of this nature, could you provide a fiddle with sample data covering all of your cases - i.e. in this case, where there are gaps and where there are not. This reduces the possibility of error and eliminates duplication of effort - help us to help you. Also, please always include your version of PostgreSQL.


text:
Q: How to return each element of a list as a new line in AppleScript? I'd like to return the variable additionalactions as a paragraph delimited string so that it is easy to split back in zsh. Like so, it is returned as a comma separated string.
#!/bin/zsh

WER=("Option 1" "Option 2" "Option 3")

read -r -d '' SELECTWER << EOF
set actions to the paragraphs of "$(printf '%s\n' "${WER[@]}")"
set additionalactions to choose from list actions with prompt "Additional Actions:" default items {"Multiple Instances"} with multiple selections allowed
return additionalactions
EOF

WER=$(osascript -e "$SELECTWER");

WER prints Option 2, Option 3. (Assuming Option 2 and Option 3 were selected in the dialog)
WER should print Option 2\nOption3. Then I can read the individual lines into an array.

A: #!/bin/zsh

WER=("Option 1" "Option 2" "Option 3")

osascript - "${(@)WER}" << EOF
    on run argv
        set acts to choose from list argv with multiple selections allowed
        if acts is false then return ""
        set text item delimiters to linefeed
        return acts as string
    end run
EOF


text:
Q: Saving credit card data on a mobile device with two way encryption Very often, we can find mobile applications which provide in-app purchase store credit card details, allowing users to buy things in a convenient manner. I am planning to implement the same mechanism on the client side. The following points are what I can think of.
First, there are several variables involved:

*

*credit_card_number

The credit card number used for the purchase.

*cvc

The CVC of the credit card being used.

*expiry_date

The expiry date of the credit card being used.

*card_info_key

The key used to encrypt and decrypt the credit card information stored in the client device.

Is it viable to save card_info_key on the server, then use it to encrypt and decrypt credit card information on the client device as follows?
// credit card information entered by user
var credit_card_number = '1234123412341234';
var cvc = '789';
var expiry_date = '12-2020';

// the key is retrieved from server
var card_info_key = getCardInfoKeyFromServer(current_user);

var card_info = {
    'number': credit_card_number,
    'cvc': cvc,
    'expiry': expiry_date
};

// an encrypted token is expected
var encryptedCardInfo = encryptCardInfo(card_info, card_info_key);

// an object containing the same data as card_info should be returned
var decryptedCardInfo = decryptCardInfo(encryptedCardInfo, card_info_key);

Besides, what encryption and decryption algorithm should I use?

A: This is not a technical issue because you simply aren't allowed to implement such a functionality (unless you make the app PC-DSS compliant).
See How to save credit card data in a database? for more info and links.


text:
Q: jquery tab in fluid layout I'm facing a problem that I don't manage to solve by myself... That's why I need your help ;-)
My problem is when I add a jquery tab in the fluid part of an fixed-left-list/fluid-detail layout. The top of the tab is totally destroyed.
I found that when I clear the float of the detail div, the tab is back to normal. But actually that's not really what I want to do... :-(
Here is the code: http://jsfiddle.net/Mr63q/
What is your advice on my problem ?
Many thanks in advance!
Cedric.

A: Already discussed:
CSS Layout: 2 column fixed-fluid (again)
.ui-helper-clearfix {
    clear: none;
    overflow: hidden;
}


text:
Q: combine two element in an array perl I want to compare two sequences using standalone blastn.
But before I can do that I have to cut the sequence into 1020nt of each fragment. If the last fragment is less than 1020nt, i have to merge (the sequence) in the last fragment with sequence in the previous fragment . For example I cut a sequence into 1020nt and get 7 fragments. But the 7th fragment is less than 1020nt, so i have to merged it into the 6th fragment. Is anyone know how to do this using Perl language?
This is my code:
while(<QR>){

    chomp;
    s/>//g;

    my ($scaf,$seq)= split /\n/,$_,2;
    my $scaf_name = (split /\s+/,$scaf)[0];
    $seq =~ s/\s+//g;
    my @cut = ($seq =~ /(.{1,$chop_len})/g);

    if (length($#cut) < 1020) {
        $#cut="@cut[-2 .. -1]"; # i get error here
    }
    else {
    }

    print $#cut;
    for my $cut_num (0..$#cut){
        my $sgmID = "$scaf_name\_$cut_num";
        print CR ">$sgmID\n$cut[$cut_num]\n";
    }
}

close QR;
close CR;

Actually I found this Perl script on the internet, and modified it so that I can merged the last two fragments.

A: You need to remove the last cut and append it to the second-to-last cut using the .= concatenation operator:
Here is a simplified example:
#!/usr/bin/env perl

use warnings;
use strict;

my $total_length = 100;
my $chop_length  = 14;
my @letters = qw( A C G T );

my $long_string = join '', map { $letters[ int rand scalar @letters ] } ( 1 .. $total_length );
print "Long string ($total_length chars) :\n$long_string\n";
print '-'x$total_length . "\n";
my @cut = ($long_string =~ /(.{1,$chop_length})/g);

my $last_cut = pop @cut; # Take last one off
if (length $last_cut < $chop_length) {
    $cut[$#cut] .= $last_cut; # Concatenate it to the (now) last one
} else {
    push @cut, $last_cut; # Put it back, it has the right length
}

print "Parts cut into >= $chop_length char length pieces.\n";
for my $part (@cut) {
    print $part . "\n";
}

Output
Long string (100 chars) :
CCATCCTGCACATTCGGTGATTTATCAGAAGTAAGATCCTCGTCCCACTGACCGTGCGGGGATACGGAGCTCAAACAGAGAGAAACGGTTGGTCTGTAGA
----------------------------------------------------------------------------------------------------
Parts cut into >= 14 char length pieces.
CCATCCTGCACATT
CGGTGATTTATCAG
AAGTAAGATCCTCG
TCCCACTGACCGTG
CGGGGATACGGAGC
TCAAACAGAGAGAA
ACGGTTGGTCTGTAGA

A: The issue with
if (length($#cut) < 1020) {
    $#cut="@cut[-2 .. -1]"; # i get error here
}

is that it is attempting to assign a string to $#cut. $#cut is the last index of @cut, so it expects an integer value.
Something like this should work:
if (length($#cut) < 1020) {
    $cut[$#cut-1] = join '', @cut[-2 .. -1];
    $#cut -= 1;  # Remove last element from @cut
}


text:
Q: Draw border around a circle with animation I want a 2px border to draw around a circle slowly when i hover on the circle. Something like this https://jsfiddle.net/cf6fqmbx/
I tried the same method, but I'm having content under the circle, so the box shadow is overlapping the content when i hover on it. Anyway to achieve this(CSS3 or jQuery)?
My current fiddle https://jsfiddle.net/Lkch05ok/3/

  Lorem Ipsum Dolor

A: Hope this is what you want.
To make the border animation slow, just increase the time delay. Like I've done here.
.circle:hover {
  animation: border 2s ease 1 forwards;
}

updated code
EDITED

html {
  height: 100%;
}
body {
  height: 100%;
  background: #ddd;
}
.header{
  width:100%;
  height:100px;
  background:cyan;
  z-index: 9999;
}
.circle_holder {
  width: 150px;
  margin: 0 auto;
  padding: 10px;
  overflow: hidden;
}
.circle {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: red;
  box-shadow: 60px -60px 0 2px #dddddd, -60px -60px 0 2px #dddddd, -60px 60px 0 2px #dddddd, 60px 60px 0 2px #dddddd, 0 0 0 2px #dddddd;
}
.circle:hover {
  animation: border 2s ease 1 forwards;
  cursor: pointer;
}
@keyframes border {
  0% {
    box-shadow: 60px -60px 0 2px #dddddd, -60px -60px 0 2px #dddddd, -60px 60px 0 2px #dddddd, 60px 60px 0 2px #dddddd, 0 0 0 2px black;
  }
  25% {
    box-shadow: 0 -125px 0 2px #dddddd, -60px -60px 0 2px #dddddd, -60px 60px 0 2px #dddddd, 60px 60px 0 2px #dddddd, 0 0 0 2px black;
  }
  50% {
    box-shadow: 0 -125px 0 2px #dddddd, -125px 0px 0 2px #dddddd, -60px 60px 0 2px #dddddd, 60px 60px 0 2px #dddddd, 0 0 0 2px black;
  }
  75% {
    box-shadow: 0 -125px 0 2px #dddddd, -125px 0px 0 2px #dddddd, 0px 125px 0 2px #dddddd, 60px 60px 0 2px #dddddd, 0 0 0 2px black;
  }
  100% {
    box-shadow: 0 -125px 0 2px #dddddd, -125px 0px 0 2px #dddddd, 0px 125px 0 2px #dddddd, 120px 40px 0 2px #dddddd, 0 0 0 2px black;
  }
}
span {
  position: absolute;
  bottom: -50px;
  color: #333;
  text-transform: uppercase;
  text-align: center;
  font-weight: bold;
}

  Lorem Ipsum Dolor


text:
Q: Grails UrlMapping with hypenated id returns 404 I've changed the default UrlMapping from
    "/$controller/$action?/$id?(.$format)?"{
        constraints {
            // apply constraints here
        }
    }

to
    "/$controller/$action(-$id)??(.$format)?"{
        constraints {
            // apply constraints here
        }
    }

however then I navigate to item/item-1 I get a page not found response. While actions such as item/items seem to work normally. Is it not possible to have a hyphen separated id?


text: Q: 500 server error while trying to Checkout I have a magento shop which is under development. While Im trying to checkout any product, it is giving me a 500 error. It started when i tried to implement Cash on Delivery from admin backend, payment methods. It gave me 500 error. So i tried to install another Cash on Delivery extension which gave me 500 error in entire checkout process. I tried to change the app folder, yet the error persists, so i believe its either server error or DB error. How can i Fix it


text:
Q: mysqli sub query with prepared statement returning boolean so i prepared a query that already works in mysql(tested in phpmyadmin) but I have problem getting the results using mysqli class and its really weird not to get the results because I believe that the query is correct. Can anyone point out my mistake in the following code.
<?php

include_once __DIR__ . '/includes/init.php';

$sql = 'SELECT
                    `purchase_order`.`id`,
                    `purchase_order`.`po_date` AS po_date,
                    `purchase_order`.`po_number`,
                    `purchase_order`.`customer_id` AS customer_id ,
                    `customer`.`name` AS customer_name,
                    `purchase_order`.`status` AS po_status,
                    `purchase_order_items`.`product_id`,
                    `purchase_order_items`.`po_item_name`,
                    `product`.`weight` as product_weight,
                    `product`.`pending` as product_pending,
                    `product`.`company_owner` as company_owner,
                    `purchase_order_items`.`uom`,
                    `purchase_order_items`.`po_item_type`,
                    `purchase_order_items`.`order_sequence`,
                    `purchase_order_items`.`pending_balance`,
                    `purchase_order_items`.`quantity`,
                    `purchase_order_items`.`notes`,
                    `purchase_order_items`.`status` AS po_item_status,
                    `purchase_order_items`.`id` AS po_item_id
                  FROM (SELECT id, po_date, po_number, customer_id, status
            FROM purchase_order  GROUP BY  id   DESC  LIMIT ?, ? ) as purchase_order
                  INNER JOIN customer ON `customer`.`id` = `purchase_order`.`customer_id`
                  INNER JOIN purchase_order_items ON `purchase_order_items`.`po_id` = `purchase_order`.`id`
                  INNER JOIN product ON `purchase_order_items`.`product_id` = `product`.`id`
                   GROUP BY  id';

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$statement = $mysqli->prepare($sql);
$statement->execute();
$offset = 0;
$perpage = 10;
$statement->bind_param('ii', $offset, $perpage);
$result = $statement->get_result();
while ($row = $result->fetch_assoc())
{
    echo '<pre>';
    print_r($row);
    echo '</pre>';
}

Thanks in advance.

A: The sequence in which you prepare/bind and execute the statement and values is incorrect...
$statement = $mysqli->prepare($sql);
$offset = 0;
$perpage = 10;
$statement->bind_param('ii', $offset, $perpage);
$statement->execute();

You need to use bind_param() before the execute() so that it knows what values to use.


text: Q: Горячая клавиша получения списка классов по блоку VS Code кода Смотрел на 1:54:00-1:55:10 видеоурок Адаптивной верстки. В этой полтораминутной части показано, что по выделенной части блока можно получить список классов и вставить их в css код. С помощью каких горячих клавиш это можно сделать?


text:
Q: How do I create non fully connected layers in skflow? I want to create a more complex architecture than requires layers connected in a custom way.Can I achive this in skflow ? And if not which framework is best ?
Thanks

A: You can define your own custom model function or even build your own estimator. For example, you can find a ResNet example under tensorflow/examples/learn implemented using TF.Learn (originally skflow).


text:
Q: I use acrylic paint/paints
Is it oil paintings?
No, I use acrylic paint/paints.

Should paint be in plural here or what is idiomatic/makes more sense? I have seen both used.

A: See Doesn't or don't in "watercolor or any type of water-based paint {doesn't/don't} work", where one of the answers transparently switches between examples featuring singular (uncountable, mass-noun) watercolor and the countable form watercolors (which could be seen as "short for" the more obviously countable form watercolor paints). You've seen both used because they are - and in your exact context it's entirely a stylistic choice, but you'd rarely hear a native speaker ask "Is it oil paintings?" In almost all contexts, it's "Are they oil paintings?"
When talking about painting a wall or house you would say "I used red paint" or "I used emulsion paint". If talking about art, you're more likely to use the plural, but could still use the singular. The plural has more artistic connotations. To me, the plural suggests you have your own valued collection of tubes of oil or acrylic paint (which would be referred to as "my paints") rather than just viewing paint as a tool or medium that you don't care about.


text:
Q: Explicitly specify generic type constraint when calling function I am wondering wether or not is possible in Swift to explicitly specify the generic type of a generic function. Assuming I have the following function definition which basically creates an empty array of a generic type T:
func bar<T>() -> [T] {
    return [T]()
}

How would I be able to call it?
var foo = bar()

results in

generic parameter 'T' could not be inferred

which makes total sense since there really is no information to infer anything here.
But unfortunately my attempt at specifying the type constraint explicitly via the following failed as well:
var foo = bar<Int>()

error: cannot explicitly specialize a generic function

*

*Why am I not able to do that?

*Is it a language specification to not be able to explicitly specify the generic type?

*What way is there to specify the generic type of the function?

A:
What way is there to specify the generic type of the function?

The generic type can be inferred from the context:
func bar<T>() -> [T] {
    return [T]()
}

let val1 = bar() as [Int] // or:
let val2 : [Int] = bar()

(I cannot answer the other questions.)

A: The language doesn't allow you to explicitly specialize the function. I don't know why they implemented it that way. You're more likely to get an answer to that question on the swift-users mailing list.
The typical way to fix this is to make the function take the type as an argument:
func bar<T>(_: T.Type) -> [T] {
    return [T]()
}

bar(Int.self)
// Result: [], with type Array<Int>


text:
Q: XCode Throwing Errors @implementation I'm trying to learn some of the basics of developing OS X apps with XCode and Objective-C, but I am already running into problems.
I have a project I made from a while back which worked very well for me, however, when I try to replicate the results I had last time, I run into numerous errors.
I have two files, a .c and a .h named "AppDelegate"
in AppDelegate.h:
    #import <Cocoa/Cocoa.h>
    #import <WebKit/WebView.h>

    @interface AppDelegate : NSObject {
        IBOutlet WebView *gameFrame;
    }

    @end

then, in AppDelegate.c:
    #import "AppDelegate.h"

    @implementation AppDelegate
    -(void)awakeFromNib
    {

    }
    @end

In IB, there is an NSObject named 'AppDelegate' and its class is 'AppDelegate'.
However, when I try to run this, I get 11734 errors...
When I click on the error icon at the bottom of the XCode window, it lists a bunch of code that seems to be involving NSStrings, but I cant make any sense of it...
Also, within my code, the
    @end

line in both the .c and the .h are highlighted with an error saying:
'Expected identifier or '(' before '@' token.'

I don't understand what XCode is tripping up on when it tries to compile, I don't see any logical place for a '(' to go and I don't think I left anything unidentified.
Any help would be appreciated.

A: That's because that isn't valid C code.
You named your module file AppDelegate.c, which indicates that it contains source code written in (more or less) pure C. But it does not: You wrote a class interface and implementation in Objective-C, which is a superset of C (all C is valid Objective-C, but not all Objective-C is valid C—in particular, classes aren't).
For this, you must name the module file AppDelegate.m (or anything else, as long as it ends with .m; naming it after the class is a convention worth following). The .m suffix indicates a module (usually containing a class implementation) written in Objective-C.
So, just rename your module file from AppDelegate.c to AppDelegate.m. Make sure you do this in Xcode, not the Finder: If you do it in the Finder, Xcode will only care that there is no longer a file named AppDelegate.c; it won't notice the rename.
For your convenience in creating future classes, Xcode provides a template in the "New File" panel for creating subclasses of certain Cocoa classes; your AppDelegate should be a subclass of NSObject, and templates are also provided for NSView, NSDocument, UIView, UIViewController, and a few others. The files created by the template will already have the correct extensions.


text:
Q: not able to send confirmation email while signing up using rest-auth i am getting an error while using rest framework it says Exception Type: AttributeError at /rest-auth/registration/ Exception Value: module 'users' has no attribute 'get_full_name()'  Request information: USER: AnonymousUser
Template error:

In template /Users/apple/Desktop/workffbase/workforfilms-master-DJG/templates/account/email/email_confirmation_message.txt, error at line 2
         module 'users' has no attribute 'get_full_name()'
         1 : {% load account %}
         2 :  {% user_display user.email as user_display %}
         3 : {% load i18n %}
         4 : {% autoescape off %}
         5 : {% blocktrans with site_name=current_site.name site_domain=current_site.domain %}Hello from {{ site_name }}!
         6 :
         7 : You're receiving this e-mail because user {{ user_display }} has given yours as an e-mail address to connect their account.
         8 :
         9 : To confirm this is correct, go to {{ activate_url }}
         10 :
         11 : {% endblocktrans %}
         12 : {% endautoescape %}

A: just needed to modify ACCOUNT_USER_DISPLAY to correct value in setting files but still after verification no email received through smtp.


text:
Q: Is a DelegateCommand the same as an "Attached Behavior"? I have been using the DelegateCommand found in the MVVM Visual Studio template at CodePlex. This works very nicely for having Views be able to execute commands on their ViewModel.
I read somewhere that in MVVM "attached behaviors" should be used. As far as I can tell, "attached behaviors" are the same type of pattern as DelegateCommand but are used by Silverlight since it does not have commands.
Is this correct? Or are "attached behaviors" something different in kind and worth learning in addtiion to DelegateCommand?

A: A DelegateCommand (or a RelayCommand, which is almost the same but accepts a parameter) is just a light-weight implementation of the ICommand interface that allows a ViewModel to expose commands easily.
Attached behaviors are a way to link an event to a command. For instance, most WPF controls don't have a Command property, so you can't normally define a command to react to their events. With attached behaviors, you can "bind" any event of any control to a command of your ViewModel.
Have a look at Marlon Grech's implementation, which seems the most flexible to me


text:
Q: TypeError array.map is not a function I'm building a React app that pulls data from an S3 bucket.
const Products = () => {
const [photos, setPhotos] = useState([]);
useEffect(() => {
    getBucket().then( data => setPhotos({photos: data}))
  }, [])
return (
    <Fragment>
        {photos.length === 0 ? (

Loading...

            ) : (
                photos.map((photo)=>(
                    <ProductCard img={photo.Key} />
                ))
            )
        }
    </Fragment>
)}

I get TypeError: photos.map is not a function;
This is what I get back from S3.
{"photos":[{"Key":"Blusa-con-tejido-y-Pantalon-(1).jpg","LastModified":"2020-10-14T23:03:56.000Z","ETag":"\"211fa91695f9cf5c0db52b7d8696a6b5\"","Size":116003,"StorageClass":"STANDARD"},{"Key":"Blusa-con-tejido-y-Pantalon-(2).jpg","LastModified":"2020-10-14T23:03:56.000Z","ETag":"\"a27e32e9bdf275b98dd6b12d747c7ff4\"","Size":142108,"StorageClass":"STANDARD"},{"Key":"Blusa-con-tejido-y-Pantalon-(3).jpg","LastModified":"2020-10-14T23:03:56.000Z","ETag":"\"2dae6a85ffb74130317dee3577ab42c5\"","Size":159906,"StorageClass":"STANDARD"},{"Key":"Blusa-con-tejido-y-Pantalon-(4).jpg","LastModified":"2020-10-14T23:03:56.000Z","ETag":"\"f3f2f5716f2d0da2f4f7d756a1302801\"","Size":128466,"StorageClass":"STANDARD"},{"Key":"Blusa-con-tejido-y-Pantalon-(5).jpg","LastModified":"2020-10-14T23:03:56.000Z","ETag":"\"c4135e0516e6fc5f17fbcea05bbb0aa5\"","Size":125733,"StorageClass":"STANDARD"},{"Key":"Blusa-con-tejido-y-Pantalon-(6).jpg","LastModified":"2020-10-14T23:03:56.000Z","ETag":"\"2952dcf05490e21617176280bebdd5a2\"","Size":122684,"StorageClass":"STANDARD"},{"Key":"Blusa-con-tejido-y-Pantalon-(7).jpg","LastModified":"2020-10-14T23:03:56.000Z","ETag":"\"1506f3196095edd66a0d4c85936a302f\"","Size":106216,"StorageClass":"STANDARD"}]}

Any help is appreciated.

A: You're setting your photos state to data but data is not an array–it's an object with a property called photos, and THAT is the array. Change your useEffect to use that.
useEffect(() => {
    getBucket().then( data => setPhotos({photos: data.photos}))
  }, [])

A: setPhotos is wrong. you are currently passed json {photos: data}. you should pass the array as a param of the setPhotos
useEffect(() => {
    getBucket().then( data => setPhotos(data.photos))
  }, [])

A: I got it now. The issue has been that I used setPhotos incorrectly. My previous code was:
useEffect(() => {
    getBucket().then(data => setPhotos({photos: data}))
}, [])

The correct code should be:
useEffect(() => {
    getBucket().then(data => setPhotos(data))
}, [])

A: This can happen if the data type msgs is not an array. if you doing this
with "data" object from an API response. map is only available to arrays
since it lives on the array prototype array.prototype.map.
You cannot use map on an object.
like this:
const [photos, setPhotos] = useState([{}])


text:
Q: Is it possible to return IEnumerable of anonymous objects from DataContext.ExecuteQuery? I develop a reporting engine where reports are based on templates. Every template has string with SQL query and every report has specific values for SQL query parameters. To render a report I set parameters and call DataContext.ExecuteQuery method to get list of records. But to catch returned columns I have to know their names and have a class with corresponding properties.
Is it possible somehow to return IEnumerable of anonymous objects from DataContext.ExecuteQuery and then determine their properties using Reflection?
I need a LINQ equivalent for SqlDataReader.GetValues.
Thanks!

A: Until we have C# 4.0 with dynamiс keyword we can use this solution (slightly modified code from an article Executing arbitrary queries in LINQ to SQL by Octavio Hernández Leal):
public static class DataContextExtension
{
    public static IEnumerable<Dictionary<string, object>> ExecuteQuery(this DataContext dataContext, string query)
    {
        using (DbCommand command = dataContext.Connection.CreateCommand())
        {
            command.CommandText = query;
            dataContext.Connection.Open();

            using (DbDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (reader.Read())
                {
                    Dictionary<string, object> dictionary = new Dictionary<string, object>();

                    for (int i = 0; i < reader.FieldCount; i++)
                        dictionary.Add(reader.GetName(i), reader.GetValue(i));

                    yield return dictionary;
                }
            }
        }
    }
}

This extension method returns IEnumerable of Dictionary<> objects where keys are names of query columns.

A: Yes, you can do it.
Please have a look at this snippet.
class Program {
        static void Main(string[] args) {
            var persons = new Person[]{
                new Person{Age=22,Name="John Doe",Id=1},
                new Person{Age=23,Name="Jack Smith", Id=2},
                new Person{Age=34,Name="Sara Parker", Id=3}
            };
            var anonData = GetAnonTypes(persons);
            foreach (var item in anonData as IEnumerable) {
                //use reflection to access propties
            }
        }
        static object GetAnonTypes(IEnumerable<Person> persons) {
            var query=from p in persons  select new{
                Id=p.Id,
                Name=p.Name
            };
            return query;
        }
    }

    public class Person {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }


text:
Q: How to define current product thumbnail in woocommerce? I am currently working on a shop page which works with Wordpress + Woocommerce Plugin. I edited the woocommerce Files so that I have custom products, menus and so on.
I managed to get current images from my products, but now I want them to appear on click (the little image Icon, on the Screenshot)

But instead of showing the current product image it shows the first image of each category
.
Here is my current code that loads the wrong product thumbnail:

   <a itemprop="image" href="<?php echo wp_get_attachment_url( get_post_thumbnail_id() ); ?>" class="zoom" rel="thumbnails" title="<?php echo get_the_title( get_post_thumbnail_id() ); ?>">
   <?php echo get_the_post_thumbnail(  $post->ID, apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ) ) ?>

It is located in woocommerce/content-product.php.
Thank you in advance
Nico

A: So this is the solution, I had to create dynamic IDs. As I wrote it was always the same image, the reason of this was that there was only one ID and not multiple/dynamic.
This was the code I had to add to the id:
<div id="modal-<?php echo $product->id ?>" class="modal">

And here is the other one:
<a data-target="modal-<?php echo $product->id; ?>" class="modal-trigger">photo


text:
Q: UIScrollview does not scroll all the way through So I have a scrollview that I dropped into my view (in the nib file), hence nothing has been done programmatically yet. I have then placed 9 buttons spaced out in this scrollview. Now the scrollview works perfectly, it scrolls smoothly and everything, however it does not scroll all the way down to the 9th button. It makes it as far as the 7th button, which I assume is the screen size, and scrolls now further. Do I have to do anything programmatically to fix this or can I just edit the nib file?

A: Make sure You have declared object for scrollview and connected properly and setDelegate too in xib.
and then
In ViewDidLoad please place this code..
int width = 320; (if iphone)

int height = 440; (if iphone)

[yourScrollView setContentSize:CGSizeMake(width,height)];

Please make sure your height and width according to your calculation.


text:
Q: waiting for task completion inside foreach loop I want to wait till the execution of one loop is completed in below code.Dont intended to process next item in list until one is done. How to ensure that execution inside foreach loop is completed once at a time or one loop at a time in the below scenario
Please note, this is a sample code only to demonstrate the issue, I know that if I remove the Task.Run from for each loop, it may work, but I need to have that task.Run in the foreach loop for some reason in my code.
List<int> Items = new List<int>();
Items.Add(1);
Items.Add(2);
Items.Add(3);

foreach(var itm in Items)
{
 Task.Run(() =>
       {
       MyFunction(itm);
       });

//  I want to wait here till one execution is complete, e.g till execution of Item with Value 1 is completed,
//I dont' intend to execute next item value of 2 until processing with value 1 is completed.

}

private void MyFunction(int value)
{
 Task.Factory.StartNew(() =>
    {
  MyFunction2(value);

    });

}

private void MyFunction2 (int number)
{
// do some ops
// update UI

}

A: Use async await. await allows you to wait for a Task to finish without blocking the thread (thus your application won't freeze)
foreach(var itm in Items)
{
    await MyFunction(itm);
}

// you must return Task to await it. void won't work
private Task MyFunction(int value)
{
    // Task.Run is preferred over Task.Factory.StartNew,
    // although it won't make any difference
    return Task.Run(() => MyFunction2(value));
}

Also don't forget to make the method containing the foreach loop async Task. You can await Tasks only in async methods. Return type should be Task, so you can later await it and possibly catch exceptions. Avoid async void, unless the method is an event handler.
public async Task Foo()
{
    foreach(var itm in Items)
    {
        await MyFunction(itm);
    }
}

A: Task.Run returns a Task object that represents that work. You need to call Wait on that.
 var myTask = Task.Run(() =>
   {
   MyFunction(itm);
   });
  myTask.Wait();


text:
Q: Select only rows that have a value in a data range - pandas dataframe what i have:
         date  percentage
0  2022-04-08        20.0
1  2022-04-09         0.0
2  2022-04-10         0.0
3  2022-04-11         0.0
4  2022-04-12        10.0
5  2022-04-13         0.0
6  2022-04-14         0.0
         date  percentage
0  2022-04-08         0.0
1  2022-04-09         0.0
2  2022-04-10         0.0
3  2022-04-11         0.0
4  2022-04-12         0.0
5  2022-04-13         0.0
6  2022-04-14         0.0
         date  percentage
0  2022-04-08       100.0
1  2022-04-09         0.0
2  2022-04-10         0.0
3  2022-04-11         0.0
4  2022-04-12         0.0
5  2022-04-13         0.0
6  2022-04-14         0.0
         date  percentage
0  2022-04-08         0.0
1  2022-04-09         0.0
2  2022-04-10         0.0
3  2022-04-11         0.0
4  2022-04-12        18.0
5  2022-04-13         0.0
6  2022-04-14         0.0
         date  percentage
0  2022-04-08        70.0
1  2022-04-09         0.0
2  2022-04-10         0.0
3  2022-04-11         0.0
4  2022-04-12        77.0
5  2022-04-13         0.0
6  2022-04-14         0.0

what I expect:
         date  percentage
0  2022-04-08        20.0
1  2022-04-12        10.0
         date  percentage
0  2022-04-08       100.0
         date  percentage
0  2022-04-12        18.0
         date  percentage
0  2022-04-08        70.0
1  2022-04-12        77.0

I want to select only rows that have values in those days. remove rows that have a value of 0
I use the for loop to go through all the elements, after which I append them in a list.

A: Try this:
df[df['percentage'] > 0]

A: Seems need filter rows in list comprehension:
L = [df[df['percentage'].ne(0)] for df in dfs]

A: To get values that are nonzero, you can simply do df = df[df["percentage"] != 0]. If your date column is a datetime data type, you can filter by days with df = df[df["date"].dt.day.isin([8, 12])]. If not and you do not want to convert it, you will need to use string slicing and it will be a bit more cumbersome.
split_date = df["date"].str.split("-", expand=True)
df = df[split_date[2].using(["08", "12"])

Where the 2 in the last command is just the last column what is returned by the splitting function.


text:
Q: How many elementary equivalent models are unifiable by ultrapower? Definition. A class $\mathcal{C}$ of pairwise elementary equivalent $\mathcal{L}$-structures is unifiable by ultrapower if there is an index set $I$ and an ultrafilter $F$ on it such that $\forall M,N\in \mathcal{C}~~~\prod_{F}M\cong \prod_{F}N$.
A theorem by Shelah and Keisler says that each set of elementary equivalent structures with size $2$ is unifiable by ultrapower.
Question. For which cardinal $\kappa$ the following assertion is true?
Each set $\mathcal{C}$ of size $\kappa$ of pairwise elementary equivalent $\mathcal{L}$-structures is unifiable by ultrapower.
What about when $\mathcal{C}$ is a proper class of pairwise elementary equivalent $\mathcal{L}$-structures?
The question is closely related to the problem of iterated ultrapowers.

A: A class $C$ of elementarily equivalent structures is unifiable by ultrapower if and only if the structures in $C$ have bounded cardinality (in other words, if they have a set of representatives up to isomorphism).
The left-to-right implication was given in Noah's comment above: if we fix $M\in C$, then every $N\in C$ satisfies
$$|N|\le\Bigl|\prod_FN\Bigr|=\Bigl|\prod_FM\Bigr|=:\kappa.$$
As for the converse implication, Shelah proved in Every two elementarily equivalent models have isomorphic ultrapowers something considerably stronger than just the Shelah–Keisler theorem:

Theorem (Shelah). Let $\lambda$ be an infinite cardinal, and $\mu=\min\{\mu:\lambda^\mu>\lambda\}$. There exists an ultrafilter $F$ on $\lambda$ with the following property.
Whenever $\{M_\alpha:\alpha<\lambda\}$ and $\{N_\alpha:\alpha<\lambda\}$ are sequences of models of cardinality $\le\kappa<\mu$ in the same language such that the ultraproducts $\prod_{\alpha<\lambda}M_\alpha/F$ and $\prod_{\alpha<\lambda}N_\alpha/F$ are elementarily equivalent, then they are isomorphic.
In particular, if $M,N$ are elementarily equivalent models of cardinality $<\mu$, then the ultrapowers $M^\lambda/F$ and $N^\lambda/F$ are isomorphic.

Note that for a given $\kappa$, we can take e.g. $\lambda=2^\kappa$ to make $\mu>\kappa$.


text:
Q: How to find out if a UITableViewCell has scrolled away and is invisible I have a UITableViewCell that observes (via KVO) some properties. This only makes sense if the cell is visible. I want to remove this observer when the cell scrolls away, and before prepareForReuse is called.
How can I do this?

A: Your table view delegate can implement
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

and in there you can call a method on the cell to perform the cleanup you want.


text:
Q: How can I read the selected item? I have two select tags in my view.
<%= select("cod_resource", "description_resource", Resource.all.collect {|p| [ p.description_resource, p.cod_resource] }) %>

<%= select("cod_damage", "description_damage", Damage.find_all_by_cod_resource_id(0).collect {|p| [ p.description_damage, p.cod_damage] }) %>

I want to update the value in the second item tag when the user selects the value in the first item tag.
I edit my code in this mode:
  <select id="resource" data-theme="c" onchange="changeValue(this)">
    <%= Resource.find(:all).each do |r| %>
        <option value="<%= r.cod_resource %>">
          <%= r.description_resource %>
        </option>
    <% end %>
  </select>

  <select id="damage" data-theme="c">
    <%= Damage.find_all_by_cod_resource_id(1).each do |r| %>
        <option value="<%= r.cod_damage %>">
          <%= r.description_damage %>
        </option>
    <% end %>
  </select>

and I add this script in application.html.erb:
function changeValue(obj){
   $("#damage").append("<option>Hello</option>");
}

it work, but if i edit in this mode
  function changeValue(obj){
        <%= Damage.find_all_by_cod_resource_id(1).each do |r| %>
      $("#damage").append(" <option value='<%= r.cod_damage %>''><%= r.description_damage %></option>");
      <% end %>
  }

it not work.

A: You have to fire ajax request to update second select box.
Following article help you to do this http://paramitech.com/dynamically-udating-select-list-using-jquery-and-ajax/

A: You have multiple choices. One that you can try is using .appen(). Here a example
http://jsbin.com/eguzeb/1/edit
Note: You have to use Ajax to do archive what you need.

A: Inspect select tag  in your browser, Rails will give specified id or class in the form tag
<%= select("cod_resource", "description_resource", Resource.all.collect {|p| [ p.description_resource, p.cod_resource] }) %>

<%= select("cod_damage", "description_damage", Damage.find_all_by_cod_resource_id(0).collect {|p| [ p.description_damage, p.cod_damage] }) %>

Find id or class name for your select tag and try this code
  $('first_select_tag_id/class').change(function(){
      alert($('this').val());
    }

    $('second_select_tag_id/class').change(function(){
      alert($('this').val());
    }

A: Thanks I resolved my problem with ajax request:
This is my ajax request:
<script>

      function changeValue(obj){
          resource_id = $("#resource").val();
          $.ajax({
              type: "GET",
              url: "/reports/",
              data: "resource_id="+resource_id,
              success: function(html){
                  var part= $("<div/>").append(html).find('#damage_list').html();
                  $("#damage_list").html(part);
              }
          });
       }

  </script>

and this is the code of html part
      <select id="resource" data-theme="c" onchange="changeValue(this)">
        <%= Resource.find(:all).each do |r| %>
            <option value="<%= r.cod_resource %>">
              <%= r.description_resource %>
            </option>
        <% end %>
      </select>

      <!-- Home -->
      <div id="damage_list">
        <select id="damage" data-theme="c">
          <%= Damage.find_all_by_cod_resource_id(params[:resource_id]).each do |r| %>
              <option value="<%= r.cod_damage %>">
                <%= r.description_damage %>
              </option>
          <% end %>
        </select>
      </div>

It is work!!!
There is  small problem, it is not reload the  JQuery Mobile style in the select box.
I searched this problem but all solutions that i found don't work.


text:
Q: Getting clang++: error: while compiling code contaning filesystem library I am trying to use filesystem in native code in android project. But getting this error:
FAILED:
C:/Users/Johnsnow/AndroidStudioProjects/abc/Application/app/build/intermediates/cmake/debug/obj/armeabi-v7a/libnative-lib1.so
cmd.exe /C "cd . && C:\Users\Johnsnow\AppData\Local\Android\Sdk\ndk\21.1.6352462\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++.exe --target=armv7-none-linux-androideabi16 --gcc-toolchain=C:/Users/Johnsnow/AppData/Local/Android/Sdk/ndk/21.1.6352462/toolchains/llvm/prebuilt/windows-x86_64 --sysroot=C:/Users/Johnsnow/AppData/Local/Android/Sdk/ndk/21.1.6352462/toolchains/llvm/prebuilt/windows-x86_64/sysroot -fPIC -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -march=armv7-a -mthumb -Wformat -Werror=format-security   -stdlib=libc++ -O0 -fno-limit-debug-info  -Wl,--exclude-libs,libgcc.a -Wl,--exclude-libs,libgcc_real.a -Wl,--exclude-libs,libatomic.a -Wl,--build-id -Wl,--fatal-warnings -Wl,--exclude-libs,libunwind.a -Wl,--no-undefined -Qunused-arguments -shared -Wl,-soname,libnative-lib1.so -o C:\Users\Johnsnow\AndroidStudioProjects\abc\Application\app\build\intermediates\cmake\debug\obj\armeabi-v7a\libnative-lib1.so @CMakeFiles/native-lib1.rsp  && cd ."
C:/Users/Johnsnow/AppData/Local/Android/Sdk/ndk/21.1.6352462/toolchains/llvm/prebuilt/windows-x86_64/sysroot/usr/include/c++/v1/filesystem:1615: error: undefined reference to 'std::__ndk1::__fs::filesystem::__status(std::__ndk1::__fs::filesystem::path const&, std::__ndk1::error_code*)'
C:/Users/Johnsnow/AppData/Local/Android/Sdk/ndk/21.1.6352462/toolchains/llvm/prebuilt/windows-x86_64/sysroot/usr/include/c++/v1/filesystem:1637: error: undefined reference to 'std::__ndk1::__fs::filesystem::__file_size(std::__ndk1::__fs::filesystem::path const&, std::__ndk1::error_code*)'
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.

Way I am including it is:
#include <filesystem>

In the c++ code I am using as:
std::filesystem::path

cmake contents in build.gradle:
externalNativeBuild {
            cmake {
                arguments '-DANDROID_PLATFORM=android-16',
                        '-DANDROID_TOOLCHAIN=clang', '-DANDROID_STL=c++_shared'
            }
        }

Options tried:
I have tried adding libc++ in cmakeLists.txt
set(CMAKE_CXX_STANDARD 17)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++")

Also tried:
target_link_libraries(native-lib1 -lstdc++)

Also tried:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -stdlib=libc++")

where native-lib1 is library I am trying to add. But it is not working.
My NDK version is : 21.1.6352462
Please suggest some workaround.

A: What I did to get std::filesystem to work was changing the solution platform to x64 instead of the default Win32.
I did this on Visual Studio,  in a console application.
However, I hope this could be helpful.

A: Support for std::filesystem looks like it will land in Android NDK r22 at the earliest:

The implementation for this is now checked in to master and will be in r22. I've forked the remaining testing cleanup into #1265 so I can close this to make it obvious that the part you folks care about is complete without having to read the whole thing :)

The linked thread has some workarounds, like using boost::filesystem or just building the std::filesystem library (libc++fs) yourself.


text:
Q: What particular functions that can perform Ncurses scanw() and printw() in the Form library? I have a simple Ncurses program that will ask for an ID number and the system will return for this ID number using scanw() and printw() functions respectively. Now, if I'm going to use the Form library #include <form.h> what functions should I use?
#include <ncurses.h>

int
main()
{
        initscr();
        char idnum[9];

        nodelay(stdscr, FALSE);
        printw("Enter ID number: ");
        refresh();
        scanw("%s", idnum);
        printw("The ID number entered is: %s\n", idnum);
        refresh();
        return 0;
}


text:
Q: how to configure 2 network interfaces with different gateways Here is what is in my
/etc/network/interfaces file:
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
address 172.168.10.252
netmask 255.255.255.0
network 172.168.10.0
broadcast 172.168.10.255
gateway 172.168.10.1

iface eth1 inet static
address 172.168.10.251
netmask 255.255.255.0
network 172.168.10.0
broadcast 172.168.10.255
gateway 172.168.10.10

I would like to use eth0 as for local network and eth1 for internet.
Thanks

A: To configure two interfaces say eth0 and eth1 to use two networks 192.168.0.0/24 and 10.10.0.0/24 a tool iproute2
can  be used to achieve this.
Steps:

*

*Edit your /etc/network/interfaces:
auto lo
iface lo inet loopback

# The primary network interface

allow-hotplug eth0
iface eth0 inet static
    address 192.168.0.10
    netmask 255.255.255.0
    gateway 192.168.0.1

# The secondary network interface
allow-hotplug eth1
    iface eth1 inet static
    address 10.10.0.10
    netmask 255.255.255.0

*Add second routing table by editing `/etc/iproute2/rt_tables:
#
# reserved values
#
255     local
254     main
253     default
0       unspec
#
# local
#
#1      inr.ruhep
1 rt2

*Populate new routing table:
ip route add 10.10.0.0/24 dev eth1 src 10.10.0.10 table rt2
ip route add default via 10.10.0.1 dev eth1 table rt2

# The first command says that the network, 10.10.0.0/24, can be reached through the eth1 interface.
# The second command sets the default gateway.

*Add routing rules:
ip rule add from 10.10.0.10/32 table rt2
ip rule add to 10.10.0.10/32 table rt2

# These rules say that both traffic from the IP address, 10.10.0.10, as well as traffic directed to
# or through this IP address, should use the rt2 routing table

*Making the Configuration permanent by adding it to /etc/network/interfaces:
iface eth1 inet static
    address 10.10.0.10
    netmask 255.255.255.0
    post-up ip route add 10.10.0.0/24 dev eth1 src 10.10.0.10 table rt2
    post-up ip route add default via 10.10.0.1 dev eth1 table rt2
    post-up ip rule add from 10.10.0.10/32 table rt2
    post-up ip rule add to 10.10.0.10/32 table rt2

Source:
https://www.thomas-krenn.com/en/wiki/Two_Default_Gateways_on_One_System


text:
Q: Datatables Error when using destroy(): Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted How I use DataTables:

*

*Fetch data from the db.

*Convert the data to row objects using Underscore.js template.

*Populate my table's <tbody> with the rows.

*Then I init the Datatable on the table that I have.

The problem is when I try to add more rows to the table, I am not using the API so I just add rows directly to the <tbody> and I want DataTables to ReInit it self using the new <tbody>.
I am trying to Destroy the table, but what happens is that I get this error:

Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The
  node before which the new node is to be inserted is not a child of
  this node.(…)

I created a Demo to reproduce what I am trying to do using Datatables but it doesn't reproduce the error...
Here is a question I found about the same error:
https://datatables.net/forums/discussion/28081/how-to-update-table-when-dom-changes-destroy-init-crash

A: You just need add   "retrieve": true, option into your datatable configuration.
function init(){
    ruleChangeLogTable = $('#changeLogTable').DataTable({
      //I use destroy because I want to recreate the table with new data.
            "bLengthChange": false,
            "bPaginate": false,
             "retrieve": true,              // this option is added
            "bInfo": false,
            "autoWidth": false,
            "order": [[0, "desc"]],
            "dom": '<"#searchInput"f>',
            "oLanguage": { "sSearch": "" },
            "columns": [
            null,
                null,
                null,
                null,
                 null
            ]
        });
    }

https://datatables.net/reference/option/retrieve  for more details refer this
Hope this helps you

A: no need to destroy and init, just redraw table using api
function Repopulate() {
    //...
    //...
    //...
    //init() //remove this line and add the one below
    $("#changeLogTable").DataTables().draw();
}


text:
Q: Removing Junk Characters from Ruby String I am trying to clean up a string that I get from a website using mechanize
here is an except from the string with the junk characters
"Mountain
ΓÇÄ1hr 39minΓÇÄΓÇÄ - Rated PGΓÇÄΓÇÄ - Action/Adventure/Science fictionΓÇÄΓÇÄ - EnglishΓÇÄ - <a href="

Does any one know where they characters come from and how I can replace them with spaces? How does ruby handle the encoding of characters?

A: Those characters look like they might be appearing as the result of a UTF-8 encoding problem. I recommend reading Joel's excellent article The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) which will explain UTF-8 encoding and how to handle it in your code.


text:
Q: Hanging VBScript on query I inherited a piece of code from a recently-retired colleague that gets the total physical memory on a box and, when I perform the following on Windows XP and Server 2003, it works fine:
memSize = 0
set colItems = wmi.execQuery("select * from Win32_LogicalMemoryConfiguration")
for objItem in colItems
    memSize = memSize + objItem.TotalPhysicalMemory
next

On Windows Server 2008 however, it appears to hang in the for statement (based on copious debugging statements after every line which are not shown in the example).
Any ideas why?

A: The Win32_LogicalMemoryConfiguration class has been deprecated. Try the Win32_OperatingSystem class instead. It should give the proper results on Server 2008.
I believe the property you're interested in is TotalVisibleMemorySize.


text:
Q: Formula conversion Octave to NumPy I am calculating the following lines in Octave:
DOA = [2.44511697; 171.03810943; -54.15891743; -106.57844237];
alfa = tand(DOA);

   0.042701
  -0.157703
  -1.384441
   3.359049

in radians I get the following results in Octave:
alfa = tan(DOA);

  -0.8363
   5.5366
  -0.9350
   0.2402

The second gives me the same results in NumPy:
alfa = np.tan(DOA)
[[-0.83628155]
 [ 5.53658766]
 [-0.93504359]
 [ 0.24017226]]

when converting to degrees with np.rad2deg I get the following results instead:
alfa = np.tan(DOA)
alfa = np.rad2deg(alfa)

[[-47.91540317]
 [317.22310577]
 [-53.57405123]
 [ 13.76085667]]

I couldn't find a suitable answer to this issue. I would appreciate it, if someone could help me with this issue. Thanks a lot.


text:
Q: Alinear imagen al texto con css estoy intentando crear una alerta con css y html como se muestra en la imagen:notificacion
ya tengo la imagen encima del rectangulo y que el rectangulo comience justo a mitad de la imagen, sin embargo no logro que mi alerta quede igual que la imagen que subi porque el icono no queda alineado al texto, ¿Alguien podria apoyarme?
Mi código en html es el siguiente:

  Aqui va el texto de mi alerta

Mi código en css es:
.rectangulo {
 background-color: #fff6d9;
 border-radius: 4px;
 padding: 15px;
 margin-bottom: 20px;
 font-size: 14px;
 font-family: Arial;
 color: #4c4c4c;
 margin-left: 22px;
}

.notificiacion > img {
 position: absolute;
 width: 33px;
 float: left;
 vertical-align: middle;
}

Con este código logro el siguiente resultado:
resultado_codigo

A: Como ya te mencionaron, la propiedad vertical-align no funciona con elemento float, solo funciona con elementos inline. Te comparto un ejemplo de como quedaría tu código para lograr lo que necesitas.

.notificiacion{
  width: 300px;
  height: 50px;
  background-color: #fff6d9;
  border-radius: 10px;
}

.notificiacion{
  line-height: 3em;
}

.notificiacion img{
  float: left;
  margin-top: 3%;
  margin-left: 3%;
  margin-right: 4%;
}

.notificiacion p{

}

Aqui va el texto de mi alerta

A: Eso pasa por que la propiedad vertical-align no funciona con elementos que tienen la propiedad float, para que esto te funcione debes cambiar float: left por display: inline-block para ambos elementos ... no entiendo por que usas position: absolute junto con float: left
Tu código debería quedar así:
.rectangulo {
 background-color: #fff6d9;
 border-radius: 4px;
 padding: 15px;
 margin-bottom: 20px;
 font-size: 14px;
 font-family: Arial;
 color: #4c4c4c;
 margin-left: 22px;
 display: inline-block;
 vertical-align: middle;
}

.notificiacion > img {
 width: 33px;
 display: inline-block;
 vertical-align: middle;
}


text:
Q: MongoDb: Benefit of using ObjectID vs a string containing an Id? Is there any benefit to storing an id to a related document as an ObjectId versus storing it as a string literal?
Using ObjectID:
{
   "_id": ObjectId("522bb79455449d881b004d27"),
   "username": "admin",
   "folder": ObjectId("522bb79455449d881b004d23")
}

versus a string:
{
   "_id": ObjectId("522bb79455449d881b004d27"),
   "username": "admin",
   "folder": "522bb79455449d881b004d23"
}

For my API where I'm sending data back to a client... using the string means I don't have to "cleanup" the data... and as we have to do a second query to get the folder document anyway... is it worth using ObjectId? (and if so why?)
Thanks

A: The biggest reason is that ObjectIDs are 12 bytes, whereas an equivalent string is 24 bytes. Over a large enough collection, those 12 bytes saved per ID really add up! Those IDs also mean fewer bytes transferred over the wire when reading or writing the document, as well.
Additionally, some ODMs expect ObjectIDs for external document references, and may be confused by string versions of the ID. I am not familiar enough with PHP ODMs to say if this might affect you specifically, though.
Regarding the API stuff, though, you should probably be doing normalization of the data before sending it to the client anyhow, because since Mongo doesn't enforce a schema, you can have literally any sort of data in a given field, so you might have some documents that have string IDs, and others that have BSON IDs, and your API would happily send them both through to the client, but one or the other might cause breakage. In this particular case, you should use BSON ObjectIDs in your documents, and then should cast them to strings in your API output.

A: In addition, ObjectId() has the following attribute and methods that you can use.

*

*str -  Returns the hexadecimal string representation of the object.
as a Date.

*ObjectId.toString()   # Returns the JavaScript representation.

*ObjectId.getTimestamp()   # Returns the timestamp portion of the object

*ObjectId.valueOf() # Returns the representation of the object as a hexadecimal string

A: Briefly, for example, if you shorten the filed named last_name to lname , you could save 9 bytes per document. This really makes a difference if you have millions of documents in your collection.


text:
Q: Image resize issue in Mozilla Firefox for windows I am having some weird issues. I have a large image which is being shrunk to size 30px in the img link so:
img src="/company/images/logos/1.png" height="30px"

On all browsers and computers it looks fine except for firefox on a windows.  I found out that when i rid the height constraint it looks fine but when i add the "30px" it looks messed up.
Any ideas on what i might need to do?

A: I'm guessing you're talking about issue where the default Firefox image resizing algorithm makes the image look "jagged".
In general, it's better to not let the browser resize the image.
You should instead make a version of the image that is already the correct size.
I'm not aware of a way to make the image look good when downscaling in Firefox.
See here for a comparison. (I used Firefox 3.6.15 / Windows 7)
If anybody has a way to make the first image downscale smoothly in Firefox, I'd like to know.


text:
Q: Dse is not starting stating unable to write to commit log directory I am getting below error while starting the dse:
ERROR [main] 2020-02-26 13:08:33,269  DseModule.java:97 - {}. Exiting...
com.google.inject.CreationException: Unable to create injector, see the following errors:
1) An exception was caught and reported. Message: Unable to check disk space available to /u01/dse_ops/logs. Perhaps the Cassandra user does not have the necessary permissions
  at com.datastax.bdp.DseModule.configure(Unknown Source)