text:
Q: How can I get `find` to ignore .svn directories? I often use the find command to search through source code, delete files, whatever. Annoyingly, because Subversion stores duplicates of each file in its .svn/text-base/ directories my simple searches end up getting lots of duplicate results. For example, I want to recursively search for uint in multiple messages.h and messages.cpp files:
# find -name 'messages.*' -exec grep -Iw uint {} +
./messages.cpp:            Log::verbose << "Discarding out of date message: id " << uint(olderMessage.id)
./messages.cpp:    Log::verbose << "Added to send queue: " << *message << ": id " << uint(preparedMessage->id)
./messages.cpp:                Log::error << "Received message with invalid SHA-1 hash: id " << uint(incomingMessage.id)
./messages.cpp:            Log::verbose << "Received " << *message << ": id " << uint(incomingMessage.id)
./messages.cpp:            Log::verbose << "Sent message: id " << uint(preparedMessage->id)
./messages.cpp:        Log::verbose << "Discarding unsent message: id " << uint(preparedMessage->id)
./messages.cpp:        for (uint i = 0; i < 10 && !_stopThreads; ++i) {
./.svn/text-base/messages.cpp.svn-base:            Log::verbose << "Discarding out of date message: id " << uint(olderMessage.id)
./.svn/text-base/messages.cpp.svn-base:    Log::verbose << "Added to send queue: " << *message << ": id " << uint(preparedMessage->id)
./.svn/text-base/messages.cpp.svn-base:                Log::error << "Received message with invalid SHA-1 hash: id " << uint(incomingMessage.id)
./.svn/text-base/messages.cpp.svn-base:            Log::verbose << "Received " << *message << ": id " << uint(incomingMessage.id)
./.svn/text-base/messages.cpp.svn-base:            Log::verbose << "Sent message: id " << uint(preparedMessage->id)
./.svn/text-base/messages.cpp.svn-base:        Log::verbose << "Discarding unsent message: id " << uint(preparedMessage->id)
./.svn/text-base/messages.cpp.svn-base:        for (uint i = 0; i < 10 && !_stopThreads; ++i) {
./virus/messages.cpp:void VsMessageProcessor::_progress(const string &fileName, uint scanCount)
./virus/messages.cpp:ProgressMessage::ProgressMessage(const string &fileName, uint scanCount)
./virus/messages.h:    void _progress(const std::string &fileName, uint scanCount);
./virus/messages.h:    ProgressMessage(const std::string &fileName, uint scanCount);
./virus/messages.h:    uint        _scanCount;
./virus/.svn/text-base/messages.cpp.svn-base:void VsMessageProcessor::_progress(const string &fileName, uint scanCount)
./virus/.svn/text-base/messages.cpp.svn-base:ProgressMessage::ProgressMessage(const string &fileName, uint scanCount)
./virus/.svn/text-base/messages.h.svn-base:    void _progress(const std::string &fileName, uint scanCount);
./virus/.svn/text-base/messages.h.svn-base:    ProgressMessage(const std::string &fileName, uint scanCount);
./virus/.svn/text-base/messages.h.svn-base:    uint        _scanCount;

How can I tell find to ignore the .svn directories?

Update: If you upgrade  your SVN client to version 1.7 this is no longer an issue.

A key feature of the changes introduced in Subversion 1.7 is the centralization of working copy metadata storage into a single location. Instead of a .svn directory in every directory in the working copy, Subversion 1.7 working copies have just one .svn directory—in the root of the working copy. This directory includes (among other things) an SQLite-backed database which contains all of the metadata Subversion needs for that working copy.

A: Create a script called ~/bin/svnfind:
#!/bin/bash
#
# Attempts to behave identically to a plain `find' command while ignoring .svn/
# directories.

OPTIONS=()
PATHS=()
EXPR=()

while [[ $1 =~ ^-[HLP]+ ]]; do
    OPTIONS+=("$1")
    shift
done

while [[ $# -gt 0 ]] && ! [[ $1 =~ '^[-(),!]' ]]; do
    PATHS+=("$1")
    shift
done

# If user's expression contains no action then we'll add the normally-implied
# `-print'.
ACTION=-print

while [[ $# -gt 0 ]]; do
    case "$1" in
       -delete|-exec|-execdir|-fls|-fprint|-fprint0|-fprintf|-ok|-print|-okdir|-print0|-printf|-prune|-quit|-ls)
            ACTION=;;
    esac

    EXPR+=("$1")
    shift
done

if [[ ${#EXPR} -eq 0 ]]; then
    EXPR=(-true)
fi

exec -a "$(basename "$0")" find "${OPTIONS[@]}" "${PATHS[@]}" -name .svn -type d -prune -o '(' "${EXPR[@]}" ')' $ACTION

This script behaves identically to a plain find command but it prunes out .svn directories. Otherwise the behavior is identical.
Example:
# svnfind -name 'messages.*' -exec grep -Iw uint {} +
./messages.cpp:            Log::verbose << "Discarding out of date message: id " << uint(olderMessage.id)
./messages.cpp:    Log::verbose << "Added to send queue: " << *message << ": id " << uint(preparedMessage->id)
./messages.cpp:                Log::error << "Received message with invalid SHA-1 hash: id " << uint(incomingMessage.id)
./messages.cpp:            Log::verbose << "Received " << *message << ": id " << uint(incomingMessage.id)
./messages.cpp:            Log::verbose << "Sent message: id " << uint(preparedMessage->id)
./messages.cpp:        Log::verbose << "Discarding unsent message: id " << uint(preparedMessage->id)
./messages.cpp:        for (uint i = 0; i < 10 && !_stopThreads; ++i) {
./virus/messages.cpp:void VsMessageProcessor::_progress(const string &fileName, uint scanCount)
./virus/messages.cpp:ProgressMessage::ProgressMessage(const string &fileName, uint scanCount)
./virus/messages.h:    void _progress(const std::string &fileName, uint scanCount);
./virus/messages.h:    ProgressMessage(const std::string &fileName, uint scanCount);
./virus/messages.h:    uint        _scanCount;

A: find . | grep -v \.svn

A: For searching, can I suggest you look at ack ? It's a source-code aware find, and as such will automatically ignore many file types, including source code repository info such as the above.

A: Why dont you pipe your command with grep which is easily understandable:
your find command| grep -v '\.svn'

A: Just thought I'd add a simple alternative to Kaleb's and others' posts (which detailed the use of the find -prune option, ack, repofind commands etc.) which is particularly applicable to the usage you have described in the question (and any other similar usages):

*

*For performance, you should always try to use find ... -exec grep ... + (thanks Kenji for pointing this out) or find ... | xargs egrep ... (portable) or find ... -print0 | xargs -0 egrep ... (GNU; works on filenames containing spaces) instead of find ... -exec grep ... \;.
The find ... -exec ... + and find | xargs form does not fork egrep for each file, but rather for a bunch of files at a time, resulting in much faster execution.

*When using the find | xargs form you can also use grep to easily and quickly prune .svn (or any directories or regular expression), i.e. find ... -print0 | grep -v '/\.svn' | xargs -0 egrep ... (useful when you need something quick and can't be bothered to remember how to set up find's -prune logic.)
The find | grep | xargs approach is similar to GNU find's -regex option (see ghostdog74's post), but is more portable (will also work on platforms where GNU find is not available.)

A: In a source code repository, I generally want to do things only to the text files.
The first line is all files, excluding CVS, SVN, and GIT repository files.
The second line excludes all binary files.
find . -not \( -name .svn -prune -o -name .git -prune -o -name CVS -prune \) -type f -print0 | \
xargs -0 file -n | grep -v binary | cut -d ":" -f1

A: To ignore .svn, .git and other hidden directories (starting with a dot), try:
find . -type f -not -path '*/\.*'

However, if the purpose of using find is searching within the files, you may try to use these commands:

*

*git grep - specially designed command for searching patterns within the Git repository.

*ripgrep - which by default ignores hidden files and files specified in .gitignore.

Related: How do I find all files containing specific text on Linux?

A: why not just
find . -not -iwholename '*.svn*'

The -not predicate negates everything that has .svn anywhere in the path.
So in your case it would be
find -not -iwholename '*.svn*' -name 'messages.*' -exec grep -Iw uint {} + \;

A: I use find with the -not -path options.  I have not had good luck with prune.
find .  -name "*.groovy" -not -path "./target/*" -print

will find the groovy files not in the target directory path.

A: To resolve this problem, you can simply use this find condition:
find \( -name 'messages.*' ! -path "*/.svn/*" \) -exec grep -Iw uint {} +

You can add more restriction like this:
find \( -name 'messages.*' ! -path "*/.svn/*" ! -path "*/CVS/*" \) -exec grep -Iw uint {} +

You can find more information about this in man page section "Operators":
http://unixhelp.ed.ac.uk/CGI/man-cgi?find

A: Note that if you do
find . -type f -name 'messages.*'
then -print is implied when the whole expression (-type f -name 'messages.*') is true, because there is no 'action' (like -exec).
While, to stop descending into certain directories, you should use anything that matches those directories and follow it by -prune (which is intended to stop descending into directories); like so:
find . -type d -name '.svn' -prune
This evaluates to True for the .svn directories, and we can use boolean short-circuit by following this by -o (OR), after which what follows after the -o is only checked when the first part is False, hence is not a .svn directory. In other words, the following:
find . -type d -name '.svn' -prune -o -name 'message.*' -exec grep -Iw uint {}
will only evalute what is right of the -o, namely -name 'message.*' -exec grep -Iw uint {}, for files NOT inside .svn directories.
Note that because .svn is likely always a directory (and not for example a file), and in this case certainly isn't matching the name 'message.*', you might as well leave out the -type d and do:
find . -name '.svn' -prune -o -name 'message.*' -exec grep -Iw uint {}
Finally, note that if you omit any action (-exec is an action), say like so:
find . -name '.svn' -prune -o -name 'message.*'
then the -print action is implied but will apply to the WHOLE expression, including the -name '.svn' -prune -o part and thus print all .svn directories as well as the 'message.*' files, which is probably not what you want. Therefore you always should use an 'action' in the right-hand side of the boolean expression when using -prune in this way. And when that action is printing you have to explicitly add it, like so:
find . -name '.svn' -prune -o -name 'message.*' -print

A: Here is what I would do in your case:
find . -path .svn -prune -o -name messages.* -exec grep -Iw uint {} +

Emacs' rgrep built-in command ignores .svn directory, and many more files you're probably not interested in when performing a find | grep. Here is what it uses by default:
find . \( -path \*/SCCS -o -path \*/RCS -o -path \*/CVS -o -path \*/MCVS \
          -o -path \*/.svn -o -path \*/.git -o -path \*/.hg -o -path \*/.bzr \
          -o -path \*/_MTN -o -path \*/_darcs -o -path \*/\{arch\} \) \
     -prune -o \
       \( -name .\#\* -o -name \*.o -o -name \*\~ -o -name \*.bin -o -name \*.lbin \
          -o -name \*.so -o -name \*.a -o -name \*.ln -o -name \*.blg \
          -o -name \*.bbl -o -name \*.elc -o -name \*.lof -o -name \*.glo \
          -o -name \*.idx -o -name \*.lot -o -name \*.fmt -o -name \*.tfm \
          -o -name \*.class -o -name \*.fas -o -name \*.lib -o -name \*.mem \
          -o -name \*.x86f -o -name \*.sparcf -o -name \*.fasl -o -name \*.ufsl \
          -o -name \*.fsl -o -name \*.dxl -o -name \*.pfsl -o -name \*.dfsl \
          -o -name \*.p64fsl -o -name \*.d64fsl -o -name \*.dx64fsl -o -name \*.lo \
          -o -name \*.la -o -name \*.gmo -o -name \*.mo -o -name \*.toc \
          -o -name \*.aux -o -name \*.cp -o -name \*.fn -o -name \*.ky \
          -o -name \*.pg -o -name \*.tp -o -name \*.vr -o -name \*.cps \
          -o -name \*.fns -o -name \*.kys -o -name \*.pgs -o -name \*.tps \
          -o -name \*.vrs -o -name \*.pyc -o -name \*.pyo \) \
     -prune -o \
     -type f \( -name pattern \) -print0 \
     | xargs -0 -e grep -i -nH -e regex

It ignores directories created by most version control systems, as well as generated files for many programming languages.
You could create an alias that invokes this command and replace find and grep patterns for your specific problems.

A: Try findrepo which is a simple wrapper around find/grep and much faster than ack
You would use it in this case like:
findrepo uint 'messages.*'

A: wcfind is a find wrapper script that I use to automagically remove .svn directories.

A: As follows:
find . -path '*/.svn*' -prune -o -print

Or, alternatively based on a directory and not a path prefix:
find . -name .svn -a -type d -prune -o -print

A: GNU find
find .  ! -regex ".*[/]\.svn[/]?.*"

A: I use grep for this purpose. Put this in your ~/.bashrc
export GREP_OPTIONS="--binary-files=without-match --color=auto --devices=skip --exclude-dir=CVS --exclude-dir=.libs --exclude-dir=.deps --exclude-dir=.svn"

grep automatically uses these options on invocation

A: This works for me in the Unix prompt

gfind . \( -not -wholename '*\.svn*' \) -type f -name 'messages.*'
  -exec grep -Iw uint {} +

The command above will list FILES that are not with .svn and do the grep you mentioned.

A: i usually pipe the output through grep one more time removing .svn, in my use it isn't much slower.
typical example:
find -name 'messages.*' -exec grep -Iw uint {} + | grep -Ev '.svn|.git|.anythingElseIwannaIgnore'

OR
find . -type f -print0 | xargs -0 egrep messages. | grep -Ev '.svn|.git|.anythingElseIwannaIgnore'


text:
Q: How to view aggregated liquidations for cryptocurrencies from Binance? On these sites (https://coinalyze.net/ethereum-classic/liquidations/, BTC/USDT), I am able to add following indications into grpah [Liquidations, Long Liquidations, Short Liquidations, Aggregated Liquidations COIN-margined Contracts, Aggregated Liquidations STABLECOIN-margined Contracts].

Aggregated liquidations = liquidations of coin-margined contracts +
liquidations of stablecoin-margined contracts converted to USD. For
the moment only BTC/USD and BTC/USDT contracts are included. See the
indicator options, you can select/deselect individual contracts.

=> The main question is to how to obtain data streams for liquidations in cryptocurrencies, if possible from Tradingview or exchanges like Binance.
I have tried to add Aggregated liquidations or just Liquidations in to my graphs on https://www.tradingview.com for cryptocurrencies under Futures. I was not able to find its pine-script code or its built-in indicator, so I believe that data is private and was dead end for me.
Is it possible to obtain data streams for liquidations in cryptocurrencies from exchanges like Binance or others? or add Aggregated liquidations into graphs on TradingView for cryptocurrencies?

A: The short answer is no, it's not possible because Tradingview doesn't provide that level of data. Sites like coinalyze are using the Tradingview plugin and providing their own data streams for liquidations.
To create the equivalent on the Trandingview platform itself there is something of a workaround but it is less than ideal. It won't be live data and you will have to manually update the data array yourself. You will also have to source the liquidation data yourself.
You will have to take note of the timestamp of the first data entry and parse the liquidation data into a set of comma separated values.
From there you can "import" it into a script using array.from()
start_timestamp = timestamp(2021, 7, 9, 0, 0, 0)

var float[] a_longLiqs = array.from(17, 13458.4, 87453.56, 2345.23 , 23457.983, 353, .... etc)

var int index = na
var bool started = false
float longLiqs = na

if time == start_timestamp
    started := true
    index := 0
else if time > start_timestamp
    index += 1

if started and index < array.size(a_longLiqs)
    longLiqs := array.get(a_longLiqs, index)

plot(longLiqs)

At this point you've effectively converted the array into a time series variable longLiqs which you can work with the same as any other, such as close, volume, etc. However you only get new data when you add it to the array manually.
To obtain the aggregate data itself is a bit of a process. You have to make use of the exchange's APIs.
For example :
https://www.bitmex.com/api/explorer/#/Liquidation
https://bybit-exchange.github.io/docs/inverse/#t-query_liqrecords
There are quite a number of existing projects on github in both js and python, I suggest you start there rather than reinvent the wheel. For example the cryptofeed py package might be a good place to start as it seems to support pulling the liquidation data over multiple exchanges.
https://pypi.org/project/cryptofeed/
https://github.com/bmoscon/cryptofeed/blob/master/docs/callbacks.md
Once you have the data you'll have to aggregate it yourself and parse it like I mentioned above to be able to insert it into a pine array.
Alternatively there are paid data providers that may make it a bit easier if you're ok with paying for the data. You may still need to aggregate it and parse it, but you'll only be dealing with one API rather than having to manage it from every exchange.
Here's one I've found that seems to provide aggregate liquidation data : https://www.cryptometer.io/api-doc/

A: I have started from here:

*

*https://binance-docs.github.io/apidocs/futures/en/#liquidation-order-streams

*https://github.com/Binance-docs/Binance_Futures_python/blob/master/binance_f/model/liquidationorder.py
You have to install following packages: pip install websocket-client websocket.

#!/usr/bin/env python3

import websocket

class Liq:
    def __init__(self):
        self.socket = "wss://fstream.binance.com/ws/!forceOrder@arr"
        self.ws = websocket.WebSocketApp(self.socket, on_message=self.on_message, on_close=self.on_close)
        self.symbol: str = ""
        self.order_quantity = 0
        self.event_time: int = 0
        self.average_price: float = 0.0
        self.side = ""
        self.price: float = 0.0
        self.order_last_filled_quantity = 0.0
        self.order_filled_accumulated_quantity = 0
        self.order_trade_time = 0

    def print_result(self):
        amount = int(self.order_quantity * self.average_price)
        print(f"==> symbol={self.symbol}")
        print(f"==> side={self.side} | ", end="")
        if self.side == "BUY":
            print("shorts liquadated")
        else:
            print("longs liquadated")

        print(f"==> order_quantity={self.order_quantity}")
        print(f"==> event_time={self.event_time}")
        print(f"==> order_last_filled_quantity={self.order_last_filled_quantity}")
        print(f"==> order_filled_accumulated_quantity={self.order_filled_accumulated_quantity}")
        print(f"==> order_trade_time={self.order_trade_time}")
        print(f"==> price={self.price}")
        print(f"==> average_price={self.average_price}")
        print(f"==> liq_amount={amount}")
        print("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")

    def on_message(self, ws, message):
        """Fetch liquidation Order Streams.

        __ https://binance-docs.github.io/apidocs/futures/en/#liquidation-order-streams
        """
        for item in message.split(","):
            item = item.replace("}", "").replace("{", "").replace('"', "").replace("o:s:", "s:")
            if "forceOrder" not in item:
                _item = item.split(":")
                if _item[0] == "E":
                    self.event_time = int(_item[1])
                elif _item[0] == "s":
                    self.symbol = _item[1]
                elif _item[0] == "S":
                    self.side = _item[1]
                elif _item[0] == "q":
                    self.order_quantity = float(_item[1])
                elif _item[0] == "p":
                    self.price = _item[1]
                elif _item[0] == "ap":
                    self.average_price = float(_item[1])
                elif _item[0] == "l":
                    self.order_last_filled_quantity = _item[1]
                elif _item[0] == "z":
                    self.order_filled_accumulated_quantity = _item[1]
                elif _item[0] == "T":
                    self.order_trade_time = _item[1]

        self.print_result()

    def on_close(self):
        print("closed")

liq = Liq()
liq.ws.run_forever()

Example output, all liquadated pairs will be printed:
==> symbol=KEEPUSDT
==> side=SELL | longs liquadated
==> order_quantity=4705.0
==> event_time=1634474643639
==> order_last_filled_quantity=278
==> order_filled_accumulated_quantity=4705
==> order_trade_time=1634474643630
==> price=0.9877
==> average_price=1.0
==> liq_amount=4705
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
==> symbol=FTMUSDT
==> side=BUY | shorts liquadated
==> order_quantity=1458.0
==> event_time=1634474896201
==> order_last_filled_quantity=1240
==> order_filled_accumulated_quantity=1458
==> order_trade_time=1634474896197
==> price=2.257972
==> average_price=2.236581
==> liq_amount=3260

Afterwards you can store this results in a database like mongadb.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Programa que da de alta a un usuario en java, me gustaría saber sus recomendaciones para poder mejorarlo *fecha:16/04/17

*"programa encargado de solicitar
* alta de usuario con parametros
*especificos el numero celular y password,
posteriormente le solicita que
confirme la contraseña*/

public class checking_password
{

    public static void main(String[] args)
    {
        revision_password autentificacion=new revision_password();
    }
}

class revision_password {

    private String number_Phone="";
    private final static String MATCH_NUMBER_PHONE="[0-9]{10}";
    private String password="";
    private final static String MATCH_PASSWORD="[0-9a-zA-Z]{10}";
    private Scanner entrada=new Scanner(System.in);

    public revision_password(){

        Welcome_Mensage();
        rev_password();
    }
    /*metodo con mensaje de bienvenida
    * e invitacion a ingresar datos*/
    private void Welcome_Mensage(){

        System.out.println("Hola!, gracias por elegir \"FUTURE TECH\" \n");
        System.out.println("para poder disfrutar de nuestro servicio\nnecesitas darte de alta con tu numero\ncelular y contraseña\n");
        System.out.println("Introduce tu numero celular de 10 degitos");
        }

    /* metodo encargado de almacenar
    *los datos de usuario*/
     private void rev_password(){
         boolean band_Password_Number=true;
         boolean band_Password_Contra=true;
         String Cofirmacion_Password="";

     while(band_Password_Number){
             number_Phone=entrada.next();
    if(number_Phone.matches(MATCH_NUMBER_PHONE)){
       System.out.println("correcto");

            band_Password_Number=false;
        }

    if(!number_Phone.matches(MATCH_NUMBER_PHONE)){
       System.out.println("numero ingresado incorrecto,\n ingreselo de nuevo");

        }
    }

    while(band_Password_Contra){
        System.out.println("introduce tu contraseña, que deben ser 10 caracteres\n y pueden ser\"numeros y letras MAY/MIN\"");

        password=entrada.next();

        if(password.matches(MATCH_PASSWORD)){
            System.out.println("porfavor confirmela de nuevo");

                Cofirmacion_Password=entrada.next();
                if(password.equalsIgnoreCase(Cofirmacion_Password)){

                    System.out.println("es correcto");
                    band_Password_Contra=false;

                }
                if(!password.equalsIgnoreCase(Cofirmacion_Password)){
                    System.out.println("error porfavor buelva a introducir su contraseña");
                    band_Password_Contra=true;
                }
            }

            if(!password.matches(MATCH_PASSWORD)){
                System.out.println("datos incorectos favor de ingresarlos de nuevo");

                band_Password_Contra=true;
            }

          System.out.println("usuario registrado");
    }
  }
}

A: El sistema no deja todavía hacer comentarios, por lo que te lo pongo por aqui:
En primer lugar como bien dijo Eduardo lo primero de todo sería usar la convención de nombres de constantes en mayúsculas y nombres de métodos con Camel Case
Yo separaría el main en otra clase pero eso ya es una manía mía
Sería conveniente darle una pista al usuario de los requerimientos de la contraseña con un mensaje por ejemplo:
Solo se aceptan letras minúsculas, mayúsculas y números con una longitud máxima de diez carácteres
Tambien revisaría la ortografía en las líneas:
47:
String Cofirmacion_Password;
79:
System.out.println("error porfavor buelva a introducir su contraseña");
Algunas tildes no importantes
Tambien he visto que das por hecho que un telefono es de 10 carácteres cuando en realidad es de 9 u once en el caso de que quieras registrar los dos numeros del principio que identifican cada país (en el caso de españa 34)
Si quieres hacer mas legible tu codigo usa el mismo idioma para las variables en todo el código y nombres mas específicos como por ejemplo
band_Password_Number --> phoneNumberOK
Cofirmacion_Password --> passwordOK
Añadiría un asterisco a tus comentarios para documentar los métodos nose en que IDE trabajas pero en netbeans necesitas empezar por /** para que te lo pille como javadoc quedaría asi el método rev_password()
/**
 * metodo encargado de almacenar los datos de usuario
 */

Por último yo usaría LOGs para registrar entradas a métodos por si ocurre alguna excepción saber por donde ha pasado no debería saltar excepción pero, quien sabe...
A bote pronto esto es lo que vi mirando tu código puede que me deje alguna cosa
Un saludo y gracias por leerme


text:
Q: How to get rid of horizontal scroll bar when shrinking window? Using the HTML and CSS below, you'll notice that rather than shrinking to fit the browser window, the site gets a horizontal scroll bar when shrunk down to 189px width. I've gone through my code and I cannot seem to figure out why this is happening. Keep in mind I'm a newbie so I might very well have overlooked something.
Also, I have a bonus question if that is allowed: I want to shrink the menu height but it seems impossible. How would you go about it?
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="index.css">
    <title></title>

Title

about

contact

donate

Article

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Article

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Article

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Article

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Footer

html body {
  margin: 0 auto;
  font-family: "Raleway", sans-serif;

}

.wrapper {
  margin: 0 auto;
  display: grid;
  grid-gap: 10px;
  grid-template-areas:
  "header"
  "menu"
  "pic"
  "content"
  "content2"
  "footer";
}

.header {
  grid-area: header;
  background-color: lightgrey;
}

.header h1 {
  margin-left: 0;
  padding-left: 0;
}
.menu {
  grid-area: menu;
  padding: 0;
  line-height: 2;

}
.menu a {
  text-decoration: none;

}
.menu a:link {
  color: black;
}
.pic {
  grid-area: pic;

}

img {

  width: 100%;
  height: auto;
}
.content {
  grid-area: content;

}
.content2 {
  grid-area: content2;
}
.footer {
  grid-area: footer;
  background-color: lightgrey;

}

.wrapper > * {
  margin: 0px 30px;
}
.header, .footer {

  padding: 0px 30px;
}

@media screen and (min-width: 500px) {
.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-rows: 1fr 1fr;
grid-template-areas:
"header header"
"menu menu"
"pic pic"
"content content2"
"footer footer";
}
.menu {
  display: flex;
  flex-direction: row;
  margin-left: auto;
}
.menu a {
  padding-right: 10px;

}
}

JSFiddle link: https://jsfiddle.net/tzrqf5np/

A: I fixed your CSS as you wanted. You really should start making sure you get your spacings right. it has no direct influence in HTML and CSS but helps reading and is a good practise for other languages. There plently languages where spacings make a difference if a code works or not. But having it easier to read espacially with programs like Visual Studio Code the advantage is that you see which closing tags belong to which starting tag.
Please try to practice it for me "my little padawan" :P
Ok One change of formatting was to the media query:

@media only screen
  and ...
  and ... {
    body {
      random-code: xy;
    }
}

espacilly if you use media query to adress screens use only screen. Even it works nearly always take it as a good habit same as getting your spacings right. Then get a new line with and... what every you want to use. you can combine that way many rules like min-width and max-width, orientation: landscape/portrait screen format...
then you used: grid-template-rows: 1fr 1fr; I switched it to grid-template-columns: 1fr 1fr; and added the grid-auto-rows: auto; and tada: its working. The menu is way smaller just like you wanted.
Next the picture got a width of auto. that way it shouldnt create a horizontal scrollbar. a width of 100% will as it will add the 100% to the margin and paddings on top and then the width is wider then the screen.

html body {
  margin: 0 auto;
  font-family: "Raleway", sans-serif;
}

.wrapper {
  margin: 0 auto;
  display: grid;
  grid-auto-rows: auto;
  grid-gap: 10px;
  grid-template-areas:
  "header"
  "menu"
  "pic"
  "content"
  "content2"
  "footer";
}

.header {
  grid-area: header;
  background-color: lightgrey;
}

.header h1 {
  margin-left: 0;
  padding-left: 0;
}
.menu {
  grid-area: menu;
  padding: 0;

}
.menu a {
  text-decoration: none;
}

.menu a:link {
  color: black;
}

.pic {
  grid-area: pic;
}

img {
  width: 100%;
  height: auto;
}

.content {
  grid-area: content;
}

.content2 {
  grid-area: content2;
}

.footer {
  grid-area: footer;
  background-color: lightgrey;
}

.wrapper > * {
  margin: 0px 30px;
}

.header, .footer {
  padding: 0px 30px;
}

@media only screen
  and (min-width: 500px) {
    .wrapper {
      display: grid;
      grid-gap: 10px;
      grid-template-columns: 1fr 1fr;
      grid-auto-rows: auto;
      grid-template-areas:
        "header header"
        "menu menu"
        "pic pic"
        "content content2"
        "footer footer";
    }

    .menu {
      display: flex;
      flex-direction: row;
      margin-left: auto;
    }

    .menu a {
      padding-right: 10px;
    }
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="index.css">
    <title></title>

Title

        about

        contact

        donate

Article

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Article

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Article

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Article

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Footer


text:
Q: Winsock2: How to allow ONLY one client connection at a time by using listen's backlog in VC++ I want to allow only one connection at a time from my TCP server. Can you please tell, how to use listen without backlog length of zero.
I m using the code(given below), but when i launch 2 client one by one, both gets connected. I m using VC++ with winsock2.
listen(m_socket,-1);
passing zero as backlog is also not working.
Waiting for ur reply.
Regards,
immi

A: If you can indeed limit your application to only use Winsock 2, you can use its conditional accept mechanism:
SOCKET sd = socket(...);
listen(sd, ...);
DWORD nTrue = 1;
setsockopt(sd, SOL_SOCKET, SO_CONDITIONAL_ACCEPT, (char*)&nTrue, sizeof(nTrue));

This changes the stack's behavior to not automatically send SYN-ACK replies to incoming SYN packets as long as connection backlog space is available.  Instead, your program gets the signal that it should accept the connection as normal -- select(), WSAEventSelect(), WSAAsyncSelect()... -- then you call WSAAccept() instead of accept():
sockaddr_in sin;
WSAAccept(sd, (sockaddr*)&sin, sizeof(sin), ConditionalAcceptChecker, 0);

You write the function ConditionalAcceptChecker() to look at the incoming connection info and decide whether to accept the connection.  In your case, you can just return CF_REJECT as long as you're already processing a connection.
Again, beware that this mechanism is specific to Winsock 2.  If you need portable behavior, the other posts' advice to close the listening socket while your program already has a connection is better.

A: You may set backlog equal to 1, since this is number of connections you want.
But AFAIK there's no hard warranty on queue size (this doc says it would be 1.5 * backlog on BSD, e.g.).
IMHO, you'd better control number of connections manually by not accept()'ing connections after some limit.

A: I would say, only accept once. If you only want one client at a time on your server you can use also only one thread to perform the handling. The backlog limits only the amount of pending connections handled by the system for accepting (the queue is empty again after the first accept so the next client gets into the backlog) not the amount of connections!

A: That's not what the listen backlog is for.
The listen backlog affects a queue that's used for pending connections, it allows the TCP stack to queue up pending connections for you to accept.
To do what you want to do you need to accept the one connection that you're allowing and then close the listening socket. Once you've finished with your single client you can recreate your listening socket and listen for a new connection. This will prevent more than a single client connecting to you but there will be no way for the client to know that you're actually running and accepting connections on a "one at a time" basis. All clients except the one that manages to connect will think you're just not there.
It's probably a better design to keep your listening socket open and accept all connections but once you have you "one" active connection you simply accept and then either send an application level message to your client telling it that you cant accept any more connections OR if you can't do that, simply close the new connection.


text:
Q: Альтернатива action url & post - form Подскажите, можно ли, например, при помощи curl'а выполнить запрос в стиле формы с последующей переадресацией ?
Ну т.е если есть форма, то там понятно все..вводим данные, метод POST и action на какой нибудь скрипт или ссылку.

Мне нужно заменить форму ajax'ом, где я посылаю данные на свой обработчик ($.ajax post url и т.п), который сформировал бы ссылку с POST параметрами и я мог бы ее вернуть для редиректа..Дайте совет, как лучше поступить, ибо формой ну прям вообще никак.
      $post_data = array(
//      'wmid'=>$WMID,
        'LMI_PAYEE_PURSE'=>$LMI_PAYEE_PURSE,
        'LMI_PAYMENT_NO'=>$LMI_PAYMENT_NO,
        'LMI_PAYMENT_AMOUNT'=>$LMI_PAYMENT_AMOUNT,
        'LMI_PAYMENT_DESC'=>'ququmber',
        'LMI_SIM_MODE'=>'0',

        );

$url = 'https://merchant.webmoney.ru/lmi/payment_utf.asp';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$output  = curl_exec ($ch) or die(curl_error($ch));

curl_close($ch);


text:
Q: Insert Image into Azure database as varbinary(max) using SSMS on local PC I am doing some testing to see if I can use SSRS with an Azure database to create a simple report. I want to include a signature image at the bottom of the report that I am storing as a blob in the database.
The problem I have is I created the signature file on my laptop and saved it on the C drive. When I try to insert it into the table on Azure using the following statement:
insert into Signatures (ImageFile)
values (CAST(SELECT * FROM OPENROWSET(BULK N'C:\Demos\SingnatureEg.png', SINGLE_BLOB) AS DefaultLogoImg));

As I am connected to the Azure database inside SSMS it cannot see the local file system. I ran the OPENROWSET separately using a connection to a locally stored database to generate the string. I copied and pasted it into the insert statement using a CAST to convert it to varbinary and the data inserted successfully. I used the following command:
insert into Signatures (ImageFile)
values (CAST('0x89504E470D0A....' AS VARBINARY(MAX)));

I hooked the image field up to an image object in my Report using the database field and the correct MIME Type of PNG and the image is not displaying correctly. I can only guess that the data didn't go into the table successfully.
How do I use the OPENROWSET command to insert the data into the Azure database when I can't access my local file system?


text:
Q: Error while using tm1r to send dataset. How to debug this issue? I am currently developing a database integrated forecasting tool for a costumer. I am using mainly R and TM1 Persepctives. To connect R with tm1 I use tm1r. For Data import from tm1 to r it works fine.
However, when I am trying to write back the calculated forecast from R to tm1, I run into problems.
I will give you some reprex data, so you can have a look at the output. If I use "tm2_send_data" instead of "tm1_send_dataset" it works fine too.
The latter function gives me the Error :
"Error in if (is.character(txt) && length(txt) == 1 && nchar(txt, type = "bytes") <  :
missing value where TRUE/FALSE needed"
I have no clue, what this is supposed to mean! I tried some formatting of the data types, without any effect.
library(tm1r)

# data
values <- data.frame(fake_values =
  c(105,147,159,232,312,337,285,188,257,10,98,27)
  )
date_stamps <- c("2021001","2021002","2021003","2021004","2021005","2021006","2021007","2021008","2021009","2021010","2021011","2021012")
rownames(values) = date_stamps

# Send dataset to TM1
con_obj <- tm1_connection("localhost", "8840", "test_admin", "")

tm1_send_dataset(
  con_obj,
  valueset = values, cube = "pvl_FORECAST_HILFSWÜRFEL",
  rowdim = "PVL_test_Zeit", coldim = "pvl_Produkt",
  titledim1 = "DATENART", titleel1 = "FC",
  titledim2 = "Version", titleel2 = 'Version_Bearbeitung',
  titledim3 = "FC-Scheibe", titleel3 = "ML_FC_2021",
  titledim4 = "PVL_test_Kunde", titleel4 = "MGR_domestic_D",
  titledim5 = "PVL_test_Measure", titleel5 = "Menge_EA"
)


text:
Q: Compare two dates in String format - String comparison vs Date Comparison I want to compare two dates to identify which date is older. The dates are stored in String format like
let stringA = "2022-11-14"
let stringB = "2022-11-13"

I can asure that all dates will be saved in this String format: yyyy-MM-dd
In my locale testing I was able to run
let compare = stringA > stringB

With various dates I always got the correct result true/false.
Is this the correct way of comparing those dates? Or should I use a DateFormatter to compare all those dates in Date format?
P.S. I know how two convert those Strings to Dates and compare them afterwards. I just want to avoid it if possible because the String comparison is shorter, easy to read and would save redundant code if possible.

A: you can convert string to date and compare easily just add following String extension in your code
  extension String {
    func toDate() -> Date? {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd" //you can add any date formatter I just added according to your question formate
        return formatter.date(from: self)
    }
}

Use it like this in ViewController
 class ViewController: UIViewController {

    let stringA = "2022-11-13"
    let stringB = "2022-11-13"

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let date1 = stringA.toDate(), let date2 = stringB.toDate() else {
            print("not able to convert to date")
            return
        }

        let result = date1.compare(date2)
        switch result {
        case .orderedAscending:
            print("Ascending")
        case .orderedDescending:
            print("Descending")
        case .orderedSame:
            print("same")
        }
    }
}

you can check this answer for different date formatters.


text:
Q: Fields of java.awt.geom.Rectangle2D? Not a Java person here, I'm just trying this code in Processing.org:
//import java.awt.Rectangle; // int only
import java.awt.geom.Rectangle2D;

Rectangle2D testr;

void setup() {
  testr = new Rectangle2D.Float(1.0, 1.0, 30.0, 30.0);
  println(testr);
  //println(testr.x);
}

It prints out:
java.awt.geom.Rectangle2D$Float[x=1.0,y=1.0,w=30.0,h=30.0]

... which sort of implies where are x and y fields accessible? Even Rectangle2D.Float (Java Platform SE 7 ) says:

Field Summary
  ...
  float     x
  The X coordinate of this Rectangle2D.

And yet, if I uncomment println(testr.x);, compilation fails with:
testr.x cannot be resolved or not a field.

Where am I going wrong - and why cannot I access a field, which the documentation clearly says exists?
Btw, this is what I find in /tmp as the full .java source when the processing .pde manages to compile:
import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;

import java.awt.geom.Rectangle2D;

import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

public class sketch_140204c extends PApplet {

//import java.awt.Rectangle; // int only

Rectangle2D testr;

public void setup() {
  testr = new Rectangle2D.Float(1.0f, 1.0f, 30.0f, 30.0f);
  println(testr);
}

  static public void main(String[] passedArgs) {
    String[] appletArgs = new String[] { "sketch_140204c" };
    if (passedArgs != null) {
      PApplet.main(concat(appletArgs, passedArgs));
    } else {
      PApplet.main(appletArgs);
    }
  }
}

A: These fields are declared on Rectangle2D.Float but testr is just a Rectangle2D. Changing its declaration will let you access them since they are public:
Rectangle2D.Float testr;

It's a good suggestion to use getters and setters but there aren't individual setters for these classes. Only setters to set the entire rectangle (namely setRect).

A: These fields are declared on Rectangle2D.Float you can print to control.
Ellipse2D.Float test= new Ellipse2D.Float(getPosX()-40,getPosY()-40,30.0f, 30.0f);
        System.out.println(test.getCenterX());
        System.out.println(test.getCenterY());
        System.out.println(test.getMinX());
        System.out.println(test.getMinY());
        System.out.println(test.getMaxX());
        System.out.println(test.getMaxY());


text:
Q: Google sheet API - reset auto numbered sheet name I'm using google sheet api with this logic for each request:

*

*create a sheet,

*add custom query there (custom formula),

*fecth query results,

*delete the created sheet.

The creation code is a follow with Laravel:
class GoogleSheetsApiClientManager {

    private $client;//authorized API client.
    private $service = null;

    public function __construct($apiOptions) {
        $this->client = new Google_Client();
        $this->client->setApplicationName(array_get($apiOptions, 'application_name', 'Google Sheets API PHP'));
        $this->client->setScopes(array_get($apiOptions, 'scope', Google_Service_Sheets::SPREADSHEETS));
        $this->client->setAuthConfig(array_get($apiOptions, 'credential_path'));
        $this->client->setAccessType('offline');

        $this->service = new Google_Service_Sheets($this->client);
    }

    public function addNewSheet($spreadsheetId, $hidden = false, $sheetName = false){
        try {
            $properties = [
                'hidden' => $hidden
            ];
            if($sheetName){
                $properties['title'] = $sheetName;
            }
            $body = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
                'requests' => [
                    'addSheet' => [
                        'properties' => $properties
                    ]
                ]
            ]);
            $result = $this->service->spreadsheets->batchUpdate($spreadsheetId, $body);
            return $result;
        }
        catch (\Exception $exception) {
            Log::error('Add new sheet using Google Sheet API : '.$exception->getMessage());
            return false;
        }
    }

}

And the call is like:
$apiOptions = [
            'application_name' => 'My app name',
            'credential_path' => __DIR__.'/service_account-secret.json'
        ];
$googleSheetManager = new GoogleSheetsApiClientManager($apiOptions);
$spreadsheetId = '--theSpreasheetId--';
$mySheet = $googleSheetManager->addNewSheet($spreadsheetId);

The issue : Each time I create new sheet, its name is based on last created one. eg: last sheet name is sheet5, even sheet5 has been deleted I got new sheet with name sheet6.
What I would like to have is the minimal possible name, meaning if sheet5 & sheet4 are not there (but sheet3 is present), I would like a new name sheet4, not an endless incremented name


text:
Q: Importing CSV file with Quoted ( " ) quote ( ' ) - import is mismatching quote types I am importing some data from a CSV file into a MySQL db. This has been workign well until I had a row come up which uses a single quote in the Description field.
The problematic row in the CSV is this:
"2019","3982","2018-12-16","black, height - 16.0 ', matte, waterproof, ellipsoid","42","PXC Mfg Inc","emarkham@______.com"

The SQL import is
LOAD DATA INFILE :file
            INTO TABLE $table_name
            FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
            LINES TERMINATED BY '\r\n'
            IGNORE 1 LINES
            (Year,Price,StockDate,Description,Quantity,Supplier,Contact)

Given that all columns are double quoted, I would expect the result to be
 Year | Price | StockDate  | Description                                          | Quantity | Supplier    | Contact
------+-------+------------+------------------------------------------------------+----------+-------------+---------------------
 2019 |  3982 | 2018-12-16 | black, height - 16.0 ', matte, waterproof, ellipsoid | 42       | PXC Mfg Inc | emarkham@______.com

but what I actually got was
 Year | Price | StockDate  | Description          | Quantity  | Supplier  | Contact
------+-------+------------+----------------------+-----------+-----------+----------
 2019 | 3982  | 2018-12-16 | black, height - 16.0 | 0         | waterproof| ellipsoid

As you can see the single quote (indicating 16 inches) has been interpreted as the end of that value. This is certainly not the desired result.
Anyone know how to correct this?


text:
Q: CentOS 6 - php5-pam-auth? Where do I get an updated version of the PHP pam_auth module? Can't find it on yum and the latest version I can find to download is for PHP 4.3.

A: I was looking for the answer to this myself, and eventually wound up having to solve it myself.  Since I'd found this question earlier in my searches, I figured I'd provide what worked for me :)

*

*Download the pam_auth source from http://svn.php.net/viewvc/pecl/pam/trunk/
(or for convenience I have zipped the latest files, current as of revision 324283, here)

*Change into the directory you've downloaded/unzipped/etc the files into, and run the following commands:

*

*phpize

*./configure

*make

*make install

*Add extension=pam.so to your php.ini

*Restart Apache; use phpinfo() to ensure the PAM module is running.
When verifying via phpinfo(), there should be a section like so:

I successfully installed pam_auth on CentOS 5.6/Apache 2.2.3/PHP 5.3.10 using the above instructions; hopefully it will work just as well on CentOS 6. Good luck!


text:
Q: OpenXML SDK: How to identify data type of cell? I am working on OPenXML SDK to work with excel. Currently, I am facing with one issue, how to identify data type of cell, datetime or numeric. Because, in case cell's type is date, we need to convert double value to datetime again.

A: Based on information I have found from the OpenXML SDK help files I have written the following code which should answer your question
public class ExcelEngine : IExcelEngine
{
    private readonly SpreadsheetDocument _wb;
    private WorkbookPart _wbp;
    private SharedStringTablePart _sstp;

    // Used to cache the lookup of worksheet parts
    private Dictionary<string, WorksheetPart> _wsParts = new Dictionary<string, WorksheetPart>();

    #region Constructors

    public ExcelEngine(Stream stream)
    {
        Contracts.IsNotNull(stream);

        _wb = SpreadsheetDocument.Open(stream, false);
        Initialise();
    }

    public ExcelEngine(string fileName)
    {
        Contracts.IsNullOrWhiteSpace(fileName);

        _wb = SpreadsheetDocument.Open(fileName, false);
        Initialise();
    }

    #endregion

    #region IExcelEngine

    /// <summary>
    /// Get the list of sheet names from the spreadsheet
    /// </summary>
    /// <returns></returns>
    public IList<string> GetSheetNames()
    {
        return _wbp.Workbook
            .Descendants<Sheet>()
            .Select(s => s.Name.Value)
            .ToList<String>();
    }

    /// <summary>
    /// Given a sheet name and a cell reference, return the contents of the cell
    /// </summary>
    /// <param name="sheetName"></param>
    /// <param name="addressName"></param>
    /// <returns></returns>
    public string GetCellValue(string sheetName, string addressName)
    {
        return GetCellValueLocal(sheetName, addressName);
    }

    /// <summary>
    /// Given a sheet name and a cell reference, return the contents of the cell as a boolean value
    /// </summary>
    /// <param name="sheetName"></param>
    /// <param name="addressName"></param>
    /// <returns></returns>
    public bool GetCellBool(string sheetName, string addressName)
    {
        var value = GetCellValueLocal(sheetName, addressName);

        bool result;
        bool.TryParse(value, out result);

        return result;
    }

    #endregion

    #region Private Methods

    private void Initialise()
    {
        _wbp = _wb.WorkbookPart;
        _sstp = _wbp.GetPartsOfType<SharedStringTablePart>().First();
    }

    private string GetCellValueLocal(string sheetName, string addressName)
    {
        string value = null;

        WorksheetPart wsPart = GetWorkSheetPart(sheetName);

        // Use its Worksheet property to get a reference to the cell
        // whose address matches the address you supplied.
        Cell cell = wsPart.Worksheet.Descendants<Cell>().
            Where(c => c.CellReference == addressName).FirstOrDefault();

        if (cell != null)
        {
            value = cell.InnerText;

            if (cell.DataType != null)
                switch (cell.DataType.Value)
                {
                    case CellValues.SharedString:
                        int ssid = int.Parse(cell.CellValue.Text);
                        value = _sstp.SharedStringTable.ElementAt(ssid).InnerText;
                        break;

                    case CellValues.Boolean:
                        switch (value)
                        {
                            case "0":
                                value = "FALSE";
                                break;
                            default:
                                value = "TRUE";
                                break;
                        }
                        break;

                    case CellValues.Date:
                        break;

                    case CellValues.String:
                        break;
                }
            Debug.WriteLine($"Cell {cell.CellReference}: '{value}'");
        }

        return value;
    }

    private WorksheetPart GetWorkSheetPart(string sheetName)
    {
        // Does it exist in the cache? If not, load it
        if (!_wsParts.ContainsKey(sheetName))
        {
            // Find the sheet with the supplied name, and then use that
            // Sheet object to retrieve a reference to the first worksheet.
            Sheet theSheet = _wbp.Workbook.Descendants<Sheet>()
                .Where(s => s.Name == sheetName)
                .FirstOrDefault();

            // If not sheet throw an exception
            if (theSheet == null)
                throw new ArgumentException($"Sheet {sheetName} not found in workbook");

            // Retrieve a reference to the worksheet part.
            _wsParts.Add(sheetName, (WorksheetPart) (_wbp.GetPartById(theSheet.Id)));
        }

        return _wsParts[sheetName];
    }

    #endregion

    public void Dispose()
    {
        _wb.Close();
        _wb.Dispose();
    }
}


text:
Q: antlr nongreedy operator fails to match a valid input The following rule in antlr4 will not work for a valid input:
testSimple
    : 'name' 'eq' WORD+?  .*? NEWLINE

WORD:  ~[ \t\f\r\n]+ ;

The input is :
name eq John Tom Allen notAName

The error is:
line 1:8 no viable alternative at input 'John'

I know using nongreedy operator has some limitations, like the 'first match wins' rule afterwards.  And the rule is particularly ambiguous. But shouldn't it at least match the input in at least one way?

A: Try parsing with an explicit EOF symbol on the end of your entry rule. For example:
startTestSimple
    :   testSimple EOF
    ;

Without the explicit EOF in place, the algorithm may fail to find a viable alternative in some cases. Issue #118 describes one case where this is a problem; unfortunately the performance impact of the known solution is quite large, so we won't be including it in the ANTLR 4 runtime until we come up with an alternate solution.


text:
Q: kotlin.TypeCastException: null cannot be cast to non-null type com.midsizemango.databasekotlin.Note I am trying to code my app in Kotlin, but I am getting null cannot be casted to non-null type and app force stops when I open EditNoteActivity at EXTRA_NOTE probably.
Any Help is Highly Appreciated
Code:
class EditNoteActivity : AppCompatActivity() {

var note: Note? = null

private val editNote: TextView? = null

private val fabdrwble: Boolean? = null
private val notesData: MutableList<Note>? = null
private var databaseHelper: DatabaseHelper? = null

private val save: Boolean? = null
private var saveButton: FloatingActionButton? = null
private val tint: ColorStateList? = null

internal var mRowId: Long? = null

internal var spinner: Spinner? = null
internal var spinnertext: String? = null

internal var fav: Int = 0

internal var mSharedFromIntentFilter = false

internal var editTitle: EditText? = null
internal var editContent: EditText? = null
internal var inputlayoutTitle: TextInputLayout? = null
internal var inputlayoutContent: TextInputLayout? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_edit_note)

    var toolbar = findViewById(R.id.toolbar_edit) as Toolbar?
    setSupportActionBar(toolbar)

    if (supportActionBar != null)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)

    databaseHelper = DatabaseHelper(applicationContext)

    inputlayoutTitle = findViewById(R.id.inputlayoutTitle) as TextInputLayout?
    inputlayoutContent = findViewById(R.id.inputlayoutContent) as TextInputLayout?
    editTitle = findViewById(R.id.note_title) as EditText
    editContent = findViewById(R.id.note_content) as EditText?

    val bundle = intent.extras
    val s = bundle.getString("edit")

    if (s == "add") {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
    } else if (s == "editv") {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
    }

    note = intent.getSerializableExtra(EXTRA_NOTE) as Note
    if (note != null) {
        editTitle?.setText(note!!.getTitle())
        editContent?.setText(note!!.getContent())
    } else {
        note = Note()
        //note.setUpdatedAt(new Date());
    }

    saveButton = findViewById(R.id.add_edit_button) as FloatingActionButton?
    saveButton!!.setOnClickListener {
        if (isNoteFormOk) {
            setNoteResult()
            finish()
        } else
            validateNoteForm()
    }

    var ll = findViewById(R.id.llmain) as LinearLayout?
    var ll1 = findViewById(R.id.ll1) as LinearLayout?

    /*if(note.getColor() == Color.TRANSPARENT){
        selectedColor = preselect;
    }else {
        selectedColor = note.getColor();
    }

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

    systemBarTintManager = new SystemBarTintManager(this);
    systemBarTintManager.setStatusBarTintEnabled(true);

    ll.setBackgroundColor(selectedColor);
    ll1.setBackgroundColor(selectedColor);
    toolbar.setBackgroundColor(note.getColor());
    systemBarTintManager.setStatusBarTintColor(selectedColor);*/

}

override fun onResume() {
    super.onResume()
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {

        android.R.id.home -> {
            onBack()
            return true
        }
    /*
        case R.id.speech:
            try {
                displaySpeechRecognizer();
            } catch (ActivityNotFoundException e) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://market.android.com/details?id=com.google.android.googlequicksearchbox"));
                startActivity(browserIntent);
            }
            return true;*/

        else -> return super.onOptionsItemSelected(item)
    }
}

private fun displaySpeechRecognizer() {
    val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
    startActivityForResult(intent, SPEECH_REQUEST_CODE)
}

override fun onActivityResult(requestCode: Int, resultCode: Int,
                              data: Intent) {
    if (requestCode == SPEECH_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        val results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
        val spokenText = results[0]
        editContent?.setText(spokenText)
    }
    if (requestCode == RequestResultCode.REQUEST_CODE_ADD_NOTE) {
        if (resultCode == Activity.RESULT_OK) {
            addNote(data)
        }
    }
}

private val isNoteFormOk: Boolean
    get() {
        val title = editTitle?.text.toString()
        return !(title == null || title.trim { it <= ' ' }.length == 0)
    }

private fun validateNoteForm() {
    var msg: String? = null
    if (isNullOrBlank(editTitle?.text.toString())) {
        msg = "Title Required"
        inputlayoutTitle?.error = "Title is Missing"
    }
    if (msg != null) {
        Toast.makeText(applicationContext, msg, Toast.LENGTH_LONG).show()
    }
}

private fun setNoteResult() {
    note!!.setTitle(editTitle?.text.toString().trim { it <= ' ' })
    note!!.setContent(editContent?.text.toString().trim { it <= ' ' })
    //note.setUpdatedAt(new Date());
    val intent = Intent()
    intent.putExtra(EXTRA_NOTE, note)
    setResult(Activity.RESULT_OK, intent)
    //addNote(intent);

    Toast.makeText(this@EditNoteActivity, "Note Saved.", Toast.LENGTH_LONG).show()
}

private fun onBack() {
    if (isNoteFormOk) {
        if (editTitle?.text.toString() == note!!.getTitle() && editContent?.text.toString() == note!!.getContent()) {
            setResult(Activity.RESULT_CANCELED, Intent())
            finish()
        } else {
            AlertDialog.Builder(this@EditNoteActivity)
                    .setTitle("Save")
                    .setMessage("Do You Want to Save Note")
                    .setPositiveButton("SAVE") { dialog, which ->
                        setNoteResult()
                        finish()
            }.setNegativeButton("CANCEL") { dialog, which ->
                setResult(Activity.RESULT_CANCELED, Intent())
                finish()
            }.show()
        }
    } else {
        setResult(Activity.RESULT_CANCELED, Intent())
        finish()
    }
}

private fun addNote(data: Intent) {
    val note = data.getSerializableExtra(EXTRA_NOTE) as Note
    val noteId = databaseHelper!!.createNote(note)
    note.setId(noteId)
}

override fun onBackPressed() {
    onBack()
    val intentHome = Intent(this@EditNoteActivity, MainActivity::class.java)
    intentHome.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
    intentHome.putExtra(EXTRA_NOTE, note)
    setResult(Activity.RESULT_OK, intentHome)
}

companion object {

    private val EXTRA_NOTE = "EXTRA_NOTE"
    private val SPEECH_REQUEST_CODE = 0

    fun isNullOrBlank(str: String?): Boolean {
        return str == null || str.trim { it <= ' ' }.length == 0
    }
}
}

Logs:

java.lang.RuntimeException: Unable to start activity ComponentInfo{
com.midsizemango.databasekotlin/com.midsizemango.databasekotlin.EditNoteActivity}:
kotlin.TypeCastException: null cannot be cast to non-null type
com.midsizemango.databasekotlin.Note
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
    at android.app.ActivityThread.access$800(ActivityThread.java:144)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: kotlin.TypeCastException: null cannot be cast to non-null type com.midsizemango.databasekotlin.Note
    at com.midsizemango.databasekotlin.EditNoteActivity.onCreate(EditNoteActivity.kt:82)
    at android.app.Activity.performCreate(Activity.java:5933)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
    at android.app.ActivityThread.access$800(ActivityThread.java:144)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:694)

A: In this line:
note = intent.getSerializableExtra(EXTRA_NOTE) as Note

Note is a non-null type, so the cast to it triggers a null check. Since you're comparing note to null manually afterwards, probably you meant the safe cast operator, which yields null if the expression is not of the type specified in the right-hand side:
note = intent.getSerializableExtra(EXTRA_NOTE) as? Note


text:
Q: Undefined variable: nombre (View: C:\wamp64\www\curso-laravel\prueba-laravel\resources\views\Contacto.blade.php) Buenas espero puedan ayudarme estoy creando una ruta tipo get a la cual le estoy pasando dos variables mediante una funcion pero al momento de actualizar la pagina me dice el siguiente error:
Undefined variable: nombre (View: C:\wamp64\www\curso-laravel\prueba-laravel\resources\views\Contacto.blade.php)
este es el codigo de la ruta:
Route::get('contacto/{nombre?}/{edad?}', function($nombre = "Andres Guerrero", $edad = "26")
{
    return view('contacto', array(
        "nombre" => $nombre,
        "edad" => $edad));
})->where (['nombre'=>'[A-Za-z]+','edad' =>'[0-9]+');

Este es el codigo de la vista donde quiero mostrar esa informacion:

Nombre de Contacto   {{$nombre}} {{$edad}}


text:
Q: What is the best practice to programmatically set SQL indexes with Entity-Framework-Code-First I am using Asp.Net MVC 3, Entity-Framework 4.1 and was wondering if there is any useful way to set SQL indexes programmatically on some columns in my model.

A: You can setup a Database Initializer to create indexes
public class MyInitializer : CreateDatabaseIfNotExists<MyDbContext>
{
    protected override void Seed(MyDbContext context)
    {
        //your logic here
        context.Database.ExecuteSqlCommand("CREATE INDEX IX_Products_Code ON dbo.Products ( Code )");

    }
}

Then you can setup the initializer on startup
Database.SetInitializer<ProductCatalog>(new MyInitializer());


text:
Q: Magento2: How to overwrite vendor/magento/module-configurable-product/view/frontend/templates/product/view/type/options/configurable.phtml Magento2: How to overwrite
/var/www/html/vendor/magento/module-configurable-product/view/frontend/templates/product/view/type/options/configurable.phtml

A: Just do following steps
1 . Add phtml file in your layout xml file
<action method="setTemplate">
     <argument name="template" xsi:type="string">Namespace_Modulename::configurable.phtml</argument>
</action>

*After that add configurable.phtml file in your module/view/frontend/templates/ folder

Note : Clear cache
For more information click here


text:
Q: Make Team City build result(couple of str variable) avaliable via HTTP API I have a build with Command line build step with app which have couple of str variables as a result. I can make this str avaliable via HTTP api after build finish.
I tried print to STDOUT '##teamcity[setParameter name='env.' value='']'  - this ENV variables available via buildParameters tab but missing in https://<TC_HOST>/httpAuth/app/rest/builds/id:<BUILD_ID> resource. How to make  this?

A: Use https://<TC_HOST>/httpAuth/app/rest/builds/id:<BUILD_ID>/resulting-properties


text:
Q: android namevaluepair alternate methods In Andorid  NameValuePair,BasicNameValuePair
deprecated.
I have
List<NameValuePair> pairs = new ArrayList<NameValuePair>(1);
pairs.add(new BasicNameValuePair("student",string1));

What will be alternative for this code?

A: Try using a List of Pair objects, code below from this answer:
List<Pair<String, String>> params = new ArrayList<>();
params.add(new Pair<>("username", username));
params.add(new Pair<>("password", password));

A: You can use ContentValues for example
ContentValues values=new ContentValues();
values.put("student",string1);


text:
Q: Open a remote file with Roo gem uploaded using Active Storage on Heroku and Amazon S3 I am using the ROO gem to parse an Excel file uploaded by the user (Active Storage with AWS S3) on Heroku.
Since I am on Heroku I cannot download it on filesystem and then parse it. How can I open it from HTTP?
Model
class Report < ApplicationRecord
  has_one_attached :search_report

def parsing_method(path_http)

   xlsx = Roo::Spreadsheet.open(path_http)
end

A: Yes, you can download it in Heroku into the filesystem.
I doubt theres much space, but you should be able to use the temp file. Most system stores an upload into the temp file system before pushing it somewhere else.
I'm already doing it, since Roo was patch to be able to open Excel files from the stream, but no other type (csv, ods, etc).
def create_temp_file
  filename = some_model.some_attachment.blob.filename
  @tmp = Tempfile.new([filename.base, filename.extension_with_delimiter], binmode: true)
  @tmp.write(ome_model.some_attachment.download)
  @tmp.rewind
  @tmp
end

# this is how you use it, note the rescue part
def access_the_file
  spreadsheet = Roo::Spreadsheet.open(create_temp_file)
  # access the spreadsheet as usual
rescue
  @tmp&.unlink
end

This preserves the file prefixes and extensions (important to let Roo infer what the file is) and ensures the file get deleted when done.

A: ModelName.filename.blob.open do |file|
  write your code here ...
end

A: You can temporarily download the file with open method
report.search_report.open do |file|
    xlsx = Roo::Spreadsheet.open(file)
end

A: In a similar application, I used this:
def parsing_method(path_http)

   xlsx = Roo::Excelx.new(path_http, nil, :ignore)

end

It should work for you.


text:
Q: repeated number in string impala regex I need to filter rows with repeated numbers in some id field in a table. For that i use a regular expression
\b(\d)\1+\b

This is an example of the regex.
https://regex101.com/r/rJ7hJ6/7
But in impala this solution doesn't work. I tried
select regexp_like('1111111111', '([0-9])\1+'); i this case return True
select regexp_like('2222', '([0-9])\1+'); In this case return False
I think is because impala don't recognize \1 operator so i added another backslash to the query to escape the operator
select regexp_like('1111111111', '([0-9])\\1+');
But when execute that i get a syntax error
Invalid regex expression: '([0-9])\1+'

Someone know whats is happened?? and how can fix that?
Thanks!


text:
Q: How Can we use ISNULL to all Column Names in SQL Server 2008? I have a question
I tried to google it but looks like they don't like *
I'm using SQL Server 2008.
I have the following database table:
 P_Id   ProductName UnitPrice   UnitsInStock    UnitsOnOrder
------------------------------------------------------------------------
   1    Jarlsberg   10.45                 16    15
   2    Mascarpone  Null                  23    NULL
   3    Gorgonzola  15.67                  9    20

If I need to replace the null with a string I know I do :
 SELECT ISNULL(UnitsOnOrder,'No Data') FROM tbl

Questions

*

*How can I use ISNULL() with multi column names ?

*is it possible to use it with *
Like
SELECT ISNULL(* , 'NO data') FROM tbl

I think this will be tricky because of the datatype, you can't pass string to INT datatype  so how can I fix this too
Update
Okay if i use ISNULL() with a datatype of int it will return 0
which will be a value to me , how can i pass empty string instead ?

A: Try this...
ISNULL (COALESCE (column1, column2), 'No Data')

You would need to include all column names though, you can't use *
COALESCE returns the first non-null value in its argument list so if they are all null it will return null

A: You can use ISNULL multiple times in the same SQL statement for different columns, but you must write it separately for each column:
SELECT
    ISNULL(ProductName, 'No Data') AS ProductName,
    ISNULL(CAST(UnitPrice AS NVARCHAR), 'No Data') AS UnitPrice,
    ISNULL(CAST(UnitsInStock AS NVARCHAR), 'No Data') AS UnitsInStock,
    ISNULL(CAST(UnitsOnOrder AS NVARCHAR), 'No Data') AS UnitsOnOrder
FROM tbl

If you are building a dynamic SQL query, you could theoretically gather a list of columns in the table and generate a query with ISNULL on each one.  For example:
DECLARE @SQL nvarchar(max)

SET @SQL = 'SELECT '

SELECT @SQL = @SQL + 'ISNULL(CAST([' + sc.name + '] AS NVARCHAR), ''No Data'') AS [' + sc.name + '],'
FROM sys.objects so
INNER JOIN sys.columns sc ON sc.object_id = so.object_id
WHERE so.name = 'tbl'

-- Remove the trailing comma
SELECT @SQL = LEFT(@SQL, LEN(@SQL) - 1) + ' FROM tbl'

EXEC sp_sqlexec @SQL

This code has problems when converting some column types like timestamps to an nvarchar, but it illustrates the technique.
Note that if you had another column that should be returned if a value is null, you could use the COALESCE expression like this:
SELECT COALESCE(ProductName, P_Id) AS Product...


text:
Q: How express this code mathematically? Any programmer can explain how express this code in math terms?
public static int px32(int p){
    int h = 0;
    for (int i = 0; i < p; i = i + 32) { h++; }
    return h;
}

A: Summarizing the thread so far, the code above (along with a if(p <= 0) { return 0; }) computes
\begin{matrix}
&{\rm R\acute{o}cherz} &\text{achille hui}\\
h={}&\left\lceil\dfrac{\max\{0,p\}}{32}\right\rceil &=\left\lfloor\dfrac{\max\{0,p\}+31}{32}\right\rfloor & \qquad \text{for } p \in \mathbb{Z}.
\end{matrix}
However, since $32 =2^5$ is a power of $2$, perhaps the fastest way to compute $h$ is (zwim):
return (p<0) ? 0 : ((p+31)>>5);.


text:
Q: Configure Spring Security headers() by route Is it possible with spring security to have different header().contentSecurityPolicy("...") settings for different route matchers?
I am currently using the following spring security configuration:
@Configuration
@EnableWebSecurity
public static class MyWebSecurityConfigurerAdapter extends  WebSecurityConfigurerAdapter {
    @Override
    protected final void configure(HttpSecurity httpSecurity) throws Exception     {
        httpSecurity.csrf().disable()
                .rememberMe().disable()
                .headers()
                .cacheControl().disable()
                .referrerPolicy().and()
                .contentSecurityPolicy("default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'").
// followed by .authorizeRequests() section

There is a bug or at least underspecified behaviour in chrome (https://bugs.chromium.org/p/chromium/issues/detail?id=271452) that prevents the browser from displaying PDF documents if the resource is served with a CSP-Header with a strict object-src policy.
To avoid that behaviour, I'd like to provide different contentSecurityPolicy() configuration for different route matchers (in this case one for "../*.pdf" (or even better a matcher that matches on the response content type) and another for all other requests).

A: This code will create two security filters for two different URLs. Each will have it's own content security policy:
@Configuration
@Order(1)
class PatterWebSecurityConfigurer : WebSecurityConfigurerAdapter() {
    override fun configure(http: HttpSecurity) {
        http
            .antMatcher("/pattern")
            .headers().contentSecurityPolicy("directives")
    }
}

@Configuration
@Order(2)
class OtherPatternWebSecurityConfigurer : WebSecurityConfigurerAdapter() {
    override fun configure(http: HttpSecurity) {
        http
            .antMatcher("/otherPattern")
            .headers().contentSecurityPolicy("other directives")
    }
}


text:
Q: JS Plug in or CSS that cuts an image in hexagon I'm new at scripting for web.  I am looking for a JavaScript or Jquery plug-in that crops an image on (custom provided) dimensions, in form of a hexagon (attached image).
Ideally it would be great if it could be done by CSS, but if not, then any JS or JQuery plugin may work.

A: Here is my attempt at the function you want:
function polygonalCrop(options) {
    function extend(a, b){
        b=b||{};
        for(var key in b)
            if(b.hasOwnProperty(key))
                a[key] = b[key];
        return a;
    }

    options=extend({
        url:null,
        sides:8,
        angle:0,
        centerX:null,
        centerY:null,
        radius:null,
        outlineColor:null,
        outlineThickness:null,
        success:function(url){},
        fail:function(ev){}
    },options);
    if (!options.url) throw 'options needs an image URL as url property';
    var img=new Image();
    img.setAttribute('crossOrigin', 'anonymous');
    img.onload=function() {
        var w=this.width;
        var h=this.height;
        var canvas=document.createElement('canvas');
        canvas.width=w;
        canvas.height=h;
        var ctx=canvas.getContext('2d');
        if (options.centerX===null) {
            options.centerX=w/2;
        }
        if (options.centerY===null) {
            options.centerY=h/2;
        }
        var ang=2*Math.PI/options.sides;
        var len=Math.sin(ang/2)*2;
        if (options.radius===null) {
            options.radius=Math.min(w/2,h/2)*Math.cos(ang/2);
        }
        ctx.translate(options.centerX,options.centerY);
        ctx.rotate(options.angle);
        if (options.outlineThickness) ctx.lineWidth=options.outlineThickness;
        if (options.outlineColor) ctx.strokeStyle=options.outlineColor;
        ctx.moveTo(-len/2,-options.radius);
        for (var i=0; i<2*Math.PI; i+=ang) {
            ctx.rotate(ang);
            ctx.lineTo(len/2,-options.radius);
        }
        ctx.closePath();
        if (options.outlineThickness && options.outlineColor) ctx.stroke();
        ctx.clip();
        ctx.rotate(2*Math.PI-i-options.angle);
        ctx.translate(-options.centerX,-options.centerY);
        ctx.drawImage(this,0,0);
        options.success(ctx.canvas.toDataURL());
    };
    img.onerror=function() { alert('there was an error loading the image'); };
    img.src=options.url;
}

What it does it take your URL and the values of the cropped area and returns the data URL of the cropped image. You can see it in action here: https://jsfiddle.net/psrec1b5/2/


text:
Q: Working with XML POST requests in Zend Framework2 I'm new to Zend Framework 2 and I have to use a XML POST request to call a webservice.
I've gone through ZF2 documentation and found out that I can use the following.
Zend\DOM\Query  (to parse the xml respose)
Zend\Http\Client
Zend\XmlRpc\Client

My xml post request is a lengthy one. I can start this with Zend\Http\Client and what I can't understand is where to store the xml request? Is is convenient if I keep the xml data in the code itself or do I have to store the xml requst on another document and load the document when calling the webservice? Also I need to change the values of the parameters of the xml post request per webservice call.
What do I need to do? I think I've not grabbed the basics of XML POST requests. But I could not find a proper answer in the internet to resolve my issue.

A: If you're posting a large amount of XML data that is mostly the same each time, it might make sense to store it on the file system, but you could do it either way - do whatever makes the most sense for your app.
Although you can use DOM query to parse XML, you might want to look at simplexml, which is PHP's native XML parsing lib.


text:
Q: Are static classes and methods bad? Global variables frowned upon? I have an application that has database connectivity and although there are obviously objects that correspond to data in my database, I find that all my data processing methods could be static as there is no real need for an instance of the object as my classes simply operate on the data and spit something out, no need to store anything outside the method's scope. If I can make a method or class static should I?
Also I use a utility singleton class for common (single instance) "global data". I want to have a good design, but are these frowned upon?
Let me give you an example of what I'm doing. I load some data from my database using a static method to place it into a global varaiable in my Singleton class (a list of a custom object)
So my singleton class has something like
List<MyCustomObject> SomeList

and my static class has
static void LoadData()
foreach(data in database something or other)
singletonClass.SomeList.Add()

So the code above might load in some records from the database into SomeList, where each item in SomeList is of type MyCustomObject, which contains a single record of information.
Is this good implementation? Is this how you would code it?
Then in my presentation layer I would make calls to another static class of methods to get data from the singleton class in to a format required.
It doesn't feel very OOPey. But I can't really think how to do it another way you do it.

A: Allow me to direct you toward an excellent article on this topic: Singletons are Pathological Liars.
The problem is that the need to call your LoadData() function isn't self-evident. Compare your situation to that described in the article and I think you'll see some parallels.

A: Statics and singletons are frowned upon somewhat. But only the same way as starting a sentence with "but" — bad when overused, but sometimes it's what works best.
In your example, why have separate classes, one a singleton and one static? A singleton is in many ways equivalent to a class with only static data and methods. If you already have a singleton, I'd say you should add the methods to load the data to it rather than to a separate class. A class with static methods would be more appropriate if, say, you have utility code common to all of your stored data types.
(Also, I wouldn't worry too much about what's OOPey and what's not. Overengineering in the blind service of OOP principles can be a serious problem, speaking as someone who's had to wade through the Eclipse code base …)

A: Singletons is one but static is another very big one.
OOP or not, static variables have many drawbacks but little coding convenience.

*

*Can't determine exact allocation time, life span

*Can't work well in multi-threaded

*Future problem to program expansion

...


text:
Q: Does switchmap automatically calls the subscription? I am trying to obtain a behavior such that if current observable is changed in value, the respective observables linked should be invoked respectively.
The following code works as intended, but I just need some conformation regarding this behavior, I am trying to implement this on production site.
I know switchMap unsubscribes from current subscription and resubscribes to new one that's returned.
But, Does it also call the new observable subscribed to kick in and run the code it has or is this run by the pipe operator or am I missing any crucial concept ?
Can some one kindly, clarify this.
Thank you.
Here is the stackblitz code link ::: https://stackblitz.com/edit/rxjs-ktnf9x  :: and Overview
let a = new BehaviorSubject(null);
let b = new BehaviorSubject(null);
let c = new BehaviorSubject(null);
let d = new BehaviorSubject(null);

let a$ = a.asObservable();
let b$ = b.asObservable();
let c$ = c.asObservable();
let d$ = d.asObservable();

  d$
    .pipe(
      switchMap(
        data => {
          console.log("from d :: " + data);
          return c$;
        }
      )
    )
    .pipe(
      switchMap(
        data => {
          console.log("from c :: " + data);
          return b$;
        }
      )
    )
    .pipe(
      switchMap(
        data => {
          console.log("from b :: " + data);
          return a$;
        }
      )
    )
    .subscribe(
      data => {
        console.log("from a :: " + data);
        console.log(""); // for next line.
      }
    )

  b.next("calls");
  a.next("allSubs");

  c.next("it");
  d.next("does");

  d.next('yes');

finally --> Outputs ::: yes it calls allSubs

A: To make it simpler to explain. SwitchMap unsubscribe c$ when d$ emits. if d emit once and c keeps emitting you will get a sequence of d-c-c-c
if d emits again in the middle you will get d-c-c-c-d-c-c-c
 d$
    .pipe(
      switchMap(
        data => {
          console.log("from d :: " + data);
          return c$;
        }
      )
    )


text:
Q: Функция умножения с неопределенным количеством аргументов Есть необычная функция умножения:

function multiply(param) {
  this.tmp = this.tmp === undefined ? param : this.tmp * param;
  console.log('>', this.tmp);
  return multiply;
}

console.log(multiply(2)(10)(3)(6)); //2*10*3*6 = 360

И есть цепочка, (которая может быть длиной от 2 вызовов до скольки угодно)
console.log(multiply(2)(10)(3)(6));

по выполнении которой вернется [Function: multiply]. Но интересно, можно ли каким либо образом вернуть итоговое значение вместо функции?
Возможно есть какой-то вариант отловить, когда Multiply вызывается в последний раз, чтобы подменить return? Или существует какой-то другой подход к решению данной задачки?
Возможно задача надуманная, и не имеет за собой действительного решения

A: Попробуйте добавить вторым параметром функции счётчик $counter. Инкременируйте его сравнивайте с ним что вам нужно.

A: Если вы ходите использовать сколько угодно аргументов для функции, можно их не объявлять, но получать через arguments.
Пример умножения с n-ым количеством аргументов:

function multiply() {
  let args = [].slice.call(arguments);
  let sum = args.length ? args.reduce(((a, b) => a * b)) : null;
  return sum;
}

console.log(multiply(1, 2, 3, 4, 5));
console.log(multiply(-1, -2, 0.5, 100, 6));
console.log(multiply());

Как вы можете видеть, в функции мы не объявили ни одного аргумента, но получили их массив через arguments, число переданных аргументов может быть каким угодно.
Я думаю вы именно это решение ищите.

A: Недавно решал подобную задачу, только нужно было уметь еще передавать название метода объекта Math или свой callback
function calc(a) {
 const args = [];
 let sum = a;
 args.push(a);

 const func = (b) => {
   if (typeof b === 'function') {
    b.toString = () => b(args);
    return b;
   }

   if (typeof b === 'string') {
     Math[b].toString = () => Math[b](...args);
     return Math[b];
   }

   args.push(b);
   sum += b;

    return func;
 };

 func.toString = () => sum;

 return func;
}

Работало так:
calc(5)(12)((args) => {
  return args.reduce((sum, a) => {
    return sum + a;
  }, 0);
}); // вернет 17

Степень:
calc(5)(2)('pow'); // вернет 25

Живой пример на jsfiddle


text:
Q: Django filtering over a tsvector column My Django application has a backend postgres database with a tsvector column that whose values are already computed and indexed. I want to use Django's ORM to do a full text search over that column with a query that would look something like this:
SELECT [fields] FROM [table] WHERE tsvector_column @@ plainto_tsquery('TEXT HERE');

The problem I am running into is, when I use annotate and SearchVector, Django seems to re-to_tsvector over the tsvector column, resulting in an error.
This is what I am doing:
Posts.objects.annotate(search=SearchVector('THE_TS_VECTOR_COLUMN'),).filter(search='SEARCH TEXT')

How would one do this in Django?
Thanks!

A: Figured it out!
I used inspectdb to create the database model, so it guessed that the type was a TextField. I changed it to a SearchVectorField as follows:
from django.contrib.postgres.search import SearchVectorField

class CLASSNAME(models.Model):
    THE_TS_VECTOR_COLUMN = SearchVectorField(null=True)

Then I updated the query to this:
query = SearchQuery("TEXT TO SEARCH")
CLASSNAME.objects.annotate(rank=SearchVector(F('THE_TS_VECTOR_COLUMN'), query))

The resulting query was this:
SELECT [ALL FIELD VALUES] FROM "CLASSNAME" WHERE "CLASSNAME"."THE_TS_VECTOR_COLUMN" @@ (plainto_tsquery(TEXT TO SEARCH)) = true

And that's exactly what I wanted. Great!


text:
Q: How isolated are static variables? If I have a
public class SomeClass {
    public static final HashMap hashmap = new HashMap();
}

and then I have five different classes with main(String[] args) methods, that I will run.
when they access SomeClass.hashmap, would they be accessing the same HashMap or will they each have their own hashmap created in the JVM?

A: In general, for most of the available implementations of JVM, each of your 5 classes will get their own hashmap instances to call and use, because each new main thread will run in a new JVM. A new JVM is created if you use "java" command to run your program.
If you call these 5 main classes in 5 distinct threads from a tester class, they will be run as threads in the same JVM. In that case, they'll be using the same hashmap.
(https://stackoverflow.com/questions/18394560/when-multiple-java-programs-run-on-the-same-machine)
There are two more interesting scenarios where you can look at this question from - one if what if you are running your 5 main classes as separate programs on a server, and second is what if you are using a multitenancy supporting Java SDK.
In case of the application server, usually the same JVM and a new classloader will be used for each new program, so again, each main class gets its own hashmap. For the multitenant environment, the same hashmap gets shared (http://www.ibm.com/developerworks/library/j-multitenant-java/).

A: The answer is "each instance of the class within a different class loader is distinct."
If you have two different JVMs (you invoked java MainOne and java MainTwo), these are obviously different class loaders.  However, there are corner cases here with things such as nailgun which keeps the JVM running and... things get complex.
You also have situations such as when the application is launched from within an IDE. Some IDEs will spawn a new JVM for running the application, others could be launching a new class loader within their own JVM (I don't think any do this anymore as it made the IDE less than ideally stable). This can get very tricky too.
When running in within an application server environment, this can either be configurable, or you will need to check the specifications. However, realize that every possible combination is possible. You can have isolation of two modules within the same ear (each .war has its own class loader), you can the entire .ear share a class loader, you can have some funky compatibility mode where everything shares the .jar class loader, but is itself in an isolated class loader for the .war, or you can have the entire server use one class loader. Note that some application servers have changed how they work with different versions (JBoss prior to version 5 was not isolated, while after version 5 was, and 4.0.2 had a hierarchal class loader while 4.0.3 reverted to a unified class loader).  It's a mess.  And thus the awareness of "static is one per class loader" is key.
It is even possible to have different class loaders within a single application as demonstrated in run a executable jar file within java program using class loaders.
So, going back to the answer "each instance of the class within a different class loader is distinct" - and that can take many different forms and edge conditions.


text:
Q: Does logrotate handle wildcards the same as ls? I'd like to specify the files for logrotate to handle via the following wildcard string: /home/deploy/*/logs/nginx-*.log
If I do ls with this wildcard string, it shows exactly the files I want to be rotated. Will logrotate handle the wildcard string as expected, i.e. the same as with ls?

A: Yes it does see man logrotate, but note the warning:

Please use wildcards with caution.  If you specify *, logrotate will rotate all files, including previously rotated
         ones.  A way around this is to use the olddir directive or a more exact wildcard (such as *.log).


text:
Q: Fixpoint of $(Af)(x) = \int_0^x k(t)f(t)dt$ So let $X = C([0, 1])$ the space of continuous functions and let $\|f\|_{\infty} := \sup_{s \in[0,1]}|f(s)|$. Now we have the map $A:X \to X$ defined by
$$(Af)(x) = \int_0^x k(t)f(t)\,\mathrm{d}t$$
for $x \in [0, 1]$ and $k \in X$ such that $0 \leq k(x) \leq 1/2$.
We know that $A$ is linear, continuous and a contraction. Therefore by the Banach fixed-point theorem it has an unique fixpoint. Now I want to find $f^*$ with $(Af^*)(x) = f^*(x)$. How do I do that?
I tried $f^* = e^{\int k(x)}$. Therefore $$(Af^*)(x) = e^{\int k(x)} - e^{\int k(0)}$$
It looks close, but still not it..

A: Some times it's easier than you think. The fixed point is the zero function. The big hint is that $A$ is linear, which makes $0$ a fixed point regardless of contractivity.


text:
Q: Python string extraction In the following string how to get the id after the directory media and after getting the id ignore the rest of the string to read only the id numbers
id_arr= ["/opt/media/12/htmls","/opt/media/24/htmls","/opt/media/26/htmls","/opt/media/56/htmls"]

The output should be 12 24 26 56

A: If the strings always look the way you said, try
ids = [int(s.split("/")[3]) for s in id_arr]

A: >>> import re
>>> myre = re.compile("^.*/media/(\d+)")
>>> for item in id_arr:
...     print (myre.search(item).group(1))
...
12
24
26
56

A: [x.split('/')[3] for x in id_arr]

A: parts = "/opt/media/12/htmls","/opt/media/24/htmls","/opt/media/26/htmls","/opt/media/56/htmls"
for str in parts:
    print str.split("/")[3]

EDIT: unuseful rpartition() removed

A: The correct way probably involves some clever use of the os.path module, but for the input given, just use a regex for media\/([0-9]+) and extract the first group.


text:
Q: Sed/grep results into formatted excel file I'm looking for a way to output the results of my sed/grep query into an excel file where it detects the use of columns.
So, I'm using the following
sed '/b[A-Za-z0-9._%]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/b' pool.txt | egrep "example" > names.xls

Which gives the following
test.123@example.com    FirstName LastName

What would be the best method for throwing this into an excel file with 2 columns for email | name?


text:
Q: JQuery wait until ToggleClass function completed I am using ToggleClass to trigger an animation from css and need to call a function after the animation has ended.
I'm calling a function from the typed.js library.
 $('.anim').toggleClass('slide-down');
      $(".sentence").typed({
        strings: ["first sentence", "Second sentence." ],
        typeSpeed: 45,
        backDelay: 500,
        callback: function(){}
});

how can I make the typed function wait till the toggleClass has finished?

A: You can wait for the animationend event
$('.anim').toggleClass('slide-down').one('animationend', function () {
    $(".sentence").typed({
        strings: ["first sentence", "Second sentence."],
        typeSpeed: 45,
        backDelay: 500,
        callback: function () {}
    });
});

Or if you are using transition, then use transitionend
Demo: Fiddle


text: Q: Wrong number of data values in record I have some tab delimited files that I am importing from a folder using SQL Assistant. These files each have more than 200 thousand records, when I try to insert them, I get the error message 'Wrong number of data values in record', I have tried importing 10,000 at a time and they insert. Is there a way I can insert a whole file with over 200 thousand records?


text:
Q: return NA via RCpp Newbie RCpp question here: how can I make a NumericVector return NA to R?  For example, suppose I have a RCpp code that assigns NA to the first element of a vector.
// [[RCpp::export]]
NumericVector myFunc(NumericVector x) {
   NumericVector y=clone(x);
   y[0]=NA; // <----- what's the right expression here?
   return y;
}

A: The canonical way to get the correct NA for a given vector type (NumericVector, IntegerVector, ...)  is to use the static get_na method. Something like:
y[0] = NumericVector::get_na() ;

FWIW, your code works as is with Rcpp11, which knows how to convert from the static Na_Proxy  instance NA into the correct missing value for the target type.

A: Please at least try to grep through the large corpus of examples provided by our regression tests:
edd@max:~$ cd  /usr/local/lib/R/site-library/Rcpp/unitTests/cpp/
edd@max:/usr/local/lib/R/site-library/Rcpp/unitTests/cpp$ grep NA *cpp | tail -5
support.cpp:           Rf_pentagamma( NA_REAL) ,
support.cpp:           expm1( NA_REAL ),
support.cpp:           log1p( NA_REAL ),
support.cpp:           Rcpp::internal::factorial( NA_REAL ),
support.cpp:           Rcpp::internal::lfactorial( NA_REAL )
edd@max:/usr/local/lib/R/site-library/Rcpp/unitTests/cpp$

Moreover, this is actually a C question for R and answered in the Writing R Extensions manual.
You could also have found a good example in this Rcpp Gallery post as well as others; there is a search function right at the Rcpp Gallery.