text:
Q: How come the second wand configuration shoots faster than the first? I have a no-shuffle wand with 2 spells per cast and the following spells in it:
Chainsaw | add mana | projectile area teleport | double scatter | energy sphere
I find that if I swap the 1st and 2nd spell, the wand fires much faster, but I don't understand why. So that would be
add mana | Chainsaw | projectile area teleport | double scatter | energy sphere
I thought I understood spell wrapping, namely that if the wand tries to cast a spell block of more than 1 spell but it reaches the end of the wand's slots without finding enough spells to cast, it would start at the first slot again and grab the first spell it finds to copy into the last spell-block.
However this would not explain the faster casting speed of the second configuration, so I must be missing something?
Slow firing spell order

Fast firing spell order

If it helps, you can also see both in action here: Different rates of fire caused by chainsaw location


text:
Q: Python, Tkinter, Function to destroy Images. (multiple arguments) ive been making a program in Tkinter and basically i want to remove all the images that have been placed on the window to be removed. Seen as the function i have created (or tried to :P) is in charge of clearing the window i need it to be able to remove whatever i want it to from any point in the program.
Theres 2 images on this window, img and img1. After 5000 seconds? (Another thing im not sure on but havent looked at that bit yet) The timer will run out and lead to the function. However i seem to be formatting the function wrong.
As you can see, i tried using (*A) But that appears to just be for strings for printing and such and doesnt recognise the .destroy(). Another thing i tried was to have the function like:
def removewidgets(A)(B)(C)(D):
    A.destroy()
    B.destroy()
    C.destroy()
    D.destroy()
    return;

But i am convinced this is a terrible method and it didnt work anyway hah.
Really hope someone can solve my issue, many thanks!
Heres the code.
import sys
from tkinter import *
from PIL import Image, ImageTk
#______________________________________________________________________________________
SWH = Tk()
SWH.geometry("1024x950+130+0")
SWH.title("ServiceWhiz.")
#_______________________________________________________________#GlobalFunctions#______
#ClearAllWidgets
def removewidgets(*A):
    A.destroy()
    return;
#_______________________________________________________________#LoadingPage#__________
load = Image.open("Logo.png")
render = ImageTk.PhotoImage(load)
img = Label(SWH,image=render)
img.image = render
img.place(x=458,y=250)

load = Image.open("PoweredByServiceWhiz.png")
render = ImageTk.PhotoImage(load)
img1 = Label(SWH,image=render)
img1.image = render
img1.place(x=362,y=612.5)

img.after(5000, removewidgets(img, img1))

A: First, when you're numerating your variables, you should use something else instead, in this case, a list, so you just have to pass a single list to the function. In the function, you can loop over the sequence items and call destroy for each of them. It would be even easier if you'd create a class for the GUI.
The thing is that you call the function removewidgets inside the img.after parameter. Since all callable parameters are called and their return value is used, your calling the event None.
Use this construct instead:
img.after(5000, lambda: removewidgets(img, img1))

lambda creates an anonymous function, thus you're using the function object as the parameter.
You don't need to type return;, btw. If there's no return specified, the function will return None.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como posicionar o footer no fim da página sem o conteudo da pagina ficar em cima Olá, estou com um problema simples que não consigo resolver de jeito nenhum.
Tenho uma página com bastante conteúdo, mas o conteúdo fica em cima do footer ou vice-versa. Já tentei por position absolute, relative, fixed etc. O body e html estão com height 100%. Body com display flex, e flex-direction: column. Alguem para dar uma luz? A estrutura está assim:
Imagem do conteudo da pagina em cima do footer
const Layout = () => {
  const isMobile = useMediaQuery({ maxWidth: 900 });

  return (
    <Fragment>
      {isMobile ? <NavbarMobile /> : <Navbar />} //header (navbar)

        <Routers /> // conteudo da pagina

        // footer
    </Fragment>
  );
};

css:
footer:
   width: "100%",
   height: "auto",
   color: "white",
   bottom: "0",

A: Pode colocar a div do conteúdo com um padding-bottom do tamanho do footer.
Seria mais ou menos o seguinte:
footer {
  height: 300px;
}

/* div do conteúdo */
.page-content {
  padding-bottom: 300px;
}

A: no seu caso pode fazer assim
const Layout = () => {
  const isMobile = useMediaQuery({ maxWidth: 900 });

  return (
    <Fragment>
      {isMobile ? <NavbarMobile /> : <Navbar />} //header (navbar)

        <Routers /> // conteudo da pagina

          // footer

    </Fragment>
  );
};

.content{
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

footer {
  margin-top: auto;
}

isso garantira que seu footer sempre ficará no bottom mesmo que n haja conteúdo


text:
Q: How can I save my progress on GTA 5 in the middle of a mission? Sometimes I need to get off of the game while I'm in the middle of a mission but I can't find a way to save besides ending the mission.
Is this possible?

A: Unfortunately you can't. You have two options:
You can quit the game and rely on your autosave. See this question for how to turn it on and when it saves. There's no way not to lose your progress in the current mission though.
Alternatively, you could leave the game paused, assuming that's practical.


text:
Q: Select All from one table and fill values from another table on the result I want get full column from one table and select sum from another table that have same id.
Eg:
 table1          table2
 id    target        id    target achived
 1      40           1      20
 2      50           2      25
 3      66
 4      80

and i want to select all from table 1 and fill achived target results on it.
Eg:
 id    target  target achived
  1      40         20
  2      50         25
  3      66          0
  4      80          0

how can i do that using mysql

A: Use this query:
 select table1.*, case when table2.target_achieved is null
                  then 0
                  else table2.target_achieved
                  end as target_achieved
       from table1 left join table2
       on table1.id = table2.id
       order by table1.id

A: Below query results in 0 instead of NULL
SELECT t1.id, target, COALESCE(target_achieved, 0) AS target_achieved
FROM table1 AS t1
LEFT JOIN table2 AS t2
ON t1.id = t2.id;


text:
Q: fixed point iteration i am trying to find such  p,that for given function f(p),we have equality
p=f(p);
here is code
#include <iostream>
#include<math.h>
using namespace std;
float fixed(float x){
    return (float)(pow(x,3)-4*pow(x,2)-10);
}

int main(){
    float p=0.0;
    float p0=1.5;
    float tol=(float).001;
    int N=25;
    int i=1;
    while(i<N){
        p=(float)fixed(p0);
        if((p-p0)<tol){
          cout<<p<<endl;
          break;
        }
        i=i+1;
        p0=p;
        if(i>N){
          cout<<"solution not found ";
          break;
        }
    }
    return 0;
}

i have tried different  initial point,also different  tolerance,but result is very  nonsense -16 or -15.something,so what is wrong?is code correct?please help

A: I'm not sure what you're trying to achieve, but probably using :
if(fabs(p-p0)<tol){

instead of :
if((p-p0)<tol){

will get you closer to where you want to go.
The reason is that all negative values are smaller than .001, so if the result of the function is a negative value (like in this case), you'll stop immediately.
Btw : this check :
if(i>N){

will never be true. You probably meant to use == or >= instead of >.

A: I think you simply don't have a situation in which the iterative algorithm is applicable. See here for some conditions. Your function doesn't have an attractive fixed point near 1.5, and the algorithm diverges.
But why the numerics: Your function is f(x) = x^3 - 4x - 10, so solving f(x) = x amounts to finding the zeros of f(x) - x, and there is only one real zero near 5.35. Howevever, f'(x) at that point is very large, so even there the iterative algorithm isn't usable.
A numeric root-finding algorithm may be a more appropriate approach.

A: fabs(p - p0) <= tol * fabs(p);

Is the correct formula for equal values. In case of special ranges you also have to care for NaN and Inf.
#include <limits>
#include <cfloat>

inline bool Equal(const double& x, const double& y)
{
  const int classX (_fpclass(x));

  if(classX != _fpclass(y)) {
    return false;
  }

  switch(classX) {
      case _FPCLASS_SNAN:
      case _FPCLASS_QNAN:
      case _FPCLASS_NINF:
      case _FPCLASS_NZ  :
      case _FPCLASS_PZ  :
      case _FPCLASS_PINF:
        return true;
        break;
      case _FPCLASS_NN  :
      case _FPCLASS_ND  :
      case _FPCLASS_PD  :
      case _FPCLASS_PN  :
      default:
        break;
  }

  return fabs(x - y) <= std::numeric_limits<double>::epsilon() * fabs(x);
}


text:
Q: Spring Boot API Gateway Unable to resolve name Api calls via gateway throws java.net.UnknownHostException even though I am able to hit the application directly with the given hostname
Spring Boot version : 2.4.2
Spring-cloud.version: 2020.0.1
Java version: 11
Note: Samething works with spring boot 2.3.8.RELEASE and cloud version: Hoxton.SR9 with Java 8
Logs:
2021-02-10 14:25:05.398 ERROR 12632 --- [ctor-http-nio-4] a.w.r.e.AbstractErrorWebExceptionHandler : [efcc81fd-3]  500 Server Error for HTTP GET "/sample-order-service/sample-order"

java.net.UnknownHostException: failed to resolve 'MY-COMPUTER-NAME' after 2 queries
    at io.netty.resolver.dns.DnsResolveContext.finishResolve(DnsResolveContext.java:1013) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
    |_ checkpoint ⇢ org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter [DefaultWebFilterChain]
    |_ checkpoint ⇢ HTTP GET "/sample-order-service/sample-order" [ExceptionHandlingWebHandler]
Stack trace:
        at io.netty.resolver.dns.DnsResolveContext.finishResolve(DnsResolveContext.java:1013) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.resolver.dns.DnsResolveContext.tryToFinishResolve(DnsResolveContext.java:966) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.resolver.dns.DnsResolveContext.query(DnsResolveContext.java:414) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.resolver.dns.DnsResolveContext.onResponse(DnsResolveContext.java:625) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.resolver.dns.DnsResolveContext.access$400(DnsResolveContext.java:63) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.resolver.dns.DnsResolveContext$2.operationComplete(DnsResolveContext.java:458) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:578) ~[netty-common-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.util.concurrent.DefaultPromise.notifyListeners0(DefaultPromise.java:571) ~[netty-common-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:550) ~[netty-common-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:491) ~[netty-common-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.util.concurrent.DefaultPromise.setValue0(DefaultPromise.java:616) ~[netty-common-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.util.concurrent.DefaultPromise.setSuccess0(DefaultPromise.java:605) ~[netty-common-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.util.concurrent.DefaultPromise.trySuccess(DefaultPromise.java:104) ~[netty-common-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.resolver.dns.DnsQueryContext.trySuccess(DnsQueryContext.java:201) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.resolver.dns.DnsQueryContext.finish(DnsQueryContext.java:193) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.resolver.dns.DnsNameResolver$DnsResponseHandler.channelRead(DnsNameResolver.java:1230) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103) ~[netty-codec-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.nio.AbstractNioMessageChannel$NioMessageUnsafe.read(AbstractNioMessageChannel.java:93) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:719) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) ~[netty-common-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.58.Final.jar:4.1.58.Final]
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.58.Final.jar:4.1.58.Final]
        at java.base/java.lang.Thread.run(Thread.java:834) ~[na:an]

A: Add this config to your microservice
eureka.instance.hostname=localhost

A: You can use " eureka.instance.prefer-ip-address=true " in application.properties file of all the microservices you are calling from api-gateway. Root cause is that your api-gateway is calling the microservices using username of the system which you need to call using ip address of the system.

A: This bugged me a lot and seemed to be a problem with the Netty and Spring Boot 2.4.x.
But I managed to fix this problem by using the reactor.netty.http.client.HttpClient with DefaultAddressResolverGroup.INSTANCE resolver.
So, when you create your WebClient bean, you can do the following
    @Bean
    @Primary
    public WebClient webClient() {
        HttpClient httpClient = HttpClient.create().resolver(DefaultAddressResolverGroup.INSTANCE);
        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();
    }

Explanation from the Netty documentation on why this works:

By default, the HttpClient uses Netty's domain name lookup mechanism that resolves a domain name asynchronously. This is as an alternative of the JVM's built-in blocking resolver.
Sometimes, you may want to switch to the JVM built-in resolver.

A: Add this property in your property file:
eureka.instance.hostname=localhost

A: I have had the same problem, I was able solve it changing de version of spring. Here my POM.
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo.microservices</groupId>
<artifactId>api-gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>api-gateway</name>
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>11</java.version>
    <spring-cloud.version>Hoxton.SR10</spring-cloud.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

A: Adding below property in API Gateway should address this. Its seems on windows platform discovery of the API gateway is not by default.
spring.cloud.discovery.enabled=true
Refer to the link below.
"https://stackoverflow.com/questions/65333590/spring-cloud-api-gateway-routing-not-working

A: I faced the same problem and found that this is because of the Spring and spring.cloud versions.
I have changed my pom.xml like below. In the parent I have commented 2.4.4 and used 2.2.6 and then in properties I have replaced the spring.cloud.version 2020.0.2 with
Hoxton.SR3 that's it then it started working.
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <!-- <version>2.4.4</version> -->
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <java.version>11</java.version>
    <!-- <spring-cloud.version>2020.0.2</spring-cloud.version> -->
    <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
</properties>

A: I have resolved this issue by the another way.
For those who encountered this issue with Spring Webflux + Spring Cloud do the following:

*

*You need to autowire DiscoveryClient discoveryClient;

*add this method into your service layer (where you using WebClient):

    private String getGatewayBaseUrl(ServiceInstance instance) {
        return instance.getUri().toString();
      }

*Get the url of gateway from the instance

    getGatewayBaseUrl(discoveryClient.getInstances("YOUR_GATEWAY_SERVICE_NAME").get(0)

Maybe this is not the best way to solve the problem, or maybe not the most correct one, but working


text:
Q: postgres get names of jsonb fields that comprise a unique index I'm using postgres 12.5. I've been researching answers on how to get the names of the columns that comprise a unique index. After combining a few answer on StackOverflow and elsewhere I came up with this solution
select i.relname as index_name,
    a.attname as column_name
from pg_class c
    inner join pg_index ix on c.oid=ix.indrelid
    inner join pg_class i on ix.indexrelid=i.oid
    inner join pg_attribute a on a.attrelid=c.oid and a.attnum=any(ix.indkey)
where c.oid='public.accounts'::regclass::oid
    and ix.indisunique is true
order by array_position(ix.indkey, a.attnum) asc

That solution worked great for unique indexes on traditional column types but didn't work for unique indexes on fields within a jsonb column type. See the example in this SQLFiddle
http://sqlfiddle.com/#!17/22f6d/4
In that SQLFiddle you can see how the table is created and two different unique indexes are created. You can see how the above query gets all regular column names that comprise a unique index but doesn't get the jsonb field name. But you can also see that the unique index on the jsonb field actually does its job.
How would I modify (or replace) the above query to return the names of the columns that comprise a compound unique index including jsonb fields?
p.s. Please don't suggest I move the field out of jsonb to a dedicated column. This is a legacy schema that I have inherited and need to make it work as-is

A: If you have an index on an expression, that expression is stored in the indexprs column of pg_index in the form of a parsed node tree.
To deparse that into an SQL string, you can use the pg_get_expr function:
SELECT i.relname AS index_name,
    coalesce(
       a.attname,
       pg_get_expr(ix.indexprs, ix.indrelid)
    ) AS indexed_expression
FROM pg_class c
    INNER JOIN pg_index ix ON c.oid = ix.indrelid
    INNER JOIN pg_class i ON ix.indexrelid = i.oid
    LEFT JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY (ix.indkey)
WHERE c.oid = 'public.accounts'::regclass
    AND ix.indisunique
ORDER BY array_position(ix.indkey, a.attnum) ASC;

    index_name     │    indexed_expression
═══════════════════╪═══════════════════════════
 accounts_pkey     │ id
 accounts_expr_idx │ (data ->> 'member'::text)
(2 rows)

But I don't think that there is a way to extract the column names used in that expression from the node tree in SQL.
The only possible path would be via pg_depend, where dependencies between an index and the columns of the underlying table are stored.


text:
Q: PDO Get Multiple Insert Ids  Running the following query using PDO (Actually, I use prepared statements but same problem)
INSERT INTO MyTable(MyField) VALUES('Row1'), ('Row2')
How can I get the Ids for the records relating to Row1 and Row2?
$db->lastInsertId() literally returns the last single Id.
Is it sufficient to take this last Id, subtract the # of records and assume that range covers all my records? can there be gaps/jumps. Is this query guaranteed to be atomic?

A: If you're using MyISAM tables then because of the table level locking mechanism it's only possible for you to get given a range of ids.
After reading http://dev.mysql.com/doc/refman/5.5/en/innodb-auto-increment-handling.html#innodb-auto-increment-traditional assuming you're using "traditional" innodb locking (which likely you are) then again for a single statement the set of IDs will be sequential.


text:
Q: В базу данных (при трёх значениях) сохраняет первое значение выводится 3 раза, второе 2 раза,третье 1 раз. Почему? Я делаю приложение заметок, и при нажатии кнопки Save ALL все значения сохраняются в базу данных.
Но как я говорил они сохраняются неправильно. На скриншотах всё будет понятно. Заранее СПАСИБО!

from pyclbr import Class
from tkinter.tix import TEXT
from PyQt5.QtWidgets import*
from PyQt5.QtGui import*
from PyQt5.QtCore import*
import sys
import sqlite3
conn = sqlite3.connect('todo.db')
cur = conn.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS todo_list(
list_item TEXT);
""")
conn.commit()
conn.close()

class Main_WINDOW(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Заметки')
        self.setGeometry(10,30,1920,1080)
        self.setStyleSheet('.Main_WINDOW {background-image: url(Background (1).jpg);}')
        self.button()

    def button(self):

        self.list_widget = QListWidget(self)
        self.list_widget.setGeometry(465, 510, 825, 304)
        self.list_widget.setStyleSheet("QListWidget{font-size: 54pt;}")

        self.text1 = QLineEdit(self)
        self.text1.setGeometry(500, 240, 780, 60)
        self.text1.setStyleSheet("QLineEdit{font-size: 28pt;}")

        self.text2 = QLineEdit(self)
        self.text2.setGeometry(585, 411, 720, 60)
        self.text2.setStyleSheet("QLineEdit{font-size: 28pt;}")

        instr = QLabel('Для редакта нажмите два раза по объекту', self)
        instr.setGeometry(650, 850, 780, 60)
        instr.setFont(QFont('Tekton Pro', 20, 23, True))

        btn_add = QPushButton('Add', self)
        btn_add.setGeometry(1300, 240, 125, 60)
        btn_add.setStyleSheet('.QPushButton {background-image: url(Window (2).jpg); color: white;}')
        btn_add.setFont(QFont('Arial', 22, 23, False))
        btn_add.clicked.connect(self.Add)

        btn_save = QPushButton('Save', self)
        btn_save.setGeometry(1325, 410, 105, 62)
        btn_save.setStyleSheet('.QPushButton {background-image: url(К.jpg); color: #ff4193;}')
        btn_save.setFont(QFont('Arial', 22, 30, False))
        btn_save.clicked.connect(self.Save)

        btn_saveALL = QPushButton('Save all', self)
        btn_saveALL.setGeometry(1530, 145, 170, 170)
        btn_saveALL.setStyleSheet('.QPushButton {background-image: url(SaveA.jpg); color: #000000;}')
        btn_saveALL.setFont(QFont('Nueva Std Cond', 31, 60, False))
        btn_saveALL.clicked.connect(self.SaveAL)

        self.get_items()

    def get_items(self):
        conn = sqlite3.connect('todo.db')
        cur = conn.cursor()
        cur.execute('SELECT * FROM todo_list')
        rows = cur.fetchall()
        conn.commit()
        conn.close()
        for row in rows:
            self.list_widget.addItem(str(row[0]))

    def Add(self):
        iteme = self.text1.text() #.text() Получение текста
        self.list_widget.addItem(iteme) #.addItem Добавление в список
        iteme = self.text1.setText("")# setText() -  доб. текста в QLineEdit

    def delite_item(self):
        clicked = self.list_widget.currentRow() #получение индекса текущей строки
        self.list_widget.takeItem(clicked)

    def redact(self, item):
        clicked = self.list_widget.currentRow()
        TEXT =  self.text2.setText(item.text())
        self.list_widget.takeItem(clicked)

    def Save(self):
        itema = self.text2.text()
        self.list_widget.addItem(itema)
        itema = self.text2.setText("")

    def SaveAL(self):
        conn = sqlite3.connect('todo.db')
        cur = conn.cursor()
        cur.execute("""DELETE FROM todo_list;""")
        items = []
        for i in range(self.list_widget.count()):
            items.append(self.list_widget.item(i))
            for item in items:
                cur.execute("""INSERT INTO todo_list (list_item) VALUES (:item);""",{'item':item.text()})
        conn.commit()
        conn.close()

if __name__ == '__main__':
    App = QApplication([])
    w = Main_WINDOW()
    w.show()
    App.exec_()


text:
Q: Using values from previously chained thenCompose lambdas in Java 8 The Java 8 coding style preferred by my colleagues is chaining asynchronous calls all the way through, e.g.
CompletionStage<E> someMethod() {
    return doSomething().thenCompose(a -> {
      // ...
      return b;
    }).thenCompose(b -> {
      // ...
      return c;
    }).thenCompose(c -> {
      // ...
      return d;
    }).thenApply(d -> {
      // ...
      return e;
    });
}

I have something like the above, but with an added challenge: I need to recall values retrieved within some of the lambdas, in later lambdas. For example,
CompletionStage<E> someMethod() {
    return doSomething().thenCompose(a -> {
      // ...
      Foo foo = fooDAO.getFoos(a);
      // ...
      return b;
    }).thenCompose(b -> {
      // ...
      return c;
    }).thenCompose(c -> {
      // ...
      Bar bar = barDAO.getBars(foo);
      // ...
      return d;
    }).thenApply(d -> {
      // ...
      return someResult(d, bar);
    });
}

When I declare Foo foo; and Bar bar; in the outside scope, I get errors about them not being final or effectively final. And I read about using a wrapper to make them effectively final, but it seems rather hacky to me to do this (I don't understand why that's allowed...)
I read that Java 8 didn't add support for tuples (though it considered BiVal, which maybe I could have used to pass to BiFunction lambdas). So I tried using pairs, e.g.
    return doSomething().thenCompose(a -> {
      // ...
      Foo foo = fooDAO.getFoos(a);
      // ...
      return new Pair<>(foo, b);
    }).thenCompose(fooAndB -> {

and then wherever I needed to recall foo,
      Foo foo = fooAndB.getKey();

But this feels so semantically wrong. Also, it doesn't work! I don't know why, because I thought a lambda parameter's scope is the same as its outside scope, and so all lambda parameters would be accessible from within later-chained lambdas.
What really is the scope of lambda parameters, and is there an idiomatic or at least semantically unoffensive way to do what I'd like to do while keeping the chaining?
Answers based on breaking the chain are fine as they may be useful for future viewers, but in my case, deviations from the dominant style in this repo may result in drawn out PR conversations and delayed approval, so I'd love a solution that preserves the chaining. Or, an explanation or demonstration as to how insane it would be to try to keep the chaining. Thank you!

A: Since you mention the coding style preferred by your colleagues, you probably already know the alternative of using nested calls instead:
CompletionStage<E> someMethod() {
    return doSomething().thenCompose(a -> {
        // ...
        Foo foo = fooDAO.getFoos(a);
        // ...
        CompletableFuture<B> resultB = ...;
        return resultB.thenCompose(b -> {
            // ...
            CompletableFuture<C> resultC = ...;
            return resultC;
        }).thenCompose(c -> {
            // ...
            Bar bar = barDAO.getBars(foo);
            // ...
            CompletableFuture<D> resultD = ...;
            return resultD.thenApply(d -> {
                // ...
                return someResult(d, bar);
            });
        });
    });
}

This immediately fixes your issue, at the cost of a bit less readable code. But this problem can easily be fixed by extracting some methods from your code:
CompletionStage<E> someMethod() {
    return doSomething()
            .thenCompose(this::processA);
}

private CompletionStage<E> processA(final A a) {
    // ...
    Foo foo = fooDAO.getFoos(a);
    // ...
    final CompletableFuture<B> result = ...;
    return result
            .thenCompose(this::processB)
            .thenCompose(c -> processCAndFoo(c, foo));
}

private CompletionStage<C> processB(B b) {
    // ...
    return ...;
}

private CompletionStage<E> processCAndFoo(final C c, final Foo foo) {
    // ...
    Bar bar = barDAO.getBars(foo);
    // ...
    final CompletableFuture<D> result = ...;
    return result
            .thenApply(d -> someResult(d, bar));
}

By doing this, you avoid nested lambdas (and respect the preferred code style of your colleagues), but you also gain in readability and testability since you now have several small methods that are easier to understand and unit test.

A: You can try this approach (I'm not necessarily an advocate of doing it this way but it does maintain the chain).  You create a POJO that contains all the arguments you will need for the chain and pass the same POJO down the chain.  The downside here is that it's kind of a pain to add additional methods to the chain, as you now have to also add a property to the argument class.
public class SomeMethodContext {

    private Object a;
    private Object b;
    private Object c;
    private Object d;
    private Object foo;
    private Object bar;

    // Getters and setters

}

// ...

CompletionStage<E> someMethod() {
    return doSomething().thenCompose(a -> {
      SomeMethodContext context = new SomeMethodContext();
      context.setA(a);
      // ...
      context.setFoo(fooDAO.getFoos(context.getA()));
      // ...
      context.setB(b);
      return context;
    }).thenCompose(ctxt -> {
      // ...
      ctxt.setC(c);
      return ctxt;
    }).thenCompose(ctxt -> {
      // ...
      ctxt.setBar(barDAO.getBars(ctxt.getFoo()))
      // ...
      ctxt.setD(d)
      return ctxt;
    }).thenApply(ctxt -> {
      // ...
      return someResult(ctxt.getD(), ctxt.getBar());
    });
}

A: As another alternative, you might also consider introducing EA Async on your project. This API provides async/await for Java, and is particularly neat for this kind of problem. Here I rewrote your code with EA Async:
CompletionStage<E> someMethodWithEAAsync() {
    final A a = await(doSomething());
    Foo foo = fooDAO.getFoos(a);
    // ...
    CompletableFuture<B> futureB = ...;
    final B b = await(futureB);
    // ...
    CompletableFuture<C> futureC = ...;
    final C c = await(futureC);
    // ...
    Bar bar = barDAO.getBars(foo);
    // ...
    CompletableFuture<D> futureD = ...;
    D d = await(futureD);
    return completedFuture(someResult(d, bar));
    // or alternatively
    return futureD.thenApply(d -> someResult(d, bar));
}

It looks really similar to synchronous code, but behind the scenes EA Async will transform this method in order to keep everything asynchronous. No need to worry about chaining anymore!


text:
Q: Uninstalling programs silently via CMD Is there a way I can uninstall programs without the graphical interface and doing it via CMD?

A: If you have PowerShell 3 (or higher) installed, you can issue a WMI call to get all programs named a certain thing (or 'like' a certain thing, to do wildcard searches), and then call the Uninstall method for each of them:
(Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name like '%Partial Name%'").uninstall()

A: If a program uses Windows Installer, you can use one of the following commands:
msiexec /q /x <ProductCodeGuid>
msiexec /q /x <PathToMsi>

However, you're likely have neither the product code nor the original MSI file used for installation.
Other than that, there is no generic uninstall command, since installers that do not make use of Windows Installer are "unknown" by the operating system. They might supply their own uninstall executable, but whether that executable includes a way to run it without GUI depends on the individual software package.

A: If you know where the MSI installer file is you can use:

Msiexec /uninstall Application.msi /quiet

A: You can invoke the correct uninstaller without knowing the GUID, etc. by using WMIC.
To see a list of the names of the programs as known internally by Windows:
wmic product get name

Look for your product name. It probably matches the one listed in the "Programs and Features" control panel, but not always.
Then you can use
wmic product where name="_my_product_name" call uninstall

to perform the uninstall, which AFAIK should be silent (it has been in my experience, but try it before you bet the farm on that. Silence may depend on how your installer/uninstaller was built).
See here for more:

*

*WMIC: the best command line tool you've never used (overview of WMIC with lots of cool commands described)

*Windows: Uninstall an Application from the Command Line (the specific recipe)

There's also reference documentation for WMIC on microsoft.com.

A: Every program that properly installs itself according to Microsoft's guidelines makes a registry entry in HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall. Usually, the key for the program will be its GUID, or else the name of the program. Within that key will be an entry called UninstallString. This contains the command to execute to uninstall the program.
If you already know ahead of time what you will be uninstalling, it should be easy enough to just put that in your batch file. It gets tricky when you try to automate that process though. You can use the reg command to get data from the registry, but it returns a lot of text around the actual value of a given key, making it hard to use. You may want to experiment with using VBscript or PowerShell, as they have better options for getting data from the registry into a variable.

A: Check this out, this is using a batch find the software's UninstallString registry key and then uninstall the software silently which is much more reliable compare to wmic I found.
https://community.spiceworks.com/topic/2143980-deploy-or-upgrade-java-8-via-shutdown-script-remove-old-javas
::It extracts software software GUID, then use the GUID to search the name and version
@echo off
setlocal ENABLEDELAYEDEXPANSION

set SoftwareName=Java 8
set NewVersion=8.0.1720.11
set x86GUID=HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
set x64GUID=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
set Installer=\\dc\sources\jre-8u172-windows-i586.exe REMOVEOUTOFDATEJRES=1 AUTO_UPDATE=0 EULA=0 NOSTARTMENU=1 SPONSORS=0 WEB_ANALYTICS=0 WEB_JAVA=1 WEB_JAVA_SECURITY_LEVEL=H /s
REM set Installer=d:\downloads\jre-8u172-windows-i586.exe REMOVEOUTOFDATEJRES=1 AUTO_UPDATE=0 EULA=0 NOSTARTMENU=1 SPONSORS=0 WEB_ANALYTICS=0 WEB_JAVA=1 WEB_JAVA_SECURITY_LEVEL=H /s

REM It's faster to first locate the software GUID, then search it's Name, Version & UninstallString
for /f "delims=" %%P in ('reg query "%x86GUID%" /s /f "%SoftwareName%" 2^>nul ^| findstr "HKEY_LOCAL_MACHINE"') do (
  echo %%P
  reg query "%%P" /v "DisplayVersion" 2>nul | findstr /r /c:"  %NewVersion%" >nul && (
    for /f "tokens=2*" %%A in ('reg query "%%P" /v "DisplayName" 2^>nul ^|findstr "DisplayName"') do echo %%B has already been installed
    for /f "tokens=2*" %%A in ('reg query "%%P" /v "DisplayVersion" 2^>nul ^|findstr "DisplayVersion"') do echo Version: %%B
    goto :EOF
  ) || (
    for /f "tokens=2*" %%A in ('reg query "%%P" /v "DisplayName" 2^>nul ^|findstr "DisplayName"') do echo Found other version %%B, upgrade in progress
    for /f "tokens=2*" %%A in ('reg query "%%P" /v "UninstallString" 2^>nul ^|findstr "UninstallString"') do (
      echo %%B | findstr /c:"MsiExec.exe"  >nul && (
        set MsiStr=%%B
        set MsiStr=!MsiStr:/I=/X!
        echo !MsiStr! /quiet /norestart
        !MsiStr! /quiet /norestart
        rem %Installer%
      ) || (
        echo None MsiExec Uninstall String %%B
        rem "%%B" /S
      )
    )
  )
)
if not defined MsiStr (
  echo %SoftwareName% not found, install it?
  rem %Installer%
)

endlocal

A: A VBScript script will help you to uninstall the require program.
To use this script you will require software name which is located in your registry.
Just enter the application name in the script and run it with admin privileges; it will uninstall the application. But this will only work for a window-based application; for standalone setup or apps which doesn't make an entry in the uninstall string of registry, the script will not work.
So in that case you will have to find another way to uninstall the application.
Code:
On error resume Next

Dim strName, WshShell, oReg, keyname

Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."

'=============================================
'Change the value here with DisplayName's value
strName = " "
'=============================================
Set WshShell = CreateObject("WScript.Shell")
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
strKeyPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
oReg.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubKeys
For Each subkey In arrSubKeys
    keyname = ""
       keyname = wshshell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" & subkey & "\DisplayName")
    If keyname = strName then
        i = subkey
    End If
Next

If i Then

    WshShell.Run "MSIEXEC.EXE /X " & i & " /QN", 1, True
End If

Set WshShell = Nothing
set ObjReg = Nothing

WScript.Quit

A: The correct answer is above, but for Windows X64 installs you will also need to check:
HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\


text:
Q: What is a RP Paket in a tcpdump log? I have a tcpdump log with the following entry:

14:53:31.428570 IP 10.4.65.65.16666 > 192.168.201.10.80: RP 587:687(100) ack 48545454154 win 0

My Problem is that i have never seen an RP paket before.. What does it mean?
Is it kind of a reset paket?
Thanks in advance!

A:
Flags are some combination of S (SYN),
  F (FIN), P (PUSH),  R  (RST),  W (ECN
  CWR)  or  E  (ECN-Echo),  or a single
  `.' (no flags).

© man tcpdump
So, here you have TCP packet with RST (which means that it actually is a reset packet) and PUSH flags set.

A: In network related situations I only know RP as "Rendevouz Point" in Protocol Independent Multicast (Sparse Mode) - PIM-SM.
Unfortunately I am not sure about what the packets would look like. You might want to compare the ports or take a decision based on the environment you recorded the tcpdump. (These packages are not that common AFAIK)


text:
Q: How to show/hide DIVs with jQuery I want to make a function to show and hide a div tag and hide all others:
function showPage(showdiv){
    $('#midRight').not(showdiv).hide();
    $(showdiv).show();
}

Link calling the function:

Show Page 1

Show Page 2

DIVs on page:

Content 1

Content 2

The function showPage ends up hiding every div within midRight, while on JSFiddle, the click event doesn't seem to be handled at all.
What is the correct way to show/hide a DIV with jQuery?

A: You could write you selector to hide all child div's of midRight, then show the div with the passed ID. No need to cast to a String, since that is what you are passing:
function showPage(showdiv){
    $('#midRight > div').hide()
    $(showdiv).show();
}

A: Fixed up some syntax errors. As the comments say, you're appending an empty string with the variable, just use the variable. Also, you need to tell the selector to select the children of the targetted container:
function showPage(showdiv){
    $('#midRight').children().not(showdiv).hide();
    $(showdiv).show();
}

Demo: http://jsfiddle.net/ACGMj/1/

A: DEMO
function showPage(showdiv){
    $(showdiv).show().siblings().hide();
}

Or, without using IDs:
DEMO
$('ul a').click(function() {
    var index = $(this).index();
    $('#midRight > div').hide().eq(index).show();
});

A: The fiddle isn't working because it can't find the function, it can't find the function because you specified the functions to be interpreted during onLoad.  To fix it, in the upper left of the jsFiddle, set the dropdown from onLoad to No wrap - in .
Here's a working version that doesn't use in-line events:
http://jsfiddle.net/gRDdC/

  Show Page 1

  Show Page 2

Content 1

Content 2

$(document).ready(function() {
    $('.nav-link').click(function(e) {
        e.preventDefault();
        $('#midRight > div').hide();
        $($(this).attr('href')).show();
    });
});


text:
Q: Converting $46°30'$ to radians
Question: $46°30'$ to radians

To convert
From relation $180°=\pi$
$$(46\times30/60)\times\frac{\pi}{180}=0.4012$$
I'm getting wrong answer

A: $$(46\color{red}+30/60)^\circ\times \frac{\pi}{180^\circ}=0.7069$$

A: It's a sum, not a product. $46^\circ$ $30'$  =$(46+30/60)^\circ$ and so
$$(46+30/60)\frac{\pi}{180}$$


text:
Q: Django 1.7 modelform_factory form is always invalid with factory_boy created model I'm using Django 1.7 and factory_boy to create some models. Here's the code:
In models.py:
class Address(models.Model):
    first_line = models.CharField(max_length=50, blank=True)
    second_line = models.CharField(max_length=50, blank=True)
    city = models.CharField(max_length=30, blank=True)
    state = models.CharField(max_length=2, blank=True)
    zipcode = models.CharField(max_length=5, blank=True)
    zipcode_ext = models.CharField(max_length=4, blank=True)

The associated factory in factories.py (same directory):
class AddressFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Address

    first_line = "555 Main St."
    second_line = "Unit 2"
    city = "Chicago"
    state = "IL"
    zipcode = "60606"
    zipcode_ext = "1234"

Now, given this code in the django shell:
>>> from models import Address
>>> from django.forms.models import modelform_factory
>>> AddressForm = modelform_factory(Address)
>>> from factories import AddressFactory
>>> a = AddressFactory.create()
>>> af = AddressForm(instance = a)
>>> af.is_valid()
False

For some reason, the call to is_valid seems to always return false, and I can't figure out why. There don't seem to any errors on the form, and clean(), clean_fields(), and validate_unique() all do not seem to raise errors on the instance.
Why does is_valid always return false?

A: This has nothing to do with factory_boy. Forms are always invalid if they don't have any data, which yours doesn't. The instance parameter is used to populate the form's initial data for display, and to determine the object ID for updating, but it isn't used to set that data on POST.
I'm not quite sure what you want to do with the form there, but you'd need to convert it to a POST dictionary and pass it to the form's data parameter for it to be valid.


text:
Q: How to execute socket.io endpoints sychronously My application is using socket.io, from what I gather, socket.io executes asynchronously. Most of the time this is not a problem, however there is a particular case where 2 users in my app may call the same socket endpoint at the same time, and this causes issues.
What I would rather have is for each socket endpoint to wait until the one before it finishes executing, before it gets executed. If they run asynchronously, I get unexpected results.
On the server I have the following...
// Establish a connection with a WebSocket.
io.on("connection", socket => {

  socket.on("add_song", async (data) => {
    PlaylistHandler.add_song(io, socket, data);
  });

...
...

add_song gets called at the same time by two different io connections (2 different users). I don't want the function PlaylistHandler.add_song to run in parallel for each so I tried using async/await...
await PlaylistHandler.add_song(io, socket, data);

That didn't solve anything because I suspect it is because there are two different io connections making the call.
Is there any way to make the socket call itself run sequentially rather than in parallel?

A: await doesn't block the event loop, so it indeed doesn't matter here. Both await PlaylistHandler.add_song will get executed in their respective io.on listeners in parallel.
Your best/easiest shot is to set a variable calculating = true at the beginning of your add_song, and to postpone any add_song if we are already doing one.
Hope this snippet will inspire you into achieving a workable solution:
let calculating = false;

function add_song(io, socket, data){
    if(calculating){
        setTimeout(function(){
            add_song(io, socket, data)
        }, 500); //depends on how often you want to check, reduce/increase timeout depending on how time-sensitive checking should be
        return;
    }
    calculating = true;

    //Do all your usual add_song processing

    //After final operation of add_song
    calculating = false;
}


text:
Q: Access K8S API from a pod I have a main pod that accesses and makes Kubernetes API calls to deploy other pods (the code similar below). It works fine. Now, I don't want to use the config file. I know it's possible with a service account. https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/. How do I configure a service account (e.g default service account) that allows my pod to access the APIs?
public class KubeConfigFileClientExample {
  public static void main(String[] args) throws IOException, ApiException {

    // file path to your KubeConfig
    String kubeConfigPath = "~/.kube/config";

    // loading the out-of-cluster config, a kubeconfig from file-system
    ApiClient client =
        ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();

    // set the global default api-client to the in-cluster one from above
    Configuration.setDefaultApiClient(client);

    // the CoreV1Api loads default api-client from global configuration.
    CoreV1Api api = new CoreV1Api();

    // invokes the CoreV1Api client
    V1PodList list = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
    System.out.println("Listing all pods: ");
    for (V1Pod item : list.getItems()) {
      System.out.println(item.getMetadata().getName());
    }
  }
}

A: The official Java client has example for in-cluster client example.
It is quite similar to your code, you need to use a different ClientBuilder:
ApiClient client = ClientBuilder.cluster().build();

and use it like this:
    // loading the in-cluster config, including:
    //   1. service-account CA
    //   2. service-account bearer-token
    //   3. service-account namespace
    //   4. master endpoints(ip, port) from pre-set environment variables
    ApiClient client = ClientBuilder.cluster().build();

    // set the global default api-client to the in-cluster one from above
    Configuration.setDefaultApiClient(client);

    // the CoreV1Api loads default api-client from global configuration.
    CoreV1Api api = new CoreV1Api();


text:
Q: Cancelling a logout and returning to a shell I don't actually want to do this; the Law of Unintended Consequences looms large over this idea. I'm just curious if the capability even exists. Similar functionality might be handy for some scripts as a break out step.
Suppose I want to write this into a ${HOME}/.logout file:
#! /bin/bash
cd /path/to/git/working/project
if [ "$( git status | wc -l )" -gt 5 ]
then
  echo "Check in your work before you leave."
  <STOP THE LOG OUT PROCESS AND RETURN TO THE SHELL PROMPT>
fi

How would I do that last bit? Would a break do it?

A: First configure a trap in the session for the exit behavior:
trap ~/.logout EXIT

If you want you can add this trap behavior to the bashrc, and then .logout script will be executed every time the users try to exit the shell.
And then you can write the .logout script:
#!/bin/bash
cd /path/to/git/working/project
if [ "$( git status | wc -l )" -gt 5 ]
then
  echo "Check in your work before you leave."
  bash
fi

Then when you try to exit the session the script .logout will be executed, and the bash will show up to check if the user does the right thing. If the users does whatever is right with git, the session will end normally.


text:
Q: How do I get rid of U+200B (Unicode zero width space) in my code? I have this piece of Python code:
# Subroutine to calculate VAT
def VAT(Total):
    return Total * 0.05

# Main program
Total = 100.12
ValueAddedTax = VAT(Total)
ToPay = Total + ValueAddedTax
print("Total £{:.2f} VAT £{:.2f} To pay £{:.2f}".format(Total, ValueAddedTax, ToPay))

When running this, I get:
    def VAT(Total):
                   ^
SyntaxError: invalid character in identifier

The reason is that the code contains U+200B ZERO WIDTH SPACE (UTF-8 encoding: E2 80 8B), as seen in the output of hexdump -C:

00000000  23 20 53 75 62 72 6f 75  74 69 6e 65 20 74 6f 20  |# Subroutine to |
00000010  63 61 6c 63 75 6c 61 74  65 20 56 41 54 e2 80 8b  |calculate VAT...|
00000020  0a 64 65 66 20 56 41 54  28 54 6f 74 61 6c 29 3a  |.def VAT(Total):|
00000030  e2 80 8b 0a 20 20 20 20  72 65 74 75 72 6e 20 54  |....    return T|
00000040  6f 74 61 6c 20 2a 20 30  2e 30 35 20 e2 80 8b 0a  |otal * 0.05 ....|
00000050  0a 23 20 4d 61 69 6e 20  70 72 6f 67 72 61 6d e2  |.# Main program.|
00000060  80 8b 0a 54 6f 74 61 6c  20 3d 20 31 30 30 2e 31  |...Total = 100.1|
00000070  32 e2 80 8b 0a 56 61 6c  75 65 41 64 64 65 64 54  |2....ValueAddedT|
00000080  61 78 20 3d 20 56 41 54  28 54 6f 74 61 6c 29 e2  |ax = VAT(Total).|
00000090  80 8b 0a 54 6f 50 61 79  20 3d 20 54 6f 74 61 6c  |...ToPay = Total|
000000a0  20 2b 20 56 61 6c 75 65  41 64 64 65 64 54 61 78  | + ValueAddedTax|
000000b0  e2 80 8b 0a 70 72 69 6e  74 28 22 54 6f 74 61 6c  |....print("Total|
000000c0  20 c2 a3 7b 3a 2e 32 66  7d 20 56 41 54 20 c2 a3  | ..{:.2f} VAT ..|
000000d0  7b 3a 2e 32 66 7d 20 54  6f 20 70 61 79 20 c2 a3  |{:.2f} To pay ..|
000000e0  7b 3a 2e 32 66 7d 22 2e  66 6f 72 6d 61 74 28 54  |{:.2f}".format(T|
000000f0  6f 74 61 6c 2c 20 56 61  6c 75 65 41 64 64 65 64  |otal, ValueAdded|
00000100  54 61 78 2c 20 54 6f 50  61 79 29 29 0a           |Tax, ToPay)).|
0000010d

I was wondering how to get rid of all of the zero width spaces.

A: You can get rid of those characters by replacing them with an empty string using sed:

$ sed 's/\xe2\x80\x8b//g' INPUTFILE >OUTPUTFILE

or, modifying the file in-place:

$ sed -i 's/\xe2\x80\x8b//g' INPUTFILE


text:
Q: How to edit the attributes/data of the various columns in windows explorer details view Running Windows 7 Pro
In windows explorer in details view there a multitude of pre defined columns that can be displayed
I'd like to know how to edit the data / attributes for the columns.
In particular the "Status" column.
So far the only column data I can edit is the "comments" column by placing a desktop.ini file in the folder and using infotip= to add comments to folders.
I've added the "status" column but there is no specified data to sort the folders by.
is editing the column data even possible?

A:
… in details view there a multitude of pre-defined columns
  that can be displayed …
  the only column data I can edit is the "comments" column …

Well, you're not being literal, are you?  Of course you know that you can change

*

*the Name, by renaming the file,

*the Type, by changing the file's extension,

*the Size and Date modified, by editing the file,

and you probably know that you can change the Attributes
(Read-only, Hidden, Compressed, and Encrypted) by going into "File Properties"
(right-click).
Other techniques:

*

*In Windows Explorer, you can change many column values (data attributes)
in the panel below the details area.
The fields that are available for change depend on the file type.
JPEG makes quite a few available:

*

*Date taken

*Rating

*Authors

*Camera maker

*Tags

*Title

*Comments

*Also, Microsoft Office gives you the ability to tweak a few attributes.
For example, in Word 2013,
if you click on the "File" tab, the "Properties" area:

lets you change

*

*Title

*Tags

*Comments

*… and, if you click on "Properties" → "Show Document Panel",

you get this:

which lets you change Title, Tags (labeled as "Keywords"), Comments, and also,

*

*Author

*Subject

*Category

*"Content Status" (as identified in Windows Explorer),
which is labeled "Status" in Word.

The actual Windows Explorer "Status" column is hard to pin down.
I found the Dell Data Protection PDF file, which suggests that,
when you are running the Dell Data Protection software,
it uses the "Status" column to indicate encryption status —
see paragraph 6 (spanning pages 4 and 5).

A: See the MSDN article, 'How to Customize Folders with Desktop.ini,' for how to edit the Status column:
https://msdn.microsoft.com/en-us/library/windows/desktop/cc144102(v=vs.85).aspx
Whatever you have next to 'InfoTip=' in the '[.ShellClassInfo]' section will display in the Status column.  I find Windows may take a few seconds to update it after you've changed it.
i.e.
[.ShellClassInfo]
InfoTip=Some sensible information.

A: You can't.
Status is a special column, and I can guess it's available only through programming a special folder view. The only one I can think of right now using that column is the Network Connection folder and that is not an actual folder, it's an application (control.exe - Control Panel) implementing these columns. If you right click an adapter, you'll have the status entry, and associated with it is the Status column in details view.
Other than that the only columns you can influence are the ones available for the files in question under Properties > Details. Some have more, others less, depending on file type. Some can be edited, other can't. For instance you won't be able to edit bitrate of an mp3 or video file, that's hardlinked to the file's contents.

A: Well, if anyone still needs it in 2022, at least in Windows 10 there are more than a dozen status properties, some with the same name and others only editable by the system (as is probably your case). Look for user editable properties in this list, or use a simple editor like ProperySystemView. Test by adding [{5CBF2787-48CF-4208-B90E-EE5E5D420294}] and Prop21=31,myproperty to your desktop.ini and enabling the display of the "description" property to Explorer.


text:
Q: What's the right way to check null or check exceptions in a chained statement in Java 8? For example for this code:
List<Class> classes =
        Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
              .map(className -> Class.forName(className))
              .collect(Collectors.toList());

This code runs fine now. but, assume we have a empty list in stream and we have tons of operations to the stream. It could get NullPointer exceptions and etc.
I find it's also hard to try-catch for this kind of statement.
What's the right way to handle exception for this?

A: You do not need to check for nulls. If you have an empty stream  all operations will be skipped:
Stream.of("hello")
      .filter(e => "world".equals(e)) // empties the stream
      .foreach(System.out::println); // no NullPointer, no output

Exception handling is possible in mapper:
    List<Class<?>> classes = Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
            .map(className -> {
                try {
                    return Class.forName(className);
                } catch (Exception e) {
                    throw new YourRuntimeException();
                }
            })
            .collect(Collectors.toList());

If you want exceptions to be ignored, then I suggest to map to Optionals.
    List<Class<?>> classes = Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
            .map(className -> {
                try {
                    return Optional.of(Class.forName(className));
                } catch (Exception e) {
                    return Optional.<Class<?>>empty();
                }
            })
            .filter(Optional::isPresent) // ignore empty values
            .map (Optional::get) // unwrap Optional contents
            .collect(Collectors.toList());

Please also have a look at How can I throw CHECKED exceptions from inside Java 8 streams? for a more detailed discussion about Class.forName in combination with java 8 streams.

A: Your question is a bit strange. You are claiming "This code runs fine now" whereas it should generate compile-time errors as you are not handling the checked exception declared by Class.forName. Further you are talking about empty lists, but in your code, no lists are involved. The same applies to your reference to NullPointerException as your code does not produce null at any place.
Most probably, you are talking about a code which catches the ClassNotFoundException and handles it by returning null. You should never do this. If you want to filter out failures, you may do it this way:
List<Class<?>> classes =
    Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
        .flatMap(className -> {
                try {
                    return Stream.of(Class.forName(className));
                } catch (ClassNotFoundException ex) {
                    // recommended: insert logging statement here
                    return Stream.empty();
                }
            })
        .collect(Collectors.toList());

This way, no element will be generated in the case of an exception and you don't have to do additional error handling downstream.

A: We can use try-with-resources also,
try(List<Class> classes = Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String"))
{
 List<Class> classes = Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
              .map(className -> Class.forName(className))
              .collect(Collectors.toList());
}

should add throws Exception to handle

A: I wasn't sure what you meant by "have a empty list in stream", but if you wanted to safely handle possibility of nulls in the Stream, you could use:
List<Class> classes =
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String", null)
    .filter(Objects::nonNull)
    .map(className -> {
      try {
        return Class.forName(className);
      } catch (ClassNotFoundException e) {
        System.out.println("No class found for: " + className);
        return null;
      }
    })
    .filter(Objects::nonNull)
    .collect(Collectors.toList());


text:
Q: Calling another JSF component from within custom component Is it possible to call another JSF component from within a custom component (as opposed to from a composite one)?
In particular, I'm looking to call the PrimeFaces message component from within another component's encodeEnd method
I was (naively) hoping for something like this:
@Override
public void encodeEnd(FacesContext context, UIComponent component)
        throws java.io.IOException {

    // Do stuff...

    // set up Message object
    // tell Message object the current component's id
    // render Message object
}

A: This should do:
import org.primefaces.component.message.Message;

// ...

Message message = new Message();
message.setParent(component);
message.setFor(component.getId());
message.encodeAll(context);


text:
Q: Ideal Dev Environment We have a linux based development server which we connect to from our windows based desktops (via ssh, scp, samba (mapped network drive), etc)
We're doing web development in perl, using apache2, mod_perl and MySQL, and our code base is under SVN source control.
What is the best way to allow all (currently 5) developers to develop independently?
In the past I've experienced running multiple instances of apache (achievable by hacking apache's source code and compiling)
But perhaps it would be better to use virtualisation and effectively give each developer their own development server (seems a bit overkill for web development though)
And if I only run one instance of apache, what's the best way to redirect incoming request to the correct codebase? port? sub-domain? IP address of client?
Thanks

A: Virtual machines are great for this sort of thing -- each developer can work without fear of getting in anyone else's way, and they can play around with system config changes to support new code if necessary.  Maintaining a production-like environment is easy with a master VM image or configuration management.

A: I would actually recommend using Apache's built in VirtualHost functions. By using name based virtual hosts you can run one instance of apache with completely different root codebases. They will have to have there own domain name per user but that shouldn't be an issue. You'll end up with something like:
mark.dev.example.com
james.dev.example.com
julia.dev.example.com

Since you already have an SVN server setup, you can create an independent repository for each user which they can have merged back into the main trunk when they finish working on there chunk. You can do SSL with these as well but if you want to use the same certificate it would need to either be a wildcard or include all of the additional addresses.
You can get more information about name based virtual hosts from the apache website for both version 1.x and version 2.x
You can also give your developers there own MySQL databases without running an additional database (I'm assuming your software can specify the name of the database it connects to not just the host).


text:
Q: Is log transforming square root transformed data a legitimate data transformation? Is it legitimate to do a "double transformation" on data? Specifically, log transforming data which has already been square root transformed, or conversely, square root transforming log transformed data? Does this even make sense?

A: Specifically, no.
Using natural logarithms for concreteness, and a generic variable $x$, the transformation $\ln \sqrt{x}$ is defined easily for positive numbers, but also can be seen to be just $\ln x^{0.5} = 0.5 \ln x$. Hence it has exactly the same effect in terms of effect on nonlinearity, asymmetry, lack of Gaussianity -- or whatever the transformation is designed to cure or improve -- as $\ln x$.
The transformation $\sqrt{\ln x}$ is defined easily for $x > 1$, but that seems also to be an artificial constraint. I'd be happy to learn of a rationale but I can't think of one. If you want a transformation that is stronger than the logarithm, the reciprocal is a simpler transformation to consider first. Reciprocals can be applied usefully so long as all values are positive or all values are negative.
Generally, there certainly are useful transformations that can be regarded as two-step functions, e.g. the logit $\ln [p / (1 - p)]$ or the angular transformation $\arcsin \sqrt{p}$. Here the domain is now proportions or probabilities $p$ and $0 < p < 1$ for logit and $0 \le p \le 1$ for angular. If a transformation is useful and natural enough, we tend to regard it as a function directly defined and named, so that (e.g.) statistical software commonly supplies logit functions for immediate use.
Some might want to underline that in some contexts complex results, i.e. those with real and imaginary parts, might be interesting or useful.

A: By the properties of logarithms, $$
y = \sqrt{x}
$$$$
\log(y)=0.5\log(x)
$$
So the net effect in something like a regression setting is to add a constant multiplier out front of the variable, i.e. to double the coefficient value of the log-square-root compared to simply taking the log.
But in other contexts, the effect won't matter at all! If you're using decision tree methods (e.g. random forest), and x > 0, then it won't even matter because these models are insensitive to monotonic transformations of the data.


text:
Q: Is it possible to load an app in parts, module by module, in angulardart If I want to load a small angulardart application at first and then later add modules, is it possible and how to do this.
For example:

*

*the first module will handle a websocket connection and login

*if login is successful, then load the main app

I'm just trying to get the big picture of the good practices of programming with angulardart.

A: Yes. Support for deferred module loading landed in Angular.dart (not releases yet at the moment of writing). An (unofficial) example can be found here: https://github.com/pavelgj/angular_deferred_sample

A: There is basic support for this in Dart. This is work in progress.
Some links where this functionality was mentioned:
- https://plus.google.com/+MatthewButler/posts/fHbbVuUhSni
- https://code.google.com/p/dart/issues/detail?id=17110
- http://blog.sethladd.com/2013/04/lazy-load-libraries-in-dart.html (somewhat dated)
- Code Splitting in Dart (also somewhat dated)
I don't know how this would work with angular.


text:
Q: Create a mdadm raid mirror of an existing lvm Hello I'm trying to figure out how I can create a pretty strange mdadm mirror of my lvm.
I have 4 disks, (sda,b,c,d).
Each disk has 2 partitions:
1Gb   - physical volume
500mb - Swap
My system lvm volume is currently made of two physical drives:
/dev/sda1 - 1Gb
/dev/sdb1 - 1Gb

Creating a 2Gb volume group for my root partition.
/dev/mapper/sys-root

What I want to do now is mirror my sys-root volume onto the other two disks.
I originally thought I would create mirror as:
 mdadm --create /dev/md0 --level=1 --raid-disks=4 missing missing /dev/sdc1 /dev/sdd1

Except I realise that all that would do is mirror the the contents of 1 drive onto the other 3.
What would be the method of mirroring /dev/mapper/sys-root onto my other 2 disks? Unfortunately doing this from scratch isn't an option as I need to use the existing file system.


text:
Q: Groupby multiple and count in Javascipt I am a new learner of Javascript. I have one question about the findIndex function.
Here I want to do the counting based on name_station and result_run.
const res = runs.reduce((acc, obj) => {
   const existingIndex = acc.findIndex(
        el => el.name_station === obj.name_station && el.result_run === obj.result_run
        )
   console.log(existingIndex)
   if (existingIndex > -1) {
       acc[existingIndex].count += 1
   } else {
       acc.push({
       station: obj.name_station,
       result: obj.result_run,
       count: 1
       })
   }
   return acc
}, [])

console.log(res)

Below is my data
const runs = [
  { name_station: 'fpc10', result_run: true },
  { name_station: 'fpc10', result_run: false },
  { name_station: 'fpc10', result_run: true },
  { name_station: 't10', result_run: true }
]

Here when I print the existingIndex, it return all -1 (which means the condition in el doesn't meet), but actually there are some matched value in my data.
My expected output would be like this
{ name_station: "fpc10", result_run: "true", count: 2 },
{ name_station: "fpc10", result_run: "false", count: 1 },
{ name_station: "t10", result_run: "true", count:1 }

Please help me to check that whether I did something wrong or missing something. Thanks in advance!

A: This line of your: el => el.name_station === obj.name_station && el.result_run === obj.result_run
should be: el => el.station === obj.name_station && el.result === obj.result_run
Just change the object fields :)


text:
Q: Every Holomorphic function on a Hartog's figure can be extended holomorphically to the while of $P^n$ Let $f$ be a holomorphic function on the Euclidean Hartog's figure that is $$H=\{(z,w)\in P^2 : 1 \gt|z| \gt q_1 \text{or} |w|  \lt q_2 \}$$ where $0 \lt q_i \lt 1$. I need to show that it has a holomorphic extension to whole of $P^2$ where $P^2$ is the unit polydisc.
For a fixed $z$, $$f(z,w)=\sum_{n=-\infty}^{\infty}a_n(z)w^{n}$$, where $$a_n(z)=\frac{1}{2\pi i}\int_{|\alpha|=r} \frac{f(z,\alpha)}{\alpha^{n+1}}d\alpha$$ where $0 \lt r \lt q_2$. Since $f$ depends continuously on $z$ (How do I prove it??) and $f(.,\alpha)$ is holomorphic in $|\alpha| \lt q_2$ we get $$\frac{\partial a_n(z)}{\partial \bar{z}}=\frac{1}{2\pi i}\int_{|\alpha|=r} \frac{\partial f(z,\alpha)}{\partial \bar{z}}.\frac{1}{\alpha^{n+1}}d\alpha=0$$ This shows that $a_n(z)$ is a holomorphic function of $z$ for $|z| \lt 1$.
Now for $|z| \gt q_1$, $a_n(z)=0$ for $n \le -1$ since $f$ is holomorphic in this region. Now since $a_n(z)$ is holomorphic , $a_n(z)=0$ for $n \lt -1$ in the whole $|z| \lt 1$.
 And we are done.
Is this alright??
Thanks for the help!!

A: You don't need the Laurent series expansion of $f$. Just extend your function via the Cauchy integral formula in the variable $z$ and show that the extension is complex-differentiable along each coordinate direction.


text:
Q: AppiumDriver MobileElement not found despite Existing ClassName can be found I've setup my AppiumDriver automation class and attempting simple tests, such as testing parallel, identifying MobileElements and general swipe commands are working. Working through the kinks, I'm getting an error stating that a MobileElement I initialized as part of the Class for a web page, such as Google main page on Chrome browser. I'm getting no such element even though the className undereneath the id I picked is correct. From my Appium Server, it's attempting to find by className (android.widget.EditText), but it can't find it. I've tried that class and ".//android.widget.EditText" and no luck.
I would use search by name, but no its not giving me alot of options. I even tried to do a List of WebElements, but it doesn't have a size bigger than zero.
Here is my page-object classes:
PageObject:
public class PageObject {
    public AppiumDriver<MobileElement> driver;
    protected WebDriverWait wait;
    Dimension size;

    public PageObject(AppiumDriver<MobileElement> driver){
        this.driver = driver;
        wait = new WebDriverWait(driver, 15);

        PageFactory.initElements(new AppiumFieldDecorator(driver), this);
    }

    @SuppressWarnings("rawtypes")
    public  void  swipeVertical  (double startPercentage, double finalPercentage, int duration) {
        size = driver.manage().window().getSize();
        int width = (int) (size.width/2);
        int startPoint = (int) (size.getHeight() * startPercentage);
        int endPoint = (int) (size.getHeight() * finalPercentage);
        new TouchAction(driver)
            .press(PointOption.point(width, startPoint))
            .waitAction(WaitOptions.waitOptions(Duration.ofMillis(duration)))
            .moveTo(PointOption.point(width, endPoint))
            .release()
            .perform();
    }

    @SuppressWarnings("rawtypes")
    public void swipeHorizontal (double startPercentage, double finalPercentage, int duration) {
        size = driver.manage().window().getSize();
        int height = (int) (size.height/2);
        int startPoint = (int) (size.getWidth() * startPercentage);
        int endPoint = (int) (size.getWidth() * finalPercentage);
        new TouchAction(driver)
            .press(PointOption.point(startPoint, height))
            .waitAction(WaitOptions.waitOptions(Duration.ofMillis(duration)))
            .moveTo(PointOption.point(endPoint, height))
            .release()
            .perform();
    }

(Update, not using PageFactory Approach this time): GoogleMainPage:
public class GoogleMainPage extends PageObject {

    //@AndroidFindBy(id="com.android.chrome:id/tsf")
    private MobileElement searchSection = driver.findElement(By.id("main"));

    //@AndroidFindBy(id="com.android.chrome:id/tophf")
    //private MobileElement searchCategories;

    public GoogleMainPage(AppiumDriver<MobileElement> driver) {
        super(driver);

    }

    public void searchQuery(String query) {

        MobileElement searchText = searchSection.findElement(By.className(".//android.widget.EditText"));
        MobileElement confirmSearch = searchSection.findElement(By.name("Google Search"));
        searchText.click();
        searchText.sendKeys(query);
        confirmSearch.click();
    }

}

The class where I'm performing my tests, after I setup my driver/drivers (generalWait() is just a Thread Sleep method):
@Test
    public void testActivation() {
        assertTrue(driver != null);

        pageObject = new PageObject(TLDriverFactory.getTLDriver());
        pageObject.driver.get("https://www.google.com");
        System.out.println(pageObject.driver.getCurrentUrl());
        assertTrue(pageObject.driver.getCurrentUrl().equals("https://www.google.com/"));

        try {generalWait(8000);} catch (InterruptedException e) {e.printStackTrace();}

        GoogleMainPage googleMainPage = new GoogleMainPage(TLDriverFactory.getTLDriver());

        googleMainPage.searchQuery("star wars");

        GoogleSearchResultsPage resultsPage = new GoogleSearchResultsPage(TLDriverFactory.getTLDriver());

        resultsPage.swipeVertical(0.20, 0.80, 2000);
    }

I'm currently running this with Maven, and io.appium java client is 6.1.0.
Is there something I'm missing while setting this up? Let me know if you need more info.

A: After more research on finding elements with Appium on Web Page browsers, if the web page you want to test through its elements has a desktop version, (and haven't switched to a non-webview context,) the desktop layout takes precedence over the mobile version of the web page.
The other half you have to consider is looking at the page source for the mobile web page version in case the AppiumDriver can't find the desktop element.  You can get find the Element setup in Mobile version with driver.getPageSource(). Now my GoogleMainPage class works when typing some text and selecting the Google Search Button
public class GoogleMainPage extends PageObject {

    private MobileElement searchSection = driver.findElement(By.id("tsf"));

    public GoogleMainPage(AppiumDriver<MobileElement> driver) {
        super(driver);

    }

    public void searchQuery(String query) {

        MobileElement searchText = searchSection.findElement(By.name("q"));
        MobileElement confirmSearch = searchSection.findElement(By.className("Tg7LZd"));
        searchText.click();
        searchText.sendKeys(query);
        confirmSearch.click();
    }

}


text:
Q: Help in solving a problem posed in International Mathematical Olympiad 1983 There was this question posed in IMO 1983:
"Can you choose 1983 pairwise distinct positive integers less than $10^5$, such that no three are in Arithmetic Progression?"
A close look at the sequence reveals the following things as mentioned in Problem Solving Strategies by Arthur Engel.

*

*When the numbers which belong to the sequence are written in the ternary system, all the digits in any of the number is either 0 or 1

*A further look suggests that the $nth$ term of the sequence has the same representation in the ternary system as $n$ has in the binary system
These help me to solve the original problem However, I am unsure as to how to prove the above two points
Any help please!!


text:
Q: How to specify in the intent-filter not to receive intents whose extra is null I have an Android application. For some reason, I want my application not to show in the chooser dialog when the intent's extra is null. Actually, the null extra will crash my application. Is there any way that I can specify such information in intent-filter?
Thanks a lot!

A: I think no. What about checking for null?
if( getIntent().getExtras() != null) {
  //your code
}


text:
Q: Why does java app crash in gdb but runs normally in real life? Attempting to run java app from gdb results in segfault, yet running app alone does not. This app is a .JAR which uses JOGL and a bit of memory-mapping to talk to the GPU.
Stacktrace below hints at some sort of memory access problem but I don't understand why it manifests in GDB but not in real life. Could there be some environment factor gdb needs to know to allow proper execution?
This issue persists between JVMs OpenJDK 6 and 7, as well as Oracle JRE 7. The oracle JRE runs a little farther into startup before segfault. All segfaults are otherwise consistent in occurrence and location between trials.
Segfault persists between GPUs and drivers(!!): nvidia, radeon, fglrx current and fglrx beta (14.xx). GDB will successfully attach to an already-running instance of my program, however it doesn't seem possible for gDEBugger to do this, which is ultimately what needs to work.
There is no intent to actually debug with gdb. Rather I am trying to use gDEBugger to perform OpenGL debugging. gDEBugger apparently relies on GDB as part of its backend, so if GDB fails, so does gDEBugger. This resulted in attempts to run gdb alone to isolate the issue.
gDEBugger output:
GDB String:  [Thread debugging using libthread_db enabled]
GDB String:  Using host libthread_db library  /lib/x86_64-linux-gnu/libthread_db.so.1 .
Thread Created: 140737353893632 (LWP: 3265)
Thread Created: 140737294624512 (LWP: 3266)
Thread Created: 140737293571840 (LWP: 3267)
Thread Created: 140737292519168 (LWP: 3268)
Thread Created: 140737155180288 (LWP: 3269)
Thread Created: 140737154127616 (LWP: 3270)
Thread Created: 140736913602304 (LWP: 3271)
Thread Created: 140736909629184 (LWP: 3272)
Thread Created: 140736908576512 (LWP: 3273)
Thread Created: 140736907523840 (LWP: 3274)
Thread Created: 140736906471168 (LWP: 3275)
Thread Created: 140736905418496 (LWP: 3276)
Thread Created: 140736278275840 (LWP: 3277)
Thread Created: 140736272963328 (LWP: 3278)
Thread Created: 140736271910656 (LWP: 3279)
Thread Created: 140736270857984 (LWP: 3280)
Thread Created: 140736269805312 (LWP: 3281)
Thread Created: 140737287657216 (LWP: 3285)
Thread Created: 140736261945088 (LWP: 3289)
GDB String:  [Thread 0x7fffb6e67700 (LWP 3289) exited]
Thread Created: 140736261945088 (LWP: 3290)
API Connection Established: gDEBugger Servers Manager
Thread Created: 140736234641152 (LWP: 3291)
GDB String:  [Thread 0x7fffb6e67700 (LWP 3290) exited]
API Connection Established: gDEBugger OpenGL Server
GDB String:  [Thread 0x7fffb77e8700 (LWP 3279) exited]
GDB String:  [Thread 0x7fffb76e7700 (LWP 3280) exited]
Debug String: gDEBugger OpenGL Server was initialized
Thread Created: 140736270857984 (LWP: 3292)
Thread Created: 140735692441344 (LWP: 3294)
Thread Created: 140735582430976 (LWP: 3295)
Thread Created: 140735574038272 (LWP: 3296)
OpenGL Render Context 1 Created
Signal: SIGSEGV
Process Exit

$ java -versionjava version "1.6.0_33"
OpenJDK Runtime Environment (IcedTea6 1.13.5) (6b33-1.13.5-1ubuntu0.14.04)
OpenJDK 64-Bit Server VM (build 23.25-b01, mixed mode)

$ gdb -version
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1

$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.1 LTS"

$ fglrxinfo
display: :0.0  screen: 0
OpenGL vendor string: Advanced Micro Devices, Inc.
OpenGL renderer string: AMD Radeon HD 5570
OpenGL version string: 4.4.12967 Compatibility Profile Context 14.20

$ gdb --args java -jar RunMe.jar
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from java...Reading symbols from /usr/lib/debug//usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java...done.
done.
(gdb) show configuration
This GDB was configured as follows:
   configure --host=x86_64-linux-gnu --target=x86_64-linux-gnu
             --with-auto-load-dir=$debugdir:$datadir/auto-load
             --with-auto-load-safe-path=$debugdir:$datadir/auto-load
             --with-expat
             --with-gdb-datadir=/usr/share/gdb (relocatable)
             --with-jit-reader-dir=/usr/lib/gdb (relocatable)
             --without-libunwind-ia64
             --with-lzma
             --with-python=/usr (relocatable)
             --with-separate-debug-dir=/usr/lib/debug (relocatable)
             --with-system-gdbinit=/etc/gdb/gdbinit
             --with-zlib
             --without-babeltrace
(gdb) run
Starting program: /usr/bin/java -jar RunMe.jar
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
process 6866 is executing new program: /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[New Thread 0x7ffff7fc4700 (LWP 6870)]
[New Thread 0x7ffff486c700 (LWP 6871)]
[New Thread 0x7ffff476b700 (LWP 6872)]
[New Thread 0x7ffff466a700 (LWP 6873)]
[New Thread 0x7fffea2d6700 (LWP 6874)]
[New Thread 0x7fffea1d5700 (LWP 6875)]
[New Thread 0x7fffea0d4700 (LWP 6876)]
[New Thread 0x7fffe9d0a700 (LWP 6877)]
[New Thread 0x7fffe9c09700 (LWP 6878)]
[New Thread 0x7fffe9b08700 (LWP 6879)]
[New Thread 0x7fffe9a07700 (LWP 6880)]
[New Thread 0x7fffe9906700 (LWP 6881)]
...
[New Thread 0x7fffe8110700 (LWP 6882)]
[New Thread 0x7fffe3169700 (LWP 6883)]
[New Thread 0x7fffe3068700 (LWP 6884)]
[New Thread 0x7fffe2f67700 (LWP 6885)]
[New Thread 0x7fffe2e66700 (LWP 6886)]
[New Thread 0x7fffe2d65700 (LWP 6887)]
[Thread 0x7fffe2d65700 (LWP 6887) exited]
[New Thread 0x7fffe2d65700 (LWP 6891)]
[Thread 0x7fffe2d65700 (LWP 6891) exited]
[New Thread 0x7fffe2d65700 (LWP 6895)]
[Thread 0x7fffe2d65700 (LWP 6895) exited]
[New Thread 0x7fffe2d65700 (LWP 6896)]
[New Thread 0x7fffe0efd700 (LWP 6897)]
libEGL warning: DRI2: failed to authenticate
[New Thread 0x7fff9799f700 (LWP 6898)]
[New Thread 0x7fff9719e700 (LWP 6899)]
[New Thread 0x7fff9699d700 (LWP 6900)]
[Thread 0x7fffe2d65700 (LWP 6896) exited]
[New Thread 0x7fffe2d65700 (LWP 6901)]
[New Thread 0x7fffe01ab700 (LWP 6902)]
[New Thread 0x7fff92f00700 (LWP 6903)]
[New Thread 0x7fff92dff700 (LWP 6904)]
[New Thread 0x7fff92cfe700 (LWP 6905)]
Setting up sound system...[New Thread 0x7fff92bfd700 (LWP 6906)]

[New Thread 0x7fff92afc700 (LWP 6907)]
[New Thread 0x7fff929fb700 (LWP 6908)]
[New Thread 0x7fff928fa700 (LWP 6909)]
[New Thread 0x7fff927f9700 (LWP 6910)]
[New Thread 0x7fff926f8700 (LWP 6911)]
[New Thread 0x7fff925f7700 (LWP 6912)]

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffe2f67700 (LWP 6885)]
0x00007ffff6b3a770 in acl_CopyRight ()
   from /usr/lib/jvm/java-6-openjdk-amd64/jre/lib/amd64/server/libjvm.so
(gdb) where
#0  0x00007ffff6b3a770 in acl_CopyRight ()
   from /usr/lib/jvm/java-6-openjdk-amd64/jre/lib/amd64/server/libjvm.so
#1  0x00007ffff6d51309 in Unsafe_CopyMemory2 (env=<optimized out>,
    unsafe=<optimized out>, srcObj=0x0, srcOffset=140737008618496, dstObj=0x0,
    dstOffset=140737006779392, size=1024)
    at /build/buildd/openjdk-6-6b33-1.13.5/build/openjdk/hotspot/src/share/vm/prims/unsafe.cpp:689
#2  0x00007fffed011790 in ?? ()
#3  0x0000000000000400 in ?? ()
#4  0x0000000000000000 in ?? ()
Warning: the current language does not match this frame.
(gdb) quit
A debugging session is active.

    Inferior 1 [process 6866] will be killed.

Quit anyway? (y or n) y

UPDATE: Switched to AMD CodeXL (basically the most recent form  of gDEBugger) and situation hasn't changed much.

A:
Why does java app crash in gdb but runs normally in real life?

Because it doesn't actually crash.
Java uses speculative loads. If a pointer points to addressable memory, the load succeeds. Rarely the pointer does not point to addressable memory, and the attempted load generates SIGSEGV ... which java runtime intercepts, makes the memory addressable again, and restarts the load instruction.
When debugging java programs, one has to generally do this:
(gdb) handle SIGSEGV nostop noprint pass

Unfortunately, if there is some JNI code involved, and that code SIGSEGVs, GDB will happily ignore that signal as well, resulting in the death of inferior (being debugged) process. I have not found an acceptable solution for that latter problem.

A: This was too long for a single comment on the accepted answer. Its basically links quoting for future reference (in case the pages vanish).
Some of you might find interest in part 2.
Table of contents

*Small trick

*Reasons / documentation

*Signal Chaining between native code and JVM

0. Small trick
A way around the issue could be to force the JVM to invoke a GDB console on error using the following JVM launch directive (see this blog page from Alexey Pirogov which can be also found in Oracle Java doc along with several usage example):
-XX:OnError="gdb - %p"

p will be replaced with the PID.
Example output from the blog post below. From what I read, it looks like the JVM is able to tell if a given SIGSEGV is Java-induced (and use it silently) or if it comes from a (C++) lib.
As far as I understand, this means the GDB session would start on a "legit" SIGSEGV occurrence, with a correct context.
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007f7348cba806, pid=10055, tid=10057
#
# JRE version: OpenJDK Runtime Environment (10.0.2+13) (build 10.0.2+13->    Ubuntu-1ubuntu0.18.04.4)
# Java VM: OpenJDK 64-Bit Server VM (10.0.2+13-Ubuntu-1ubuntu0.18.04.4, mixed mode, tiered, compressed oops, g1 gc, linux-amd64)
# Problematic frame:
# C  [libJNIDemo.so+0x806]  Java_jnidemo_JNIDemoJava_nativeCrash+0x1c
#
...
(gdb)

I found statements in this SO answer inconsistent with the Oracle Java doc description, but I would rather trust Oracle doc.
1. Reasons / documentation
I found this link https://www.ateam-oracle.com/why-am-i-seeing-sigsegv-when-i-strace-a-java-application-on-linux
It gives some insight for JVM behind-the-scene implementation.

The JVM is a multi-threaded process and so under the covers it's using signals to do OS level threading.

But the JVM is also doing a metric ton of other really clever stuff; for example in a regular C/C++ program [emphazis mine] hitting a NULL (a Zero) when you're expecting a pointer to some structure would cause your application to crash. That crash is actually, as you can probably guess by now, the OS sending your process a signal - specifically SIGSEGV. If your app didn't register a signal handler for that signal (and 99.5% of c/c++ apps out there don't) then the signal comes back up to the OS which then terminates the app and (usually) saves the memory state into a core file.

The JVM does register a signal handler for SIGSEGV and not just because it doesn't want to crash out when something goes wrong. The JVM registers a signal handler for SIGSEGV because it actually uses SIGSEGV and a bunch of other signals for its own purposes. [emphazis mine]

[...] And that's perfectly normal and completely safe.

The above link also points to this https://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-VM/html/signals.html

Signal

*

*

SIGSEGV, SIGBUS, SIGFPE, SIGPIPE, SIGILL
Used in the implementation for implicit null check, and so forth.

*

SIGQUIT
Thread dump support: To dump Java stack traces at the standard error stream. (Optional.)

*

SIGTERM, SIGINT, SIGHUP
Used to support the shutdown hook mechanism (java.lang.Runtime.addShutdownHook) when the VM is terminated abnormally. (Optional.)

*

SIGUSR1
Used in the implementation of the java.lang.Thread.interrupt method. (Configurable.) Not used starting with Solaris 10 OS. Reserved on Linux.

*

SIGUSR2
Used internally. (Configurable.) Not used starting with Solaris 10 OS.

*

SIGABRT
The HotSpot VM does not handle this signal. Instead it calls the abort function after fatal error handling. If an application uses this signal then it should terminate the process to preserve the expected semantics.

2. Quotes related to Signal Chaining
The Oracle link indicates that some actions can be taken to better handle the signals between JVM and non-java code. This is referred as signals chaining.
NOTE: I do not know if it works, and if it has any positive effect when using debugging a library called by a Java app.
I think it won't help at intercepting the "right" signal during a GDB session. But maybe with custom handler code + breakpoint it could?
From my understanding, it seems suited for a native application that would embbed a JVM, not a JVM app that embbeds a native library. I keep quotes there for completness
Quoting:

If an application with native code requires its own signal handlers, then it might need to be used with the signal chaining facility.

An application can link and load the libjsig.so shared library before libc/libthread/libpthread. This library ensures that calls such as signal(), sigset(), and sigaction() are intercepted so that they do not actually replace the Java HotSpot VM's signal handlers if the handlers conflict with those already installed by the Java HotSpot VM. Instead, these calls save the new signal handlers, or chain them behind the VM-installed handlers. During execution, when any of these signals are raised and found not to be targeted at the Java HotSpot VM, the pre-installed handlers are invoked.

The proposed procedure:

Perform one of these two procedures to use the libjsig.so shared library.

*

*Link it with the application that creates/embeds a HotSpot VM [remark: so this is not relevant for a library loaded from a Java app ...] , for example:
cc -L libjvm.so-directory -ljsig -ljvm java_application.c

*Use the LD_PRELOAD environment variable, for example [see https://stackoverflow.com/questions/426230/what-is-the-ld-preload-trick]:
export LD_PRELOAD=libjvm.so-directory/libjsig.so; java_application (ksh)

setenv LD_PRELOAD libjvm.so-directory/libjsig.so; java_application (csh)

The interposed signal(), sigset(), and sigaction() return the saved signal handlers, not the signal handlers installed by the Java HotSpot VM and which are seen by the operating system.
Note that SIGUSR1 cannot be chained.

1


text:
Q: "None" em vez de [1,1,1,1] Eu estou fazendo um problema que funciona assim: Por exemplo, suponha que um time de 4 vendedores de telemarketing deve fazer 6 ligações, cujos tempos sejam 5, 2, 3, 3, 4, 9. Como inicialmente nenhum vendedor está ocupado, o primeiro vendedor fará a ligação de 5 minutos, o segundo vendedor a ligação de 2 minutos e os vendedores de número 3 e 4 farão ligações de 3 minutos. Como o segundo vendedor terminará a sua ligação antes dos demais, ele fará a quinta ligação, de 4 minutos e, por fim, o terceiro vendedor (cujo tempo é igual ao do quarto vendedor, mas o seu número de identificação é menor) fará a sexta ligação, de 9 minutos.
A função tem que retornar uma lista com o número de ligações que cada vendedor fez. No exemplo acima, teria que retornar [1,2,2,1].
Meu código está por enquanto só avaliando se o número de vendedores é igual ao número de ligações ou maior. Porém, estou printando um exemplo em que esse número é igual, e ele está retornando "None" em vez de [1,1,1,1].
def ligacoes(n,l):
"Retorna uma lista que contem quantas ligacoes cada vendedor fara, seguindo as regras"
resultado = []
#v = numero de identificacao dos vendedores
    if n == len(l):
        for n in range(len(l)):
            resultado = resultado + [1]
    if n > len(l):
        for n in range(len(l)):
            resultado = resultado + [1]
        resultado = resultado + [0]

print ligacoes(4,[3,3,4,5])