text:
Q: problem with double scripting, because of speed reasons, awk verse bash builtin I have a lot of bash functions, which contain a bash builtin code and the same code rewritten in awk code. I want to get rid off this.
I use the bash builtin for short strings, and awk for long strings, so a lot of my
functions have a boolean for length type. (0) for short strings (bash builtin), (1) for long strings (awk).
For short strings bash builtin is faster.
I want to give an example:
the g_SO_formatText_width function, which formats a text according to overhanded columns width by break words or try to keep words unbroken, depending on boolean.
In the text there also could be font tags like <b:u:color 255;123:120> , which is filtered out and not relevant for the data text and calculations on it , where to break words. the font tags are converted to ANSI escape codes by a other function.
this function only formats the text
#!/bin/bash
            declare g_RV="" g_ESC=$'\x1b'; declare -i g_tabSpaces="8"

            #-- call:        g_SO_formatText_width [text STR] [max columns INT] [length type bINT] [word wrap bINT] [text type bINT]
            #-- description: formats the text appearance, so that the text appears with a max columns width, either with breaking words or trying to keep words unbroken
            #--              word splitting is used! use set -o noglob to prohibit that data characters * ? [] are recognized as file patterns, or even more characters, if extented glob is on.
            #-- parameters:  $1 ... text STR - text to format
            #--              $2 ... max columns INT - max columns should be lower than terminal columns, to see an effect
            #--              $3 ... length type bINT optional - faster for short strings (0), faster for long strings with awk (1) - Standard:0
            #--              $4 ... word wrap bINT optional - try to keep word unbroken (0), break word (1), Standard:0
            #--              $5 ... text type bINT optional - normal text (0), FSS Font Style Simple text (1)
            #-- returnValue: written to g_RV - STR .. the formatted text
            #-- depends on:  variables - g_RV, g_ESC, g_tabSpaces;
            function g_SO_formatText_width ()
                {
                if [[ $2 -eq 0 ]];then return 1; fi
                #-- bash builtins
                if [[ $3 -eq 0 ]]; then
                    local -a dataText_ARR=() formatText_ARR=()
                    #-- text     ... complete text overhanded - which can contain format strings (text)
                    #-- dataText ... the data of the text without format strings
                    #-- iline    ... input line - a line of dataText separated with \n
                    #-- oline    ... output line - a calculated line of text on screen according to columns limit and respecting \n in source text
                    local text dataText iline oline output=""

                    #-- iline_SIndex ... input line startIndex, for reading characters
                    #-- iline_l oline_l  ... iline oline length
                    #-- oline_dl ... length difference, between two different oline lengths (oline is shortened to last space)
                    local -i i oline_aChars=$2 iline_SIndex iline_l oline_l oline_dl

                    #-- \t becomes \n\t - so tabulator appears only at first place of a new line, making calculation of tab action easier
                    text=${1//$'\t'/$'\n\t'}

                    #-- FSS text
                    if [[ $5 -eq 1 ]]; then
                        local textPart savIFS=$IFS
                        dataText_ARR[0]=${text%%"$g_ESC"*}

                        IFS=$g_ESC; i=0; for textPart in ${text:${#dataText_ARR[0]}+1}
                            do
                            formatText_ARR[i]=${textPart%%>*}">"
                            dataText_ARR[i+1]=${textPart:${#formatText_ARR[i]}}
                            ((i++))
                            done
                        IFS=$savIFS

                    #-- normal text
                    else dataText_ARR[0]=$text; formatText_ARR[0]=""
                    fi

                    for i in ${!dataText_ARR[*]}
                        do
                        dataText=${dataText_ARR[$i]}

                        while true
                            do
                            #-- search for first input line
                            iline=${dataText%%$'\n'*}
                            iline_l=${#iline}

                            #-- subtract line characters from columns limit, if <0 line too big!
                            ((oline_aChars-=iline_l, iline_SIndex=0))

                            #-- if input line too big, then split it to output lines with allowed columns amount separated by \n,
                            #-- loop breaks, when the rest of the input line is small enough to suit in one output line, that's the case, when oLine_aChars>=0
                            #-- case: try to keep word unbroken
                            if [[ $4 -eq 0 ]]; then
                                while ((oline_aChars<0))
                                    do
                                    oline=${iline:iline_SIndex:oline_aChars}
                                    if [[ ${iline:oline_aChars-1:2} == [^$' ,;'][^$' '] ]]; then
                                        oline_l=${#oline}; oline=${oline% *}; ((oline_dl= ${#oline}-oline_l))
                                        if ((oline_dl<0)); then oline+=" "; fi
                                        ((oline_aChars+=oline_dl+1))
                                    fi
                                    output+=$oline$'\n'
                                    ((iline_SIndex=oline_aChars,oline_aChars+=$2))
                                    done
                            #-- case: break word
                            else
                                while ((oline_aChars<0))
                                    do
                                    oline=${iline:iline_SIndex:oline_aChars}
                                    output+=$oline$'\n'
                                    ((iline_SIndex=oline_aChars,oline_aChars+=$2))
                                    done
                            fi
                            #-- if iline is (now) not too big, simply add it to output
                            output+=${iline:iline_SIndex}

                            #-- check if next line exists
                            if (($iline_l<${#dataText})); then
                                #--shorten dataText by cutting out the acutal input line
                                dataText=${dataText:$iline_l+1};
                                #-- Tabulator sign recognition - check if first character of a theoretical new line is tab sign
                                #-- if so prohibit new line!
                                if [[ ${dataText:0:1} == $'\t' ]]; then
                                    #-- calculate the amount of spaces the tab sign causes according to its position in the line
                                    #-- with oline_aChars and max columns $2 get the actual position - with g_tabSpaces, calculate the amount of spaces
                                    ((oline_aChars-=g_tabSpaces-1-($2-oline_aChars)%g_tabSpaces));
                                    #-- if oline gets below zero, when subtracting the amount of spaces, tab would cause
                                    #-- then it moves to beginning of new line, so add \n reset oline_aChars to max columns
                                    if ((oline_aChars<0)); then
                                        dataText=${dataText:1}
                                        output+=$'\n'; oline_aChars=$2
                                    fi
                                #-- close iline with \n and reset oline_aChars for new line
                                else output+=$'\n'; oline_aChars=$2; fi
                                if ((${#dataText}==0)); then break; fi
                            else break; fi
                            done

                        output+=${formatText_ARR[$i]};
                        done
                    g_RV="$output"
                #-- awk
                else
                    #-- awk script begin
                    g_RV=$(awk \
            '   BEGIN {textType='"$5"'; wordWrap='"$4"'; tabSpaces='"$g_tabSpaces"'; maxColumns='"$2"'; if (textType) RS="'"$g_ESC"'"; else RS="\x00"; oline_aChars=maxColumns; i=0 }
                {gsub(/\t/,"\n\t"); if (i) {indexGT=index($0,">"); dataText_ARR[i]=substr($0,indexGT+1); formatText_ARR[i-1]=substr($0,1,indexGT);} else dataText_ARR[0]=$0 ;i++ }
                END {
                    for (i in dataText_ARR) {
                        dataText=dataText_ARR[i];
                        while (1) {
                            indexNL=index(dataText,"\n"); if (!indexNL) indexNL=length(dataText)+1;
                            iline=substr(dataText,1,indexNL-1); iline_l=length(iline);
                            oline_aChars-=iline_l; iline_SIndex=1;
                            oline_l=iline_l+oline_aChars;

                            if (wordWrap) {
                                while (oline_aChars<0)  {
                                    oline=substr(iline,iline_SIndex,oline_l); printf "%s",oline "\n";
                                    iline_SIndex+=oline_l; oline_l=maxColumns; oline_aChars+=maxColumns;}}
                            else {
                                while (oline_aChars<0) {
                                    oline=substr(iline,iline_SIndex,oline_l);
                                    if (match(substr(iline,iline_SIndex+oline_l-1,2),/[^ ,;][^ ]/)) {
                                        if (match(oline,/.* /)) oline=substr(oline,1,RLENGTH);
                                        oline_aChars+=RLENGTH-oline_l; oline_l=RLENGTH; }
                                    printf "%s" , oline "\n";
                                    iline_SIndex+=oline_l; oline_l=maxColumns; oline_aChars+=maxColumns}}

                            printf "%s",substr(iline,iline_SIndex);
                            if (iline_l<length(dataText)) {
                                dataText=substr(dataText,iline_l+2);
                                if (substr(dataText,1,1) == "\t") {
                                    oline_aChars-=tabSpaces-1-(maxColumns-oline_aChars)%tabSpaces;\
                                    if ((oline_aChars<0)) {
                                        dataText=substr(dataText,2);
                                        printf "%s","\n"; oline_aChars=maxColumns; }}
                                else {printf "%s","\n"; oline_aChars=maxColumns; }
                                if (length(dataText)==0) break; }
                            else break; }
                        printf "%s",formatText_ARR[i]; }}' <<< $1;)
                    #-- awk script end
                    fi
                }

you see nearly the same code, doubled in one function.
here a test function, which can be added to the code above
            #-- $1 amount of 'Hello World ' in text, $2 columns where to break word
            function helloWorld_test
                {
                for ((i=0;i<$1; i++)); do text+="Hello World "; done

                #g_SO_formatText_width [text STR] [max columns INT] [length type bINT] [word wrap bINT] [text type bINT]
                echo -e "\nbash builtin: $1"
                time g_SO_formatText_width "$text" $2 0 0 0
                echo -e "\nawk script: $1"
                time g_SO_formatText_width "$text" $2 1 0 0
                echo -e "\n$g_RV";
                }

            helloWorld_test 10 70
            helloWorld_test 50 70
            helloWorld_test 80 70
            helloWorld_test 100 70
            helloWorld_test 1000 70

for formatting 50 "Hello World"'s i get
bash builtin: 50
real    0m0,001s
user    0m0,000s
sys 0m0,001s
awk script: 50
real    0m0,003s
user    0m0,001s
sys 0m0,002s
for formatting 80 "hello world "s i get
bash builtin: 80
real    0m0,002s
user    0m0,000s
sys 0m0,002s
awk script: 80
real    0m0,003s
user    0m0,003s
sys 0m0,000s
so let's say 3ms difference on short text, that#s not much but doing a lot of conversion, the difference would grow.
I'm a Linux beginner,
I think the file awk has over 700kb, and every time i call the command in bash it will be loaded to memory and then the script has to be read in and evaluted.
I think the problem is the loading, is that right.
is there a command, with which i could keep awk in memory over the time and only overhand the script to it, or how could i increase the speed of awk, to get rid off this bash builtins code.
I'm still wondering, why bash is so slow on text manipulations. There are no typed variables like boolean, double float, int32 and so on. its all about strings.


text:
Q: Laravel Eloquent union models from relationsships I have a user who can have meetings from different relationships.He can be directly assigned to a meeting with one too many relationships, he can have user groups with many too many relationships that can have meetings with many too many relationships, and he can be responsible for a meeting with a relationship of one to many.
I want to get all meetings for one user. I don't want to merge the collections because I want to be able to use features like where directly in the database. My attempt is to merge all meeting ids and then get the meetings via 'whereIn'.
$ids = $this->meetings()->select('meetings.id')
    ->union($this->meetingsFromGroups()->select('meetings.id'))
    ->union($this->responsibleMeetings()->select('meetings.id'));

return Meeting::whereIn('id', $ids)->get();

When I execute this, I get this error:

"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'union (select `meetings`.`id` from `meetings` inner join `meeting_user_group` on' at line 1 (SQL:...)"
The SQL that is executed:

select *
from `meetings`
where `id` in (
        (
            select `meetings`.`id`
            from `meetings`
                inner join `meeting_user` on `meetings`.`id` = `meeting_user`.`meeting_id`
            where `meeting_user`.`user_id` = 1
        )
        union
        (
            select `meetings`.`id`
            from `meetings`
                inner join `meeting_user_group` on `meeting_user_group`.`meeting_id` = `meetings`.`id`
                inner join `user_groups` on `user_groups`.`id` = `meeting_user_group`.`user_group_id`
                inner join `user_user_group` on `user_user_group`.`user_group_id` = `user_groups`.`id`
            where `user_user_group`.`user_id` = 1
        )
        union
        (
            select `meetings`.`id`
            from `meetings`
            where `meetings`.`responsible_id` = 1
                and `meetings`.`responsible_id` is not null
        )
    )

The relations:
    public function responsibleMeetings(): HasMany {
        return $this->hasMany(Meeting::class, 'responsible_id');
    }

    public function meetings(): BelongsToMany {
        return $this->belongsToMany(Meeting::class)->withTimestamps();
    }

    public function meetingsFromGroups(): HasManyDeep {
        return $this->hasManyDeepFromRelations($this->userGroups(), (new UserGroup())->meetings());
    }

I'm using the package Staudenmeir\EloquentHasManyDeep for meetingsFromGroups.
I can't use union on the whole meeting, because then I would get

SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns

because of the pivot fields.
How would the SQL have to change for it to work, and how can I do that with Eloquent?

A: By default whereIn expects array to perform IN() clause on array items but in your case your are sending a union query which is why it is throwing error.
$ids = $this->meetings()->select('meetings.id')
    ->union($this->meetingsFromGroups()->select('meetings.id'))
    ->union($this->responsibleMeetings()->select('meetings.id'))
    ->pluck('id')->all();

return Meeting::whereIn('id', $ids)->get();

Additionally whereIn accepts a closure method also but not sure how would you call these relateables $this->meetings() ,$this->meetingsFromGroups() & $this->responsibleMeetings()  inside closure
return Meeting::whereIn('id', function($query){
    $query->select('...')
    ...;
})->get();

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to stretch list text to fill webpage my webpage
In the link above I have a list where I specify cities of service, and right now the list seems to be condensed. I tried to stretch it out using the font-stretch function using in-line CSS but it doesn't seem to be working. Are there any other ideas anyone has?

Serving the Greater Twin Cities Area

            <div class="col-md-2 col-sm-4 col-

Minneapolis and suburbs 10 minutes in any direction

St. Paul and suburbs 10 minutes in any direction

            <div class="col-md-2 col-sm-4 col-

A: You could widen the div instead. I tried out the code on my computer. The website displayed a bit differently, but this seemed to help.
div#navigation {width: XXXpx; }


text:
Q: iOS AVAudioSession interruption notification not working as expected I want to know when my AVAudioRecorder is inaccessible (e.g when music starts playing).
As audioRecorderEndInterruption will be deprecated with iOS 9 I am focusing on AVAudioSession's interruption notification (but neither is working as expected).
The issue is that the interruption notification is never called if the app was and remains in the foreground when the interruption occurs.
E.g: The user starts and stops playing music without moving the application into the background.
To detect any interruptions I am using:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionWasInterrupted:) name:AVAudioSessionInterruptionNotification object:nil];
...
- (void)audioSessionWasInterrupted:(NSNotification *)notification {
    if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) {
        NSLog(@"Interruption notification");

        if ([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] isEqualToNumber:[NSNumber numberWithInt:AVAudioSessionInterruptionTypeBegan]]) {
            NSLog(@"InterruptionTypeBegan");
        } else {
            NSLog(@"InterruptionTypeEnded");
        }
    }
}

I get InterruptionTypeBegan as expected, but InterruptionTypeEnded isn't called if the app is still in the foreground (meaning it won't be called until the app is placed in the background and back into the foreground).
How may I receive InterruptionTypeEnded notification when the interruption occurs while the app is in the foreground?

A: This is a widespread problem affecting any app using AV framework components (the same goes for native iOS apps).
As explained in 's documentation on the subject of audio interruptions, the InterruptionTypeEnded should actually be applied in the scenario mentioned:

If the user dismisses the interruption ... the system invokes your callback method, indicating that the interruption has ended.

However, it also states that the InterruptionTypeEnded might not be called at all:

There is no guarantee that a begin interruption will have an end interruption.

Therefore, a different approach is needed in the scenario mentioned.

When it comes to handling music interruptions, the issue won't be around for long. iOS 9 effectively prevents outside audio sources to be used while the app's audio handler is invoked.
A way to handle the exact issue of media interruption could be to listen to MPMusicPlayerController's playbackState, as shown in this stackoverflow question: Detecting if music is playing?.

A more direct way to handle the issue of interruptions would be to either:
Block outside audio interruptions completely by re-invoking your audio component at the time of InterruptionTypeBegan.
Or by giving a UI indication that an outside media source has interrupted the audio session (for example showing an inactive microphone).

Hopefully  will come up with a better solution to the problem, but in the meantime this should give you some options to solve the interruption issue.

A: If you haven't already, try setting your AVCaptureSession's property usesApplicationAudioSession to NO.
This question & answer may act as a good reference if you're looking for any more detail.

A: I try this and find InterruptionTypeEnded may called after music pause in some app, but other not called when pause.
My solution is update the UI to let user know record has stopped and do some related work such as file operation. When interruption ends, active AVAudioSession, if doesn't have error, start a new record.
If you want to join the file before and after interrupt, the answer to this question: AVAudioRecorder records only the audio after interruption may be helpful to you.


text:
Q: Changing displayed state of Views based on a parent ViewGroup's state I have a compound UI component built up from a ViewGroup containing a number of TextView, ImageView etc. components. Many of these have StateListDrawables as their images/backgrounds. Is there any way of making them select from this drawable based on the state of the parent ViewGroup rather than the component itself? Ideally I want to be able to change the visual state of all children of the ViewGroup (text colour, image etc) based on the state of the ViewGroup, preferably without having to hook up complex logical code. This seems like a fairly common sort of requirement, so I was hoping it would be straightforward in Android - am I going to be disappointed? :)

A: No disappointment, just set android:duplicateParentState="true" in the layout file to enable what you want. You have to do that for each child View you want to have this functionality enabled on.


text:
Q: Quando utilizar linhas em branco em um programa Python? Pular linhas é um dos aspectos que tornam um programa bem indentado? Se sim, qual o critério utilizado para pular linhas?

A: Python possui um guia de estilos que é muito utilizado pela comunidade e nela há uma seção sobre linhas em branco no código: PEP 8 -- Style Guide for Python Code: Blank Lines. Abaixo citarei o texto original, em inglês, e comentarei logo mais abaixo.

Surround top-level function and class definitions with two blank lines.

Cercar definições de funções de nível superior e classes com dois espaços em branco. Ou seja, sempre que for definir uma nova função de nível superior ou uma classe, deixe um espaçamento de duas linhas.
import json

def stringify(obj):
    return json.loads(obj)

def show(string):
    print(string)

class Person:

    def __init__(self, name):
        self.name = name

Method definitions inside a class are surrounded by a single blank line.

Sempre que definir um novo método em uma classe, deixe um espaçamento de uma linha em torno do mesmo.
class Person:

    def __init__(self, name):
        self.name = name

    def walk(distance):
        ...

    def speak(text):
        ...

Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

Linhas em branco podem ser utilizadas (com moderação) para separar grupos de funções relacionadas e podem ser omitidas entre várias declarações de uma linha. Atribuição de variáveis, atributos em um objeto, definições de estruturas lambdas, etc, são, geralmente, estruturas de uma linha e, neste caso, a linha em branco pode ser omitida.
x = 1
y = 2
z = 3

distance = lambda x, y, z: x + y + z
square = lambda x: x**2

Use blank lines in functions, sparingly, to indicate logical sections.

Use linhas em branco em funções, com moderação, para separar seções lógicas. Por exemplo, atribuição de variáveis, validação, etc.
def status(age):

    output = "baby"  # atribuição

    if age < 0:  # validação
        raise Exception("The age must be a non-negative number")

    if 2 < age < 18:  # lógica
        output = "young"
    elif age < 60:
        output = "adult"
    else:
        output = "old"

    return output  # retorno

Em qualquer outro caso não citado fica completamente a seu critério. Na verdade, isso são só recomendações, você não precisa obrigatoriamente seguí-las. Se seguir, seu código será melhor recebido pela comunidade, pois será muito mais fácil entendê-lo.

A: Indentar é o recuo do texto em relação a sua margem, ou seja, se antes de escrevermos uma instrução, utilizamo 4 espaçamentos da margem esquerda até a instrução propriamente dita, podemos dizer que a indentação utilizada possui 4 espaços.
#coding: utf-8

print(nivel 1)#primeiro nível hierárquico

if(True):
    print(nível 2)#segundo nível hierárquico

Mais informações: http://excript.com/python/indentacao-python.html

A: Python Enhancement Proposal
Essas são documentos de design mantidos pela comunidade Python e mantidos no GitHub que definem guidelines para melhor utilização da linguagem e seus recursos. Essas definições são bem argumentadas, definem um postulado e o embasam com as justificativas da adoção desse documento. Elas são numeradas, então é comum ler PEP 1, PEP 5, PEP 8 ou PEP 500.

*

*python.org: "What is a PEP?" (direto da PEP 1)

Uma das PEPs ditas essenciais a leitura do programador Python é a oitava. A PEP 8 é um guia de estilização de código. Minha resposta foi formulada em cima dessa PEP, que é uma documentação de alta credibilidade.
Nessa PEP também foram definidas guidelines da indentação de código Python.
Quantos espaços ao indentar?
É sintaticamente obrigatório que você indente o seu código Python. A PEP diz para que você utilize quatro espaços por nível de indentação.
print("olá")
if foo:
    # quatro espaços

Tabs e/ou espaços
Espaços são preferíveis. Tenha consistência: se fizer com tabs, faça TUDO com tabulações. O contrário também é válido. O Python 3 nem permite que você misture tabulações e espaços, assim você terá:
TabError: inconsistent use of tabs and spaces in indentation

Linhas de continuação de código (hanging indentation)
Hanging indentation é quando todas as linhas do parágrafo estão indentadas menos a primeira.
Faça:
# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

Não faça:
# Arguments on first line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
    var_three, var_four)

A guideline dos quatro espaços é opcional nesse tipo de indentação. Pode fazer:
foo = long_function_name(
  var_one, var_two,
  var_three, var_four)

Limite qualquer linha de código a 79 caracteres. Para onde não há jeito, utilize o caractere de escape assim:
with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

Quebras de linha
A PEP 8 diz que você deve ter duas linhas em branco entre os statements de import e o restante do código.
import x
import y
import z

def foo()
    pass

E duas quebras entre cada função definida.
def a()
    pass

def b()
    pass

Outra PEP que diz sobre quebras de linha é a PEP 257, que define convenções de documentação de código Python. Lá diz:

There's no blank line either before or after the docstring.

Portanto, faça isso:
def alo():
    """Retorna um alô"""
    return 'alô'

São muitas recomendações definidas nessa PEP. Existe uma ferramenta para verificar se seu código está dentro da PEP 8, baseado no pep8.py. Veja PEP8 online check.


text:
Q: Is Syncing Photos with the Google Photos API a possibility? On the home page for Google Photos APIs, it indicates you can "Keep in sync with new content":

However, looking at the documentation, I don't see an obvious way to do this. I'm wanting to build an API that one-way syncs ALL photos from Google Photos to another destination. Is this possible?


text:
Q: How do I model data for a chat app use case? Quite new to Cassandra here. As the title depicts, I am trying to create a table with the following schema for a chat use case,

*

*chat_id - uuid primary key

*sender - text

*topic - text

*content - map<text,text>

*timestamp - timestamp

*status_id - int

These are the following query that I would be using

*

*INSERT .....

*Filter data with topic and it should be filtered - SELECT

*Update content based on topic - UPDATE

I have tried defining the primary keys but not able to execute these queries hence ended up with different Create table queries.
I would like to know the perfect CREATE TABLE query which supports these queries.
Thanks

A:
...hence ended up with different Create table queries...

What did you end up with?
The main caveat to understand this is to figure out the access patterns in advance, primarily the SELECT queries, equality & range predicates, etc., so that you could better design the data model.

Filter data with topic and it should be filtered - SELECT

need to be elaborated. See this data modeling by example course & CQL Data modeling concepts to better understand the concept in depth.
More here:

*

*Understanding the primary key

*Deep look into the WHERE clause

*Cassandra Fundamentals

Without knowing the in-depth access patterns required in your application, here is a bruteforce table schema that would satisfy the below queries:
CREATE TABLE IF NOT EXISTS <<your_keyspace_name>>.chat_app_tbl (
 sender TEXT,
 topic TEXT,
 chat_id UUID,
 status_id INT,
 col_timestamp TIMESTAMP,
 content MAP<TEXT,TEXT>,
 PRIMARY KEY((topic,sender),chat_id,col_timestamp)
) WITH CLUSTERING ORDER BY (chat_id DESC, col_timestamp DESC);

and it can satisfy queries such as below:
Inserting data:
insert into chat_app_tbl(sender,topic,chat_id,status_id,col_timestamp,content) Values ('sender','sports',now(),0,totimestamp(now()),{'cricket':'India'});

Querying data based on a given topic and sender:
token@cqlsh:curatedns> select * From chat_app_tbl where topic = 'sports' and sender = 'sender';

 topic  | sender | chat_id                              | col_timestamp                   | content              | status_id
--------+--------+--------------------------------------+---------------------------------+----------------------+-----------
 sports | sender | 3f72b6d0-ad43-11ed-be31-7952b3260293 | 2023-02-15 15:13:05.725000+0000 | {'cricket': 'India'} |         0

(1 rows)

you will not be able to update the data without providing the other primary key (partition + clustering) fields/columns you will get the following error if you try to do so:
token@cqlsh:curatedns> UPDATE chat_app_tbl SET status_id = 1 WHERE topic = 'sports' AND sender = 'sender';
InvalidRequest: Error from server: code=2200 [Invalid query] message="Some clustering keys are missing: chat_id, col_timestamp"

whereas, you could perform updates to the data using queries such as below:
UPDATE chat_app_tbl SET status_id = 5 WHERE topic = 'sports' AND sender = 'sender' AND chat_id = 3f72b6d0-ad43-11ed-be31-7952b3260293 AND col_timestamp = '2023-02-15 15:13:05.725';

which would give us,
token@cqlsh:curatedns> select * From chat_app_tbl where topic = 'sports' and sender = 'sender';
 topic  | sender | chat_id                              | col_timestamp                   | content              | status_id
--------+--------+--------------------------------------+---------------------------------+----------------------+-----------
 sports | sender | 3f72b6d0-ad43-11ed-be31-7952b3260293 | 2023-02-15 15:13:05.725000+0000 | {'cricket': 'India'} |         5

and these below will insert a new row by doing an upsert:
UPDATE chat_app_tbl SET status_id = 1 WHERE topic = 'sports' AND sender = 'sender' AND chat_id = 3f72b6d0-ad43-11ed-be31-7952b3260293 AND col_timestamp = '2023-02-15T15:13:05'; <<<-- remember this would add a new row by performing an upsert

(or)
UPDATE chat_app_tbl SET status_id = 1 WHERE topic = 'sports' AND sender = 'sender' AND chat_id = 3f72b6d0-ad43-11ed-be31-7952b3260293 AND col_timestamp = '2023-02-15'; <<<-- remember this would add a new row by performing an upsert

If you ask me if the above is a good data model? The answer would be "it depends". Why?

*

*Having just the topics as the partition column would definitely be a bad idea, because for a given topic, (i.e. sports in our example) there could be a variety of discussions and you'll end up with a FAT / BIG / HUGE partition. See this blog or this learning exercise to understand how partitioning works under the covers.

*The general idea for a partition size in Cassandra is to have it less than 50-100MB for scale & throughput.

*The current (topic, sender) partition key may not even be sufficient to break down the partition size to keep under the limits, in some cases.

You may be able to play with different partitioning strategis like,

*

*PRIMARY KEY((topic, sender), chat_id, col_timestamp) (or)

*PRIMARY KEY((topic, sender), chat_id) (or)

*etc.,

to find out which would suite your case and offer the scale. There is a great tool called NoSQLBench where you could test/benchmark your table & queries with which you could emulate real-world application workloads and test your data model. More details here.

A: Data modelling in Cassandra means that you need to design a table for each application query so that reads are optimised.
If your app needs to retrieve conversations by topic then the table needs to be partitioned by topic. Additionally given it is a chat application, I imagine you would want to sort the messages in reverse chronological order based on when it was posted so the table would look something like this:
CREATE TABLE messages_by_topic (
    topic text,
    posted_tstamp timestamp,
    sender text,
    message text,
    PRIMARY KEY (topic, posted_tstamp)
) WITH CLUSTERING ORDER BY (tstamp DESCENDING)

To retrieve the last 20 messages for a topic:
SELECT sender, message, posted_tstamp
FROM messages_by_topic
WHERE topic = ?
LIMIT 20

To post a new message to a topic:
INSERT INTO messages_by_topic (topic)
VALUES (?, ?, ?, ?)

In your case using the chat ID as the partition key is not going to be helpful since your app does not query based on it. Cheers!


text:
Q: Html5 Border-Radius Reverse Fill I want to achieve drop-down button as per following design image. See drop-down menu starts just after middle of button. My problem is that button has transparent background to utilize background image from root parent div.

So far I have achieved following image. As I said above, I want to achieve white edges outside of border-radius.

    .dropdown-header {
      border-top-left-radius: 20px;
      border-top-right-radius: 20px;
      width: 210px;
      height: 185px;
      margin: auto;
    }

    .div-user-header {
      width: 210px;
      margin: auto;
      position: relative;

      border-top-left-radius: 20px;
      border-top-right-radius: 20px;

    }

    .div-user-header-1 {
      width: 206px;
      height: 24px;
      border: 2px solid #9CB2C7;
      border-radius: 20px;
      display: inline-block;
      text-align: center;
      padding-top: 5px;

    }

    .div-user-header-1 a {
      text-decoration: none;
      color: #FCCC00;
      display: block;

    }

    .div-user-header-list {
      position: absolute;
      background-color: white;
      height: 170px;
      width: 210px;

    }

    .div-user-header-2 a {
      text-decoration: none;
      font-size: 12px;
      color: #8C8C8C;
    }

    .div-user-header-2 {
      height: 40px;
      padding: 12px 15px;

    }

    .div-user-header-3 a {
      text-decoration: none;
      font-size: 12px;
      color: #8C8C8C;
    }

    .div-user-header-3 {
      height: 40px;
      padding: 12px 15px;

    }

    .div-add-profile-card {

      padding: 0px 15px;
    }

    .div-add-profile-card a {
      text-decoration: none;
      color: #8C8C8C;
      font-size: 10px;
      padding: 12px;
      display: block;
      border-top: 1px solid #D6D6D6;
    }

            ProfileUser 01

              ProfileUser 01

              ProfileUser 02

               + Add Profile Cards

Any suggestion would be really helpful.

A:
Use ::after ::before pseudo elements for the dropdown and apply separate background-image as marked in the image. Apply position:absolute and align then in the top left and right corners based on the design.

A: It's very simple. You have achieved almost 99%. Just add below styles to your CSS of .div-user-header-list as below:
.div-user-header-list {
    position: absolute;
    background-color: white;
    height: 170px;
    width: 210px;
    padding-top: 20px;
    margin-top: -20px;
    z-index: -1;
}

See the updated fiddle here: https://jsfiddle.net/8ukj3wy1/1/

A: Check this one out:

https://jsfiddle.net/sLy7fnzg/
Essentially use a negative margin to move the .div-user-header-list up and use relative positioning to enable z-indexes.
Also, to resolve the issue with the half border, remove the border from the .div-user-header-1 and add a whole element as a ::before to the .div-user-header like so:
.div-user-header::before {
    content: "";
    background: #9CB2C7;
    width: 210px;
    height: 30px;
    display:block;
    position: absolute;
    top: 0;
    left: 0;
    border-radius: 20px;
    z-index: 1;
}

A:

    <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Varela+Round" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

            ProfileUser 01

              ProfileUser 01

              ProfileUser 02

               + Add Profile Cards


text:
Q: String cannot be converted to JSONObject for a registration page i am trying to make a registration page, and i have completed the xml page and i have written the activity java file
here is the code
public class RegisterActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    final EditText etUserName = (EditText) findViewById(R.id.etUserName);
    final EditText etUserEmail = (EditText) findViewById(R.id.etUserEmail);
    final EditText etUserContactNo = (EditText) findViewById(R.id.etUserContactNo);
    final EditText etUserPassword = (EditText) findViewById(R.id.etUserPassword);
    final Button btnRegister = (Button) findViewById(R.id.btnRegister);

    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String UserName = etUserName.getText().toString();
            final String UserContactNo = etUserContactNo.getText().toString();
            final String UserEmail = etUserEmail.getText().toString();
            final String UserPassword = etUserPassword.getText().toString();

            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success =  jsonResponse.getBoolean("success");

                        if (success){
                            Intent intent  = new Intent(RegisterActivity.this, LoginActivity.class);
                            RegisterActivity.this.startActivity(intent);
                        }else{
                            AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                            builder.setMessage("Registration Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            RegisterRequest registerRequest = new RegisterRequest(UserName, UserPassword, UserContactNo, UserEmail, responseListener);
            RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
            queue.add(registerRequest);

        }
    });

}

}
and the php file that is connected to the activity
<?php
$con = mysqli_connect("******", "*****", "*******", "*******");

$UserName = $_POST["UserName"];
$UserPassword = $_POST["UserPassword"];
$UserContactNo = $_POST["UserContactNo"];
$UserEmail = $_POST["UserEmail"];

$statement = mysqli_prepare($con, "INSERT INTO UserDetails (UserName,UserContactNo, UserEmail, UserPassword) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssss", $UserName, $UserContactNo, $UserEmail, $UserPassword);
mysqli_stmt_execute($statement);

$response = array();
$response["success"] = true;

echo json_encode($response);
?>

and the problem that i am facing, which is written in the android monitor
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.example.hp.myapplication.RegisterActivity$1$1.onResponse(RegisterActivity.java:43)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.example.hp.myapplication.RegisterActivity$1$1.onResponse(RegisterActivity.java:39)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.os.Looper.loop(Looper.java:148)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-30 20:36:22.928 2828-2828/com.example.hp.myapplication W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-30 20:39:24.125 1582-1595/system_process I/UsageStatsService: User[0] Flushing usage stats to disk

A: You should change your backend part: your php script should return json content with next header: Content-Type:application/json;. Now it returns text/html.

A: Add this header in your php, that´s the way to return only json without html
header('Content-Type: application/json');
echo json_encode($response);

Now your php sholud look like this
<?php
$con = mysqli_connect("******", "*****", "*******", "*******");

$UserName = $_POST["UserName"];
$UserPassword = $_POST["UserPassword"];
$UserContactNo = $_POST["UserContactNo"];
$UserEmail = $_POST["UserEmail"];

$statement = mysqli_prepare($con, "INSERT INTO UserDetails (UserName,UserContactNo, UserEmail, UserPassword) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssss", $UserName, $UserContactNo, $UserEmail, $UserPassword);
mysqli_stmt_execute($statement);

$response->success= true;

echo json_encode($response);
?>


text:
Q: Return the most recent record only if a query results in records having the same value in a given column If my query is
SELECT * FROM EventLog WHERE Role LIKE %Admin%

And the query resulted in 3 records with Name column value "John" and 4 records with Name column value "Bob",
I would want it to only show me one Bob and one John result, and have the single result it includes for each name be the one with the latest date in the Date column (for that name)
Basically, remove duplicate Name results and just show the one with the most recent date for that name.

A: One solution is to use a correlated sub-query to get the most recent record for each name - here is a similar solution for getting the most expensive product for each supplier from a table of products:
SELECT P1.* FROM [Products] AS P1
INNER JOIN (
    SELECT SupplierID, MAX(Price) AS MaxPrice FROM [Products] GROUP BY SupplierID
) AS P2 ON (P1.SupplierID = P2.SupplierID AND P1.Price = P2.MaxPrice)

I tested this at https://www.w3schools.com/sql/trysql.asp?filename=trysql_op_in  but I don't have a database locally to be able to setup an exact example for your EventLog table, but the principle is the same.  You will need to get the MAX(Date) and GROUP BY Name.


text:
Q: SystemConfiguration.dll. Is part of the 2.0 or 3.5 Framework? I have a .NET 3.5 C# console app. I need to read the App.Config. When I go to set a reference to system.Configuration.dll, I saw that even though my app was compiled as version 3.5 of the Framework, that the Add Ref dialog only showed me the 2.0 version of the dll.
So I found the dll under:
C:\Program Files\Reference Assemblies\Microsoft\Framework.NETFramework\v3.5\Profile\Client
I decided to try and set a reference directly to this 3.5 dll. After doing this, my project ended up with a 2.0 version.
What is going on? I thought that if an app was compiled against a particular version of the Framework, that all of the dlls that were part of the framework were all from the same version. It seems like I am mixing versions. I guess I am not too surprised that I can simultaneously access dlls from older versions of the framework, but if there is a newer version in the 3.5 folder, why is it not using it? or is this really the 2.0 dll placed in the 3.5 folder?

A: System.Configuration.dll is from v2.0 of the Framework.  The file in the location you found is still the same as the .NET 2.0 file, but it's just there as a packaged component of the 3.5 Client Profile (with the Client Profile just being a trimmed down version of full .NET).
Version 3.5 of .NET is just a set of extensions on version 2.0 as it runs on the 2.0 CLR, and, as such, implements 2.0, 3.0, and 3.5 versions of the DLLs from the .NET framework.  The classes in System.Configuration.dll were introduced, and are still all from, version 2.0 of the framework, thus the DLL itself will always be 2.0.0.0
For some more detail: http://en.wikipedia.org/wiki/.NET_Framework_3.5#.NET_Framework_3.5

A: .NET 3.5 is based on the .NET 2.0 runtime, which means that many of the assemblies are still 2.0.
This is normal.


text:
Q: Horizontal scroll on wheelEvent with shift too fast I have 200 objects on the MyView that is derived from the QGraphicsView. I use the mouse wheel to scroll vertically, everything is nice and smooth. I think that is the Qt default implementation.
I implement the Shift + wheel to scroll horizontally, and the horizontal scroll bar jumps a huge step on a single wheel event - 10 times bigger than that on the vertical scroll bar.
Basically, the same wheel event drives the horizontal scroll bar 10 times farther than the vertical scroll bar.
How to slow down the horizontal scroll bar?
Well, I tried to reduce the original event's angleDelta value like this event.angleDelta()/10 to generate a new wheel event and use the new event to drive the horizontal scroll bar. That works but seems to be too complicated.
I also notice it is the Shift modifier that affects the horizontal scroll bar behavior. If I do self.horizontalBar().wheelEvent(event) without the Shift modifier, the horizontal bar scrolling is 10 times slower. That is weird. Why does pressing Shift change the horizontal scrolling behavior?!
import sys
from PyQt5.Qt import QGraphicsScene, QGraphicsView, QGraphicsTextItem, QApplication, QWheelEvent, Qt

class MyView(QGraphicsView):
    def wheelEvent(self, event: QWheelEvent):
        if event.modifiers() == Qt.ShiftModifier:
            self.horizontalScrollBar().wheelEvent(event)
        else:
            self.verticalScrollBar().wheelEvent(event)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    scene = QGraphicsScene()
    view = MyView(scene)

    # Generate 200 objects, 100 on x and 100 on y.
    for i in range(100):
        obj_on_x = QGraphicsTextItem("X" + str(i))
        obj_on_x.setX(i * 100)
        scene.addItem(obj_on_x)

        obj_on_y = QGraphicsTextItem("Y" + str(i))
        obj_on_y.setY(i * 100)
        scene.addItem(obj_on_y)

    view.show()
    sys.exit(app.exec_())

A: In order to slow down the two scrollbars, I would interact with them changing their values like this (in my code, I moved the scrollbars horizontally with Ctrl and vertically with Shift):
def wheelEvent(self, event):

    delta = event.angleDelta().y()

    if event.modifiers() & Qt.ControlModifier:
        x = self.horizontalScrollBar().value()
        self.horizontalScrollBar().setValue(x - delta)

    elif event.modifiers() & Qt.ShiftModifier:
        y = self.verticalScrollBar().value()
        self.verticalScrollBar().setValue(y + delta)

A: Another way to accomplish this is to trigger a
SliderSingleStepAdd or SliderSingleStepSub
action using the triggerAction function.
These seem to move at an appropriate scroll speed since it applies whatever delta would naturally be used.
def wheelEvent(self, event: QtGui.QWheelEvent):

    scrollbar = self.verticalScrollbar()
    if (event.modifiers() == QtCore.Qt.ShiftModifier):
        scrollbar = self.horizontalScrollBar()

    action = QtWidgets.QAbstractSlider.SliderSingleStepAdd
    if (event.angleDelta().y() > 0):
        action = QtWidgets.QAbstractSlider.SliderSingleStepSub

    scrollbar.triggerAction(action)


text:
Q: How to align my multiple collapsible Bootstrap panels nicely? I want to display a list via "collapsible bootstrap panels" but I notice when I open certain panels they do not align properly.
E.g. when I open the first panel in the code all other panels move under each other under the second panel.
I want panel 3 and 4 to stay on their place in their grid when I open panel 1.
What am I doing wrong?

                Panel 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
                        Praesent scelerisque, neque sit amet aliquam pulvinar, metus
                        arcu commodo sem, id volutpat erat nulla imperdiet enim. Proin
                        imperdiet dolor vitae lorem efficitur, non tincidunt nisi
                        accumsan. Nam condimentum mi ac auctor tincidunt. Fusce eget
                        tempus velit, in porta velit. Mauris vel ultrices ipsum. Nunc
                        rutrum vitae quam ut porta. Suspendisse diam sem, molestie sed
                        nisl id, imperdiet ornare libero. Lorem ipsum dolor sit amet,
                        consectetur adipiscing elit. Nam sagittis augue vitae iaculis
                        lacinia. Ut id eros egestas turpis vehicula feugiat ut eu
                        lectus. Ut eu consequat arcu, a porttitor magna.

                Panel 2

Nunc vel lectus sit amet ante imperdiet aliquet non sit amet
                        felis. Vestibulum rhoncus rutrum ante nec sodales. Aliquam
                        vitae suscipit orci. Nam dignissim a purus vitae efficitur.
                        Pellentesque habitant morbi tristique senectus et netus et
                        malesuada fames ac turpis egestas. Nam libero augue,
                        scelerisque ut rhoncus eu, scelerisque a enim. Vestibulum ante
                        ipsum primis in faucibus orci luctus et ultrices posuere
                        cubilia Curae; Ut luctus molestie lectus, ac dictum sem tempor
                        id.

                Panel 3

Aliquam sit amet convallis nulla, quis dapibus elit. Aliquam
                        nisl justo, mollis et pulvinar ut, laoreet eu enim. Quisque
                        maximus scelerisque dui, aliquam posuere dolor consequat ut.
                        Nullam semper dictum urna et auctor. Donec lacus risus,
                        sagittis at vestibulum ac, dictum vitae mauris. Duis non velit
                        congue diam vulputate auctor a et libero. Duis a tortor
                        lobortis, suscipit orci eu, facilisis eros. Proin et faucibus
                        tortor, in finibus elit. Morbi suscipit porttitor justo
                        interdum euismod. In posuere leo velit, non egestas tortor
                        malesuada sit amet. Phasellus malesuada ultricies massa eget
                        volutpat.

                Panel 4

Cras interdum dui sit amet nisi porttitor, iaculis cursus
                        tellus tincidunt. Praesent iaculis eget ipsum sed condimentum.
                        Fusce aliquam ipsum mauris. Donec laoreet dapibus efficitur.
                        Quisque in rhoncus dolor. Aliquam erat volutpat. Quisque eget
                        quam sed velit ultrices pellentesque. Vivamus neque arcu,
                        vestibulum in neque a, tincidunt sagittis lectus. Nullam nisi
                        nulla, semper non maximus sed, rutrum vel velit.

A: **Tyr With this**

         panel1 Code

         panel2 Code

         panel3 Code

         panel4 Code


text:
Q: Image caching does not work for me using GeowebCache integrated in Geoserver 20.4 I have configured gwc cache system and enabled layer for cache and global services over OGC Services on global settings.
When I try this URL I get this:
$ curl 'http://myserver/geoserver/geoserver/gwc/service/wms?SERVICE=WMS&REQUEST=GetMap&BBOX=-180,-90,0,80.33032694475760138&SRS=EPSG:4326&WIDTH=846&HEIGHT=800&LAYERS=ws:mylayer&FORMAT=image/png'

GWC Error

400: class org.geowebcache.mime.ApplicationMime cannot be cast to class org.geowebcache.mime.ImageMime (org.geowebcache.mime.ApplicationMime and org.geowebcache.mime.ImageMime are in unnamed module of loader org.apache.catalina.loader.ParallelWebappClassLoader @3524ee20)
Looking in geoserver.log for this request, I get:
2022-05-18 12:53:48,806 ERROR [geowebcache.GeoWebCacheDispatcher] - class org.geowebcache.mime.ApplicationMime cannot be cast to class org.geowebcache.mime.ImageMime (org.geowebcache.mime.ApplicationMime and org.geowebcache.mime.ImageMime are in unnamed module of loader org.apache.catalina.loader.ParallelWebappClassLoader @eb5471c) http://vgis.dipalme.org:8080/geoserver/gwc/service/wms
2022-05-18 12:53:48,806 ERROR [geowebcache.GeoWebCacheDispatcher] - Request failed
java.lang.ClassCastException: class org.geowebcache.mime.ApplicationMime cannot be cast to class org.geowebcache.mime.ImageMime (org.geowebcache.mime.ApplicationMime and org.geowebcache.mime.ImageMime are in unnamed module of loader org.apache.catalina.loader.ParallelWebappClassLoader @eb5471c)
at org.geowebcache.service.wms.WMSTileFuser.(WMSTileFuser.java:325)
at org.geowebcache.service.wms.WMSService.getFuser(WMSService.java:356)
at org.geowebcache.service.wms.WMSService.handleRequest(WMSService.java:319)
...


text:
Q: why R does not recognise columns and rows as they are supposed to be? The code given bellow is to extract  values of one region and write that to a text file(there are 365 binary files in the directory).
The problem which I am facing is that all my files are binary with size of 360 rows and 720 columns.
I specified that in this line:
file2 <- matrix(data=file,ncol=720,nrow=360)

but I got an error:

Error in mean(file2[X, Y], na.rm = TRUE) : subscript out of bounds.

and then I rewrote the above line as:
file2 <- matrix(data=file,ncol=360,nrow=720)

I put ncol=360 and nrows =720 which is not right. But that worked and I didn't get any error. However, the results were not correct.
X <- c(364:369) ;   Y <- c(82:92) #####   for sellected region
extract <- vector()
dir1 <- list.files("C:\\Users\\Climate_Rad_f_GAMMA_%d.img", full.names = TRUE)
listfile<-dir1()
for (i in c(1:365))
{
    conne <-  file(listfile[i], "rb")
    file <-  readBin(conne, double(), size=4,  n=720*360, signed=T)
    file2 <-  matrix(data=file,ncol=720,nrow=360)
extract[i] <- mean(file2[X,Y],na.rm=TRUE)
    close(conne)
    write.table(extract,"C:\\Users\\sam.txt")
}

A: In this code:
mean(file2[X,Y],na.rm=TRUE)

You are selecting rows X and columns Y.  You have but 360 rows.  You might want this instead:
mean(file2[Y,X],na.rm=TRUE)


text:
Q: Need help to solve Python exercise I have to make a simple Python program that allows to get the average of three different students and eventually get the class average and print it on the screen. The code is the following:
john = {
    "name": "John",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "extras": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
}
paul = {
    "name": "Paul",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "extras": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}
tyler = {
    "name": "Tyler",
    "homework": [0.0, 87.0, 75.0, 22.0],
    "extras": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
}

students = ["john", "paul", "tyler"]

def average(numbers):
    total = sum(numbers)
    total = float(total)
    return total/len(numbers)

def get_average(student):
    homework = average(student["homework"])
    extras = average(student["extras"])
    tests = average(student["tests"])

    return homework*0.1 + extras*0.3 + tests*0.6

def qualifications_in_letters(result):
    if result >= 90:
        return "A"
    elif 80 <= result < 90:
        return "B"
    elif 70 <= result < 80:
        return "C"
    elif 60 <= result < 70:
        return "D"
    else:
        return "F"

def get_class_average(students):
    marks = []
    for student in students:
        marks.append(get_average(student))
    return average(marks)

print get_class_average(students)
print qualifications_in_letters(get_class_average(students))

Each student has a dictionary with four keys and values (name, homework, extras and tests). What the program should do is to take the marks of the students, get their individual average and then get the class' average. The homework represents the 10% of each student's average; the extras the 30% and the tests the 60%.
There is a list that has the names of the students as elements. The problem is that when I run the code this error message appears:
Traceback (most recent call last):
  File "<stdin>", line 52, in <module>
  File "<stdin>", line 49, in get_class_average
  File "<stdin>", line 28, in get_average
TypeError: string indices must be integers, not str

I don't know how to fix it.
Line 28 is the second one in get_average(); line 49 the one inside the for loop and 52 is the pne where get_class_average() is called.

A: Your problem is this line of code:
students = ["john", "paul", "tyler"]

You are setting your students list to be a list of strings, not a list of dictionaries. Remove the quotations.
students = [john, paul, tyler]

Now you have a list of your student dictionaries and the program runs with the following output:
83.8666666667
B

A: Your students array is an array of strings (the literal strings "john", "paul", "tyler").
You should create the array using the variable names (no quotes).
students = [john, paul, tyler]


text:
Q: can't calling a class methods in laravel controller class Suppose I have this code:
class UserController extends Controller
{
    protected $test;

    public function __construct()
    {
        $this->test = new Test();

    }

    // first call this func
    public function add_name()
    {
        $this->test->add_name('name1')
        return $this->test->get_name();
    }

    // then this one
    public function show_name()
    {
        return $this->test->get_name();
    }

}

class Test
{
    protected  $name;

    public function get_name()
    {
        return $this->name;
    }

    public function add_name($name)
    {
        $this->name = $name;
    }
}

So when I call show_name() function after add_name() in UserController(first class), return nothing. What is my code problem?
(when calling add_name() function it work correctly)

A: In Laravel, It's not good practice to write separate class inside the Controller file . You have to create a separate class file in app/Classes directory . say for eg your class, Class_Test.php inside app/class. And in Your Controller file, on the top, you need to include namespace of class . Your controller function should be like .use App\Classes\Class_Test;

class UserController extends Controller
{
public function add_name()
{
   //call the class function
    Class_Test::add_name('name1');
}

// then this one
public function show_name()
{
    Class_Test::get_name();
}

}
Hope this Help you .


text:
Q: What are some reasons why a MySQL index would be 12X the size of the table? So we have a table that has two indexes one on the primary key and one other index on another column on the table. The index size is currently 12X larger than the table itself. What are some reasons why this would happen? We've optimized the table before and it helped but it's growing again.
Thanks!

A: This size is not uncommon with indexes, especially for large text fields. While it might be indicative of a poor indexing strategy, text is notably more complex to index than numbers, especially if enabling substring searches not anchored to the beginning of the text field.
While a large index might seem slow by its nature, it can (or should be) navigated quite quickly due to its highly structured nature, and thus yield pointers to the correct data faster than an exhaustive search of the data itself.
Assuming they will continue to fit on disk, the real tests of your indexes are satisfactory search, update and addition times, especially as the amount of data scales. If these aspects continue to be adequate, a large index is tolerable.

A: Factors which may negatively influence the size of an index

*

*Distribution of data (i.e. if it's uniform or biased)

*Order of data being inserted/deleted/updated (i.e. if it's not random)

*For varchar's, the size and charset of the varchar

*For innodb, using an unnecessarily large datatype for the primary key will affect the contribution of each index as it's implicitly part of it

As you noted, re-writing the index (i.e. optimizing the table) can/will balance the index structure out again.


text:
Q: Inflate a layout on a ViewPager fragment I've a ViewPager that uses a FragmentPagerAdapter, with 3 pages on it, and what I want is to inflate a new fragment layout on the top of my middle fragment when a button is pressed.
This was what I tried:
MainActivity.java
 ...

 // Method that is called when the button is cliked
 public void buttonCliked(View view) {
    viewPager.setCurrentItem(5);
 }

 ...

MyAdapter.java
 public Fragment getItem(int i) {

    Fragment fragment = null;
    if(i == 0) {
        ...
    }
    else if(i == 1) {
        ..
    }
    else if(i == 2) {
        ..
    }
    else if(i == 5){
        fragment = MyFragment.newInstance("aa", "aa");
    }

    return fragment;
}

But basically what's happening is, when I pressed the button, the ViewPager slides to the new fragment instead of replacing it. Any ideas how can I make this work the way I want?
Summing up how can I inflate a new layout on the top of the select fragment in a ViewPager?
Thanks.

A: getItem is called when the adapter needs to instantiate a new fragment, not everytime you swipe to show another fragment. The adapter saves created fragments in FragmentManager, so if I understand your question correcty I think that's where need to get your fragment from and replace it.
There are answers how to retrieve fragments like that here on SO. Link
Edit: As shown in this answer:
mFragmentManager.beginTransaction().remove(mFragment).commit();
mFragment = NewFragment.newInstance();
notifyDataSetChanged();


text:
Q: Display the product shipping class on Woocommerce single product pages I'm trying to display the shipping class on product page but I must do something wrong because nothing shows..
I used the bellow code in function.php:
add_action('woocommerce_single_product_summary', 'display_specific_shipping_class', 15 );
function display_specific_shipping_class(){
    global $product;

    // HERE define your targeted shipping class name
    $defined_shipping_class = "Estimated Delivery in 7-15 days";

    $product_shipping_class = $product->get_shipping_class();

    // Get the product shipping class term name
    $term_name = get_term_by( 'slug', $product_shipping_class, 'product_shipping_class' );

    if( $term_name == $defined_shipping_class ){
        echo '
' . $term_name . '
';
    }
}

A: You are getting the WP_term object and not the term name… So instead use the following:
add_action('woocommerce_single_product_summary', 'display_specific_shipping_class', 15 );
function display_specific_shipping_class(){
    global $product;

    // HERE define your targeted shipping class name
    $defined_shipping_class = "Estimated Delivery in 7-15 days";

    // Get the product shipping class WP_Term Object
    $term = get_term_by( 'slug', $product->get_shipping_class(), 'product_shipping_class' );

    if( is_a($term, 'WP_Term') && $term->name == $defined_shipping_class ){
        echo '
' . $term->name . '
';
    }
}

Code goes in function.php file of your active child theme (or active theme). It should works now.


text:
Q: How to get the contents of a webpage but after running javascript? I am trying to download the contents of a web page using curl but it seems l am missing some content that l suspect to be generated by JavaScript. If the page runs on the browser l am able to get all the contents l require.

A: You can use PhantomJS to do it.
(From the link, PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.)


text:
Q: Internet Explorer hiding iframe when its supposed to show on hover I created a simple mouse over that shows a youtube video using iframe embed.
The mouse over is: Hover A to show B and if you hover over B, B stays shown until you hover over something else that is not A or B.
If you notice, if I hover over the white space of the green box, which is B, it stays on, but as soon as I move mouse over the iframe/youtube video it disappears.
HTML

cool

CSS
.a { border: solid blue; height: 20px; }
.b {display: none; border: solid green; }
.a:hover + .b { display: block; }
.b:hover { display: block; }

JS FIDDLE LINK
BTW I am using IE 11. Firefox and Chrome do not have this problem.
Any possible solutions/suggestions/workarounds?

A: Add this to your css:
iframe { position: relative; z-index:-1; }

Can be .b iframe { also.

A: How about using this code?
http://jsfiddle.net/X5br3/37/
IE11 tested
.a { border: solid blue; height: 20px; }

.b {display: none; border: solid green; }

.a:hover + .b { display: block; }

.b:hover { display: block; }

/* added */
.b iframe {
    position:relative;
    z-index:-1;
}


text:
Q: UDP Incorrect checksum triggers repeat request instead of dropping packet hope you're having a good day.
I am using UDP to send packets of data from a microcontroller to a python server on my PC (I could not get the speeds I needed over TCP).
I want to send a repeat request to the microcontroller if a packet is dropped (assuming this is the easiest method for error correction over UDP)?
I am aware UDP uses checksum and if this is incorrect it will be dropped by the receiver. Is there a flag or equivalent in python socket so that when a packet is dropped, I can ask the microcontroller to send the packet again?
Thanks in advance for your time,
Will

A: UDP is an unreliable protocol. It has no mechanism to "ask for sending again" if a packet gets dropped because of the wrong checksum. It has also no mechanism to detect duplicate packets, reordering or lost packets. There is no kind of flag which could be switch on to get a reliable transport based on UDP.
If you need reliable transport either use TCP or implement you own custom reliability layer on top of UDP.


text:
Q: Displaying Map on Lwuit nokia s40 I'm using Lwuit to develop app on nokia s40 SDK 2.0
I have to add a Map to my application..
So i hav used the code given below but the screen doesnot display anything.
I get a blank screen. How can I display this on lwuit form or container?
(the code runs completely and exits without errors & 'END' is printed)

ApplicationContext.getInstance().setAppID("ruKXq--------Sbgq");
            ApplicationContext.getInstance().setToken("kWRp_Vp---------AG7rw");
      Display display = Display.getDisplay(COMPANY_Midlet.getInstance());
      MapCanvas mapCanvas = new MapCanvas(display) {
          public void onMapUpdateError(String description,
              Throwable detail, boolean critical) {
              // Error handling goes here.
          }
          public void onMapContentComplete() {
          }
      };

      mapCanvas.getMapDisplay().setState(
          new MapDisplayState(new GeoCoordinate(52.51, 13.4, 0), 10));

      System.out.println(mapCanvas.getMapDisplay().getState());

      display.setCurrent(mapCanvas);

      System.out.println("END");

A: Architecturally the most elegant way would be to create a custom LWUIT component which encapsulates the MapCanvas and exposes a standard LWUIT interface - in other words basic use of an adaptor pattern. There is an example of this pattern to be found within the Nokia Projects Tourist Attractions example (the version updated for LWUIT). Additionally sample code for such a component can be found on GIT hub here


text:
Q: How do I properly link math.h library in makefiles? I need to plot a function with gnuplot. This function requires the math.h library. Now I want to run it with a makefile.
When I run the makefile I get this output/error:
gcc -I./inc -o./build/result -lm ./src/main.c ./src/gnuplot.c
/usr/bin/ld: /tmp/ccwsiOjK.o: in function `plot_y':
main.c:(.text+0x64): undefined reference to `exp'
/usr/bin/ld: main.c:(.text+0xbc): undefined reference to `pow'
/usr/bin/ld: main.c:(.text+0x121): undefined reference to `exp'
collect2: error: ld returned 1 exit status
make: *** [makefile:5: all] Fehler 1

I think I didn't link the math.h library properly.
The makefile:
run: all
    ./build/result

all: build
    gcc -I./inc -o./build/result -lm ./src/main.c ./src/gnuplot.c
#-I./inc damit der compiler nicht nur im src Ordner sucht
build:
    mkdir build

clean:
    rm -f -r build

A: The order matters.  First list the .c or .o files, then the external libraries.
gcc -I./inc -o./build/result ./src/main.c ./src/gnuplot.c -lm


text:
Q: Ways to imply return values are not meant to be stored We can use nodiscard attribute to imply that the return value of a function should not be discarded. Are there any attribute (or other ways) to imply some opposite semantics: the return value of the function should only be used temporarily (by "temporary" I mean, not to assign to any variable except local ones)?
As the purpose may not be immediately clear, consider I have a class FooHolder that holds resources Foo; calling FooHolder::getFoo() returns the Foo it is currently holding:
#include <memory>

class Foo {
public:
    Foo& bar() { /* do something */ return *this; }
    const Foo& far() const { /* do something else */ return *this; }
};

class FooHolder {
private:
    std::shared_ptr<Foo> _foo { nullptr };

public:
    FooHolder(): _foo(std::make_shared<Foo>()) {}

    Foo& getFoo() { return *_foo; }
    const Foo& getFoo() const { return *_foo; }
};

And we may use it in many ways:
// Others may try storing some status:
Foo* g_foo = nullptr;

int main() {
    FooHolder foo_holder {};

    // I want to support this:
    foo_holder.getFoo().bar().far() /* chained calls... */ ;

    // Also, maybe this:
    auto& local_foo = foo_holder.getFoo();
    local_foo.bar();
    local_foo.far();

    // But not this, because the Foo instance that FooHolder holds may perish:
    static Foo& static_foo = foo_holder.getFoo();

    // Nor this:
    g_foo = &local_foo;

    return 0;
}

So are there ways to prevent (or at least warn about) storing the return value of FooHolder::getFoo()? Or, is it bad practice to return resources by reference?

A:
[...] is it bad practice to return resources by reference?

It depends. There are many examples of methods that return non-const references and they are all fine. For example consider standard container element accessors. However, they are not meant for encapsulation. std::vector::operator[] is not meant to hide the elements from the caller, it is meant to provide direct access to it. Returning a non-const reference is not encapsulation! It is the opposite. Note that std::vector  even grants you access to its data(). Thats not encapsulation either, it is relying on the user to not delete[] some_vect.data() or do other wrong stuff that would break the vector.
You want FooHolder to encapsulate the contained Foo.
This is opposing requirements.
You have basically two choices: A) The caller knows what they are doing. They read documentation. They know that they are not supposed to use FooHolder::getFoo in the wrong way. B) use proper encapsulation: Never give the caller direct access to a non-const Foo:
class FooHolder {
private:
    std::shared_ptr<Foo> _foo { nullptr };

public:
    FooHolder(): _foo(std::make_shared<Foo>()) {}

    // nope // Foo& getFoo() { return *_foo; }
    // maybe // const Foo& getFoo() const { return *_foo; }

    FooHolder& bar() {
            _foo->bar();
            return *this;
    }
    // ..same for far() ...
};

Note that A) is a viable solution. Consider that also things like std::shared_ptr can be used terribly wrong. Users are expected to know how to use it right. The difference is that std::shared_ptr is a standard type with plenty of documentation. Hence, you should think twice if this is the way to go.

So are there ways to prevent (or at least warn about) storing the return value of FooHolder::getFoo()?

No. Once you returned a non-const reference all bets are off. FooHolder is no longer in control of what the caller can do with that reference. You can prevent copies or moves but you cannot prevent holding on to a reference.


text:
Q: avoid using nvidia card for Xorg with plasma I have a dell xps 15 9570 laptop with intel and nvidia GPU running ubuntu linux 18.04 and would like to use the nvidia card exclusively for training deep neural networks. I managed to have the X server running on intel following
How to configure igpu for xserver and nvidia gpu for cuda?
it works perfectly when in gdm3 I select to login using the gnome shell (ubuntu Wayland). running nvidia-smi shows that no process is running on the GPU. However now I wanted to try kde with plasma and there the xserver ends up on the nvidia gpu.
(base) ooo: (~) 505> nvidia-smi
Sat Jul 13 14:30:18 2019
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 430.26       Driver Version: 430.26       CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 105...  Off  | 00000000:01:00.0 Off |                  N/A |
| N/A   50C    P5    N/A /  N/A |     66MiB /  4042MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      2073      G   /usr/lib/xorg/Xorg                            66MiB |
+-----------------------------------------------------------------------------+

I tried to for the X server to use intel adding teh two config files
/etc/X11/xorg.conf.d/01-noautogpu.conf
/etc/X11/xorg.conf.d/20-intel.conf
into  /etc/X11/xorg.conf.d as explained here
https://gist.github.com/s41m0n/323513c95290c85f7054384ac34c41c5
The result is unfortunately that after login the screen remains black.
It seems that the plasmashell itself finds and uses the nvidia gpu.
Any idea how to force plasma to use the intel gpu would be very much appreciated.

A: After discovering the questions and answers here How to configure iGPU for xserver and nvidia GPU for CUDA work,
notably the answer of user890178, and studying the syslog
I finally found that it is not plasma that does anything specific but the problem is the same for gnome and plasma shell when using Xorg. With Xorg the
gpu-manager.service
/lib/systemd/system/gpu-manager.service

is triggered by the display-manager
/etc/systemd/system/display-manager.service.wants/gpu-manager.service

and gpu-manager detects nvidia  and writes the file
/usr/share/X11/xorg.conf.d/11-nvidia-prime.conf

which contains
# DO NOT EDIT. AUTOMATICALLY GENERATED BY gpu-manager

Section "OutputClass"
    Identifier "Nvidia Prime"
    MatchDriver "nvidia-drm"
    Driver "nvidia"
    Option "AllowEmptyInitialConfiguration"
    Option "IgnoreDisplayDevices" "CRT"
    Option "PrimaryGPU" "Yes"
    ModulePath "/x86_64-linux-gnu/nvidia/xorg"
EndSection

This file is not used by Wayland and so the nvidia card is not used, but it is used for gnome-shell on ubuntu and plasma. So in fact both will use the nvidia card for Xorg.
The solution is then a variation of the answer of
Maksym Ganenko in the same question above which means is replacing
/usr/share/X11/xorg.conf.d/11-nvidia-prime.conf by
# DO NOT EDIT. AUTOMATICALLY GENERATED BY gpu-manager

Section "OutputClass"
    Identifier "Nvidia Prime"
    MatchDriver "nvidia-drm"
    Driver "nvidia"
    Option "AllowEmptyInitialConfiguration"
    Option "IgnoreDisplayDevices" "CRT"
    # Option "PrimaryGPU" "Yes"   <<< commented out
    ModulePath "/x86_64-linux-gnu/nvidia/xorg"
EndSection

# added
Section "OutputClass"
    Identifier "intel"
    MatchDriver "i915"
    Driver "modesetting"
    Option "PrimaryGPU" "yes"
EndSection

and additionally to avoid gpu-manager to replace these changes when starting the next session to  follow the advice of Oren in question gpu-manager overwrites xorg.conf to protect the file against changes
by means of running
chattr +i /usr/share/X11/xorg.conf.d/11-nvidia-prime.conf

I seems that the fact that the screen remained black after the adding the two files I mentioned in the question to /etc/X11/xorg.conf.d is due to the fact that with the files in /usr/share/X11/xorg.conf.d that the config file did contain contradicting information.
Given the comment of GabrielaGarcia that astonishingly made the claim that what I ask cannot work on a laptop, I feel the necessity to provide a prove, that what I asked can work, and that the answer I provided is indeed a means to make it work.
Here the output of lspci proving the existence of two graphics cards
(base) m3088: (~) 505> lspci | egrep "VGA|NVIDIA"
00:02.0 VGA compatible controller: Intel Corporation Device 3e9b
01:00.0 3D controller: NVIDIA Corporation GP107M [GeForce GTX 1050 Ti Mobile] (rev a1)

Here the output of ps aux filtering the Xorg, plasma, and anaconda python running a tensorflow session. This shows that all run happily together, while plasma and Xorg do not use the nvidia card as desired (see nvidia-smi below)
(base) m3088: (~) 511> ps aux  | egrep "Xorg|plasmashell|anaconda"
roebel   13139  0.9  5.1 17315584 819236 pts/1 Sl+  00:23   0:10 /data/anasynth/anaconda3/bin/python /data/anasynth/anaconda3/bin/ipython
roebel   16198  0.0  0.0  21540  1068 pts/5    S+   00:42   0:00 grep -E Xorg|plasmashell|anaconda
roebel   18886  1.5  1.3 628292 210572 tty2    Sl+  juil.14  24:22 /usr/lib/xorg/Xorg vt2 -displayfd 3 -auth /run/user/1000/gdm/Xauthority -background none -noreset -keeptty -verbose 3
roebel   19171  2.0  3.4 6576588 561212 ?      Sl   juil.14  33:16 /usr/bin/plasmashell

Here the output of nvidia-smi proving that Xorg is not using nvidia, but the tensorflow session in anaconda python is suing it.
(base) m3088: (~) 506> nvidia-smi
Tue Jul 16 00:34:51 2019
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 430.26       Driver Version: 430.26       CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 105...  Off  | 00000000:01:00.0 Off |                  N/A |
| N/A   47C    P8    N/A /  N/A |    123MiB /  4042MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0     13139      C   /data/anasynth/anaconda3/bin/python          109MiB |
+-----------------------------------------------------------------------------+

I am ready to provide screenshots to show that all this happens on a laptop.
EDIT Update for Ubuntu 22.04
I finally started to use Wayland, with the unfortunate side effect that the previous solution did not work anymore. The gnome-shell was running on the GPU, leading subsequently to some problems with the interface.  Following the discussion here I tried uninstalling nvidia wayland support package
sudo apt remove libnvidia-egl-wayland1

and subsequently gnome-shell does now no longer run on the Nvidia GPU keeping the GPU free for DNN training.


text:
Q: Using format specifier in for a URL in iOS I'm having problems with using format specifiers for url's. Using the zBar scanner to scan a php link. I've spent a lot of time researching here on overflow but I cannot find the answer.
This is the code I use in my viewcontroller.m:
 NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://mywebsite.co.uk/TM.php?id=%@",self.scannedValue]]];
//NSData *jsonData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sample" ofType:@"JSON"]];

NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:Nil];

I'm trying to get the part after id to take in any integer number like 200,201,202,203,...
For some strange reason it only works when I type the number in itself as id=201 or id=202.
when I use NSLog for NSLog(@"%@",scannedValue) it shows the following:
2014-02-26 21:45:27.185 MeCombine[2412:60b] http://mywebsite.co.uk/TM.php?id=201
2014-02-26 21:45:27.277 MeCombine[2412:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'

Can anyone tell me why this happens please?
A few notes:
scannedValue = sym.data;
is string, sum is ZBarSymbol class object
In the ZBarSymbol class
@property (readonly, nonatomic) NSString *data;

is the starting value.
When a value is successfully scanned it will return a NSString *data in the delegate method.

A: I can only provide a guess, since I don't see all of your code, but here's what I think goes on:
Your http link is malformed (http:: instead of http:). The jsonData object will be nil if it can't load the URL for whatever reason.
You don't do any null checking, and this nil object is sent to whatever method processes your json data, which throws a NSInvalidArgumentException if the data object is nil.

A: NSData's +dataWithContentsOfURL: does not tolerate nil URL, which in this case happens because of the incorrect URL format, notice you have two : in the URL after http. The correct URL would be.
http://mywebsite.co.uk/TM.php?id=%@

The modern and potentially more foolproof way of building URLs would be to use NSURLComponents (iOS 7 and OS X 10.9)
NSURLComponents *comps = [NSURLComponents componentsWithString:@"http://www.mywebsite.co.uk"];
comps.query = [NSString stringWithFormat:@"id=%@", self.scannedValue];
comps.path = @"/TM.php";
NSURL *URL = comps.URL;

The main benefit would be the ability to isolate the base URL into a constant string and then alter the query/path from elsewhere, both making things a bit more modular and easier to maintain than a hardcoded value in code.


text:
Q: Python: изменить кодек и частоту аудиофайла Доброй ночи. Как можно изменить кодек и частоту аудиофайла? Это прям необходимо, потому что одна программа странно зависит от этих настроек. Для создания использую следующий код:
sound = AudioSegment.from_mp3("test1.wav")
sound = sound + AudioSegment.from_mp3("test2.wav")
sound.export("test3.wav", format="wav")

A: Частота меняется через resample(), если использовать модуль audiosegment, который добавляет дополнительные функции к pydub. Или функцией set_frame_rate через pydub.
Кодек выставляется через параметр codec функции export.


text:
Q: gh-pages subdirectory files aren't shown up I have following github page displaying some HTML already: http://json-schema-faker.github.io/json-schema-faker/
this is the source repo (gh-pages branch): https://github.com/json-schema-faker/json-schema-faker/tree/gh-pages
Although top-level directory files work perfectly fine:

*

*http://json-schema-faker.github.io/json-schema-faker/index.html - https://github.com/json-schema-faker/json-schema-faker/blob/gh-pages/index.html

*http://json-schema-faker.github.io/json-schema-faker/globals.html - https://github.com/json-schema-faker/json-schema-faker/blob/gh-pages/globals.html
the lower-level directories files don't work at all, e.g.

*

*http://json-schema-faker.github.io/json-schema-faker/modules/_class_container_.html -> https://github.com/json-schema-faker/json-schema-faker/blob/gh-pages/classes/_class_container_.container.html
The files are there, uploaded in the repo in gh-pages branch. What is wrong?

A: Github pages is using Jekyll as default site generator.
Default behavior for jekyll is to ignore folders and files with a name that begins with an underscore (except if you configure jekyll not to ignore them. See include key in documentation).
Fastest resolution : instruct gh-pages not to use jekyll to process and publish your pages, but just copy all your files on the web server.
To do so, just create an empty .nojekyll file at the root of your gh-pages branch. Push. And everything is OK.