text:
Q: How to check columns with different value but same category I have two tables in my database.
I want to update value in one table retrieved from another table with condition on columns having different values.
Table 1
Shape     Rate
-------
Round
Heart
Oval

Table 2
Shape     Rate
-------
BR     2100
PS    2500

now i want to update Rate value in able 1 from Table 2 where Round means BR and Rest all means PS
How can I join these two tables using these values?
I am using oracle database.

A: If I understand correctly, you want to choose the appropriate row in table2 to update table1.
Given your sample data, you can use a correlated subquery:
update table1 t1
    set rate = (select t2.rate
                from table2 t2
                where (t2.shape = 'BR' and t1.shape = 'Round') or
                      (t2.shape = 'PS' and t1.shape <> 'Round')
               );

You should really fix your data.  Two columns called shape should really contain the same values.

A: merge is one of the ways:
merge into table1 tgt
using table2 src
on (tgt.shape = 'Round' and src.shape = 'BR' or tgt.shape <> 'Round' and src.shape = 'PS')
when matched then update set rate = src.rate

dbfiddle demo

A: Try this-
UPDATE TABLE_1
SET RATE = (
    CASE
        WHEN SHAEPE = 'Round' THEN (SELECT RATE FROM TABLE_2 WHERE SHAPE = 'BR')
        ELSE (SELECT RATE FROM TABLE_2 WHERE SHAPE = 'PS')
    END
)


text:
Q: Need help for a 3x3 tic-tac-toe game's design. I can't get rid of some space in CSS The design goal would be just to perfectly fit all div.tile into the div#gameField. My jQuery works fine, but than I got this CSS mess. Please tell me where the unwanted space, margin or padding comes from, because I have no more idea. I don't think it's the cause, but I use this one normalize.css too.
HTML5:
<!DOCTYPE html>

        <title>Tic Tac Toe</title>
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/style.css">

Tic Tac Toe

CSS3:
body {
    background-color: black;
    color: lightgrey;
    text-align: center;
}

#gameField {
    margin: 10px auto 10px auto;
    width: 300px;
    height: 300px;
    background-color: white;
    border: 5px solid darkgrey;
    border-radius: 10px;
    padding: 0 0 0 0;
}

#gameField .tile {
    width: 100px;
    height: 100px;
    border: 1px solid lightgrey;
    background-color: white;
    display: inline-block;
    border-radius: 10px;
}

A: I think you need to increase 300px width from 302px because border takes space.  Now your border is 1px therefore it take space inside. Hope it will fix your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to execute RSeval() in remotely connected client in R I was executing RSeval(c,"4+5"); and encountered :

Error in RSeval(c,"4+5") : remote evaluation failed

in a remote machine connected to a linux server which is running daemon Rserve, where c is connection object. The connection was successful though.
Please share your insights.Thanks in advance

A: That could be many things, e.g. if Rserve requires authentication. If that's the case, you can use RS.connect and RS.login from the more modern implementation of RSclient (see http://cran.r-project.org/web/packages/RSclient/RSclient.pdf).


text:
Q: SQL - How to get a range of timestamps using BETWEEN (mysql)? So for example, if I had two tables, communication and movement that both have a columns named ID and timestamp, and I had a query that generally looked something like this:
SELECT * FROM movement m
JOIN communication c
ON m.ID = c.ID
WHERE m.timestamp <= c.timestamp
ORDER BY abs(TIMESTAMPDIFF(second,ctstamp,m.timestamp))
LIMIT 1;

This finds the closest communication timestamp for a given movement timestamp when m.timestamp <= c.timestamp, that is when the movement timestamp is less than the communication timestamp. But that leaves out all of m.timestamp >= c.timestamp.
What I want to do is create a range of like 10 seconds on either side, so that it would be:
WHERE m.timestamp BETWEEN c.timestamp-10 secs AND c.timestamp+10 secs

so if the communication timestamp was '2012-03-02|09:02:30', then it would be:
WHERE m.timestamp BETWEEN '2012-03-02|09:02:20' AND '2012-03-02|09:02:40'

So how would I implement this?
Any help would be greatly appreciated, thanks!!
EDIT
In the end, I used this:
WHERE m.timestamp BETWEEN TIMESTAMPADD(SECOND,-10,c.timestamp)
AND TIMESTAMPADD(SECOND,10,c.timestamp);

A: Just use the interval keyword:
WHERE m.timestamp BETWEEN c.timestamp - interval 10 second AND
                          c.timestamp + interval 10 second


text:
Q: hibernate spatial 5 - Postgis2.2 : Query issues Just started with postgis and hibernate statial and I'm gettin some issues making queries.
Goal : Get a museum from a (its) geometry type object
In my DB I got this column:
name: geom
type: geometry(Point,4326))
that contains something like: 0101000020E6100000004C8E1516D(...)

for each museum

Then, I've a museum class with:
@Column(name = "geom", columnDefinition = "geometry(Point,4326)")
private Geometry           geometry;

And here's my query:
WKTReader fromText = new WKTReader();
        try {
            //LON and LAT are the museum's coordinates
            Geometry geom = fromText.read("POINT("+lon+" "+lat+")");
            Session hibernateSession = getCurrentSession();

            Museum result = hibernateSession
                    .createQuery("from Museum where geometry = :geometry")
                    .setParameter("geometry", geom).uniqueResult();
            return result;

        } catch (ParseException e) {
            (...)
        }

But when I try to execute it, I got this Error:
ERROR: operator is not unique: geometry = bytea
Indice : Could not choose a best candidate operator. You might need to add explicit type casts.

So I was thinking, maybe Geometry from hibernate and Geometry from Postgis aren't the same?
Any idea on how I could make it work?
Thanks!

A: I found the problem.
First I'd to make sure I'd the postgis dialect on my .properties file.
Added this Setter to have same SRID
geom.setSRID(4326);

Then I changed my query to:
.createQuery("from Museum where equals(geometry, :geometry) = true")

And also changed my db class to:
@Column(name = "geom", columnDefinition = "Geometry")

Works perfectly now. This might help someone with the same problem...
Have fun

A: I was able to store 'geometry' data in postgis table using hibernate.
my pom.xml
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-spatial</artifactId>
            <version>5.4.2.Final</version>
        </dependency>

Hibernate Entity:
 @Entity
 public class XYZ {

  @EmbeddedId
  private Key id;
  @Column(columnDefinition = "Geometry")
  private Point startLoc;
  @Column(columnDefinition = "Geometry")
  private Point endLoc;
 }

DAOImpl:
    Point start = new GeometryFactory().createPoint(newCoordinate(151.203446,
             -33.867347, 1550285443));
    start.setSRID(4283);
    Point end= new GeometryFactory().createPoint(new Coordinate(151.203446,
    -33.867347, 1550285443));
    end.setSRID(4283);
    summary.setId(key);
    try {
        summary.setStartLoc( start);
        summary.setEndLoc( start);
    } catch (Exception e){
    }
    iSaferJourneySummaryDAO.save(summary);
  }

*

*An important point in application.properties:
spring.jpa.properties.hibernate.dialect=org.hibernate.spatial.dialect.postgis.PostgisDialect
PostGIS Column type : geometry


text:
Q: An inequality about suprema and contraction function Let $T\subset \mathbb R^2$ be a bounded subset and $\phi:\mathbb R \to \mathbb R$ be a contraction (namely $|\phi(x)-\phi(y)|\le |x-y|$ for all $x,y$). I want to prove ($t=(t_1,t_2)$ below)
$$\sup_{t\in T}(t_1+\phi(t_2))+\sup_{t\in T}(t_1-\phi(t_2))\le
\sup_{t\in T}(t_1+t_2)+\sup_{t\in T}(t_1-t_2)$$
Basically one need to show for all $(t_1,t_2)$ and $(t_1',t_2')$, one has
$$t_1+\phi(t_2)+t_1'-\phi(t_2')\le RHS.$$
I got stuck from here. If $t_2>t_2'$ and $\phi(t_2)>\phi(t_2')$ then we are good since $t_1+\phi(t_2)+t_1'-\phi(t_2')\le t_1+t_2+t_1'-t_2'.$

A: $$t_1+\phi(t_2)+t_1'-\phi(t_2') \leq t_1+t_1'+|t_2-t_2'|.$$ Suppose $t_2 \geq t_2'$. Then $t_1+\phi(t_2)+t_1'-\phi(t_2') \leq (t_1+t_2)+(t_1'-t_2') \leq $ RHS.  If $t_2 < t_2'$ then $t_1+\phi(t_2)+t_1'-\phi(t_2') \leq (t_1-t_2)+(t_1'+t_2') \leq $ RHS.


text:
Q: Label end of ggplot color bar, even if no data have that value I am trying to a color scale where I label all of the breaks, including the first and last one.
irisJ <- iris
irisJ$Hour <-  sample(0:23, dim(iris)[1], replace = TRUE)
ggplot(irisJ, aes(x = Petal.Length, y = Petal.Width, fill = Hour)) + geom_point(shape = 21, size = 2) +
  scale_fill_gradientn(name = "Hour",breaks = c(0, 6, 12, 18, 24), labels =  c("0", "6", "12", "18", "24"), colors = c("black", "blue", "white", "orange", "black"))

I realize there are no hour 24s in my data set, but I'd really like to plot that 24 at the top of my color bar so that readers can see and understand that the color bar is circular and both 0 and 24 are the darkest black. I know I could stop things at 23, but then the color bar will be a little off center.
Any suggestions?

A: You can set limits :
library(ggplot2)

ggplot(irisJ, aes(x = Petal.Length, y = Petal.Width, fill = Hour)) +
  geom_point(shape = 21, size = 2) +
  scale_fill_gradientn(name = "Hour",
                       breaks = c(0, 6, 12, 18, 24),
                       labels = c("0", "6", "12", "18", "24"),
                       colors = c("black", "blue", "white", "orange", "black"),
                       limits = c(0,24))


text:
Q: Is it good to use rename object key in function parameters? Im quite new to Javascript. When im trying to learn the destructuring, i accidentially found out that i can rename the variable and use the old one as linking word to make the function easier to read (for me).
function getWords({ beginWith: character, from: text }) {
    return text.split(" ").filter(word => word.startsWith(character));
}

let msg = "Hello world.";
let words = getWords({ beginWith: "H", from: msg });
console.log(words);

However, I wonder if this has any side effects to the program or not and should I continue to use it?


text:
Q: Configuring CentOS apache server to default to a specific port for ExpressJS and Node Completely new to Linux and virtual private servers so please bear with me.
I have a webapp built on ExpressJS and NodeJS that runs on port 5000 of my server, accessible via web by typing: http://00.000.000.000:5000. When you go to my non-port IP address (http://00.000.000.000) it shows the CentOS Apache setup welcome page.
I've tried running my Express app on port 80, but I get an Address In Use error.
What do I have to do to set up CentOS so that accessing its IP address at 00.000.000.000 loads up my Express app? I've tried adding port 5000 to listeners in my /etc/httpd/conf/httpd.conf file but this did nothing.

A: You got the Address In Use error because Apache is already listening on port 80.
If you want to access your Express app throught port 80, then you have to shutdown Apache and run your app on port 80.


text:
Q: How to write presend script in declarative jenkins pipeline I am trying to send HTML file in email body itself (not attachment). I have written Jenkins declarative pipeline as follows
post {
        always {
            presendScript: "def reportPath=build.getWorkspace().child("target/serenity-summary.html")
            msg.setContents(reportPath.readToString(), "text/html")"
            emailext attachmentsPattern: "Serenity_Test_Results${env.BUILD_NUMBER}.zip" ,
            body: "${currentBuild.currentResult}: Job ${env.JOB_NAME} build ${env.BUILD_NUMBER}  More info at: ${env.BUILD_URL}Unzip the attached document and click on index.html to view complete test results",
            subject: "API Testing: Jenkins Job Results - Build # ${env.BUILD_NUMBER} - Failed",
            mimeType: 'text/html',to: "xyz@abc.com"
            }

}

I am getting error as follows
WorkflowScript: 30: expecting anything but ''\n''; got it anyway @ line 30, column 102.
   target/serenity-summary.html")
                                 ^

1 error

I need to attach the HTML file to email body itself and I need proper presend script in post section.

A: I think you made a wrong usage of pipeline step emailext. You can try as following.
post {
  always {

    emailext(
        to: "xyz@abc.com",
        mimeType: 'text/html',
        attachmentsPattern: "Serenity_Test_Results${env.BUILD_NUMBER}.zip",
        subject: "API Testing: Jenkins Job Results - Build # ${env.BUILD_NUMBER} - Failed",
        presendScript: 'def reportPath=build.getWorkspace().child("target/serenity-summary.html");msg.setContents(reportPath.readToString(), "text/html")',
        body: "${currentBuild.currentResult}: Job ${env.JOB_NAME} build ${env.BUILD_NUMBER}  " +
              "More info at: ${env.BUILD_URL}Unzip the attached document and click on index.html to view complete test results"

    )
  }
}


text:
Q: Using fabric8io docker-maven-plugin with podman, mvn docker:build causes IO-Exception I'd like to use the docker-maven-plugin (0.33.0) with podman (2.0.6). According to this issue this should be possible - at an experimental stage. Here is, what I did.
Set an alias for docker
alias docker=podman

Start podman REST service
podman system service -t 0 &

Set DOCKER_HOST to the socket file
unix:/run/user/7001/podman/podman.sock

Try to build an image from a dockerfile
mvn docker:build

And get:
[INFO] Building tar: /[...]/tmp/docker-build.tar
[INFO] DOCKER> [myapp:latest] "myapp": Created docker-build.tar in 918 milliseconds
Sep 02, 2020 2:39:24 PM org.apache.http.impl.execchain.RetryExec execute
INFO: I/O exception (jnr.enxio.channels.NativeException) caught when processing request to {}->unix://127.0.0.1:1: Connection reset by peer
Sep 02, 2020 2:39:24 PM org.apache.http.impl.execchain.RetryExec execute
INFO: Retrying request to {}->unix://127.0.0.1:1
Sep 02, 2020 2:39:25 PM org.apache.http.impl.execchain.RetryExec execute
INFO: I/O exception (jnr.enxio.channels.NativeException) caught when processing request to {}->unix://127.0.0.1:1: Connection reset by peer
Sep 02, 2020 2:39:25 PM org.apache.http.impl.execchain.RetryExec execute
INFO: Retrying request to {}->unix://127.0.0.1:1
Sep 02, 2020 2:39:25 PM org.apache.http.impl.execchain.RetryExec execute
INFO: I/O exception (jnr.enxio.channels.NativeException) caught when processing request to {}->unix://127.0.0.1:1: Connection reset by peer
Sep 02, 2020 2:39:25 PM org.apache.http.impl.execchain.RetryExec execute
INFO: Retrying request to {}->unix://127.0.0.1:1
[ERROR] DOCKER> Unable to build image [myapp] : Connection reset by peer [Connection reset by peer]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE

It seems, that it is not a permission problem. I'm able to connect to the socket with curl and with the same user
curl -i --unix-socket /run/user/7001/podman/podman.sock http://localhost/info
... 200 OK ... and json payload

Any idea what possibly goes wrong in my setup?


text:
Q: Plotting x axis HH:mm:SS for POSIXct The code below is not being coverted to new york time. Any idea why? I see that it works in the posted answer but that code on my machine doe snot change the time.
 time = as.POSIXct(c("2016-06-30 15:20:23 GMT","2016-06-30 15:20:25 GMT","2016-06-30 15:20:27 GMT"),tz = "GMT")
 attr(time, "tzone") <- "America/New_York"
 #time = as.POSIXct(format(time, tz="America/New_York"),tz ="America/New_York")
 class(time)
 value = c(10,11,12)
     category = c(0,1,0)
     dat = data.frame(time = time, value = value, category = category)
     dat
                 time value category
1 2016-06-30 11:20:23    10        0
2 2016-06-30 11:20:25    11        1
3 2016-06-30 11:20:27    12        0

dat shows 11 as the hour but the plot below still shows the hour being 15?
 str(dat)
 library(ggplot2)
 ggplot(dat, aes(x=time, y = value, group = 1 )) +
   geom_point(aes (color = as.factor(category)) ) +geom_line()  + scale_x_datetime(date_labels = "%H:%M:%S")

It wasn't converting to NY time because the scales package was out of date

A: To set the timezone, use the tz = argument to as.POSIXct(). Your input is in "GMT" so we can tell R that's the case. To convert to another timezone, set the attribute tzone appropriately.
To scale the x-axis as date/time, use scale_x_datetime() with appropriate format codes.
time = as.POSIXct(c("2016-06-30 15:20:23 GMT",
                    "2016-06-30 15:20:25 GMT",
                    "2016-06-30 15:20:27 GMT"), tz = "GMT")
attr(time, "tzone") <- "America/New_York"

value = c(10,11,12)
category = c(0,1,0)
dat = data.frame(time = time, value = value, category = category)

library(ggplot2)
ggplot(dat, aes(x = time, y = value, group = 1)) +
  geom_point(aes(color = as.factor(category))) +
  geom_line() +
  scale_x_datetime(date_labels = "%H:%M:%S %Z")


text:
Q: Defining prototype functions for a class inside IIFE, while forcing "new" Consider the following code:

var a = (function()
{
  function a(str)
  {
    if(!(this instanceof a))
      return new a(str);

    console.log('a created with str: ' + str);
  }

  a.prototype.b = function()
  {
    console.log('a.b called');
  }

  return a;
})();

console.log(a);
a('asd');
a.b();

First, the IIFE's execution defines the class a, with a prototype method b. It then returns the constructor for the class, which is stored in var a. This is confirmed by the fact that console.log(a); displays the code for the constructor in the console, and a('asd'); correctly results in a log message saying a created with str: asd.
What I don't understand is why does the line a.b(); result in an Uncaught TypeError: a.b is not a function error? Why isn't the a.prototype definition carrying over to var a? And how can I get it there?

A:
why does the line a.b(); result in an Uncaught TypeError: a.b is not
  a function

It is because the inner a function is only executed on the line
a('asd');

but this line returns a reference to the new a instance which you never store, so you have no access to a prototype methods.
Look at the below modified snippet.

var a = (function()
{
  function a(str)
  {
    if(!(this instanceof a))
      return new a(str);

    console.log('a created with str: ' + str);
  }

  a.prototype.b = function()
  {
    console.log('a.b called');
  }

  return a;
})();

console.log(a);
let c = a('asd'); // Here a holds a reference to inner a and inner a is now called, prototype b added
// a.b(); error, there is no b of (outer) a
c.b(); // This is now OK


text:
Q: displaying mysql column names in an array along with its data I am trying to fetch records from MySql and display them in an array along with column headers using PDO, reason I am doing this is because i want to export them in an excel and I am using php-excel
right now the following code displays the records perfectly fine in an array and I am able to export them just fine
    while ($row[] = $stmt->fetch(PDO::FETCH_ASSOC)) :
        $data = $row;
    endwhile;

The array i get as a result of above code is as following
Array
(
    [0] => Array
        (
            [user_id] => 1
            [fname] => First Name
            [lname] => Last Name
        )

    [1] => Array
        (
            [user_id] => 91
            [fname] => First Name
            [lname] => Last Name
        )
)

But the problem is I am missing column headers in excel, so for that I need to display the MySql column headers in an array as well.
I am using the following code to create an array for column headers
    for ($i = 0; $i < $stmt->columnCount(); $i++) {
        $col = $stmt->getColumnMeta($i);
        $columns[] = $col['name'];
    }

but this gives me an array in following format
Array
(
    [0] => user_id
    [1] => fname
    [2] => lname
)

whereas I need the column header array in following format
Array
(
    [0] => Array
        (
            [user_id] => user_id
            [fname] => fname
            [lname] => lname
        )
)

I will appreciate any help.

A: Instead of letting it auto-number, just provide the name again as the key:
for ($i = 0; $i < $stmt->columnCount(); $i++) {
    $col = $stmt->getColumnMeta($i);
    $columns[$col['name']] = $col['name'];
}

Example: https://eval.in/117424

A: I assume you want the headers to be in the same array. In that case you would do this before the while loop
$data[0] = array();
for ($i = 0; $i < $stmt->columnCount(); $i++) {
    $col = $stmt->getColumnMeta($i);
    $data[0][$col['name']] = $col['name'];
}

Also, the while loop is a little inefficient. You're pushing each row into the $row array and then copying it into $data every single time. It should be done like this instead:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) :
    $data[] = $row;
endwhile;

This should get you:
$data = Array
(
    [0] => Array
    (
        [user_id] => user_id
        [fname] => fname
        [lname] => lname
    )
    [1] => Array
    (
        [user_id] => value...
        ...
    )
    ...
)

A: Might be easier:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    if(!isset($data)) {
        $data[] = array_combine(array_keys($row), array_keys($row));
    }
    $data[] = $row;
}

Or you could add them after the fact using array_unshift().
Or in a separate array:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    if(!isset($col)) {
        $col[] = array_combine(array_keys($row), array_keys($row));
    }
    $data[] = $row;
}


text:
Q: How to create an overlay network with Docker? When I try to create an overlay network with Docker I get the following error:
docker@boot2docker:/vagrant$ docker network create --driver overlay somenetwork

Error response from daemon: failed to parse pool request for address space
"GlobalDefault" pool "" subpool "": cannot find address space GlobalDefault
(most likely the backing datastore is not configured)`

I found this bug report on GitHub: https://github.com/docker/docker/issues/18770
I checked my Boot2Docker image, it is using sysvinit and not systemd, so this shouldn't be a problem, and also the kernel version seems to be good:
docker@boot2docker:/vagrant$ uname -r
4.1.19-boot2docker

Is it possible that this is a misuse of the overlay network concept that I try to run this only on one host...? Maybe this causes that strange error?
Update:
I think this was a mistake to execute the network creation command to the locally running docker daemon. I think I should have done this to my swarm manager instead - in this case the error message is different:
docker@boot2docker:~$ docker -H tcp://0.0.0.0:3375 network create --driver overlay network
Error response from daemon: No healthy node available in the cluster

When I check the status of the swarm cluster there are no nodes indeed. Maybe the original problem is my swarm join command was not fully correct...?
docker run -d swarm join consul://127.0.0.1:8500/

A: If you read through the documentation on overlay networks, you see that in order to create an overlay network you first need to configure a key/value store (Docker currently supports etcd, consul, and zookeeper) that Docker uses to coordinate things between multiple hosts.
From the docs:

To create an overlay network, you configure options on the daemon on each Docker Engine for use with overlay network. There are three options to set:
  Option    Description

*

*--cluster-store=PROVIDER://URL
Describes the location of the KV service.

*--cluster-advertise=HOST_IP|HOST_IFACE:PORT
The IP address or interface of the HOST used for clustering.

*--cluster-store-opt=KEY-VALUE OPTIONS
Options such as TLS certificate or tuning discovery Timers

From your question, it doesn't sound like you have performed the necessary configuration.

A: As the update suggested ..
.. the problem is ..
your swarm join command.
A solution could be ..
docker run swarm join --addr=192.168.196.16:2375 token://`cat swarm_id`

Assuming that you created the swarm using a token. As for me I rather use static file.
You'll find everything you need in this answer.


text:
Q: What are the possible points to be consider if i create Business Manager for My Facebook App I have recently noticed that facebook returns different auth ids for same app on different platforms.
We have a website and integrated Facebook login and implemented login using user id returned by facebook api.
It was working like a charm, but now we have created android and ios app , when we have tried to login by facebook with same user login which has already logged in from web platform returns different user id.
So my question is that which steps need to be taken to allow facebook login through android and ios app for users who has aready made signup on our web platform and how to make mappings if we use Business Manager


text:
Q: Filtering array of custom objects I had a class which is not a subclass of NSObject and an array of instances of that class.
enum ObjectType{
  case type1
  case type2
  case type3
}

class MyObject {
  var type = ObjectType!
  //some other properties...
}

let array = [obj1(type:type1),
             obj2(type:type2),
             obj3(type:type3),
             obj4(type:type2),
             obj5(type:type3)]

let type2Array = array.filter(){ $0.type == .type2}
// type2Array is supposed to be [obj2, obj4]

this is causing fatal error: array cannot be bridged from Objective-C
How can I filter array appropriately?
Do I have to subclass from NSObject or make my class conform to any protocol?

A: From what I can see from your question, none of the above really has any connection to Objective-C. Your example contains a few other issues, however, keeping it from working as intended.

*

*MyObject has no initializer (as of Swift 2.2, you should include at least one initializer).

*What are obj1, obj2, ... ? You treat these as methods or class/structures types, when I presume you're intending for these to be instances of the MyObject type.

If fixing the above, the actual filtering part of your code will work as intended (note that you can omit () from filter() {... }), e.g.:
enum ObjectType{
    case type1
    case type2
    case type3
}

class MyObject {
    var type : ObjectType
    let id: Int
    init(type: ObjectType, id: Int) {
        self.type = type
        self.id = id
    }
}

let array = [MyObject(type: .type1, id: 1),
             MyObject(type: .type2, id: 2),
             MyObject(type: .type3, id: 3),
             MyObject(type: .type2, id: 4),
             MyObject(type: .type3, id: 5)]

let type2Array = array.filter { $0.type == .type2}
type2Array.forEach { print($0.id) } // 2, 4

As an alternative to filtering directly to an enumeration case, you could specify the rawValue type of your enumeration and match to this instead. E.g. using an Int rawValue allows you to (in addition to filtering w.r.t. rawValue) perform pattern matching for say, ranges of cases in your enumeration.
enum ObjectType : Int {
    case type1 = 1  // rawValue = 1
    case type2      // rawValue = 2, implicitly
    case type3      // ...
}

class MyObject {
    var type : ObjectType
    let id: Int
    init(type: ObjectType, id: Int) {
        self.type = type
        self.id = id
    }
}

let array = [MyObject(type: .type1, id: 1),
             MyObject(type: .type2, id: 2),
             MyObject(type: .type3, id: 3),
             MyObject(type: .type2, id: 4),
             MyObject(type: .type3, id: 5)]

/* filter w.r.t. to rawValue */
let type2Array = array.filter { $0.type.rawValue == 2}
type2Array.forEach { print($0.id) } // 2, 4

/* filter using pattern matching, for rawValues in range [1,2],
   <=> filter true for cases .type1 and .type2 */
let type1or2Array = array.filter { 1...2 ~= $0.type.rawValue }
type1or2Array.forEach { print($0.id) } // 1, 2, 4


text:
Q: Using the same frame ticks for two different histograms Consider the following:
SetOptions[Histogram, BarOrigin -> Left,
  Frame -> {{True, None}, {True, None}}, FrameTicks -> Automatic];

data1 = {Table[1, {i, 5}], Table[5, {i, 50}], Table[3, {i, 25}],
   Table[4, {i, 20}]};
data2 = {Table[1, {i, 3}], Table[5, {i, 20}], Table[3, {i, 25}]};
data3 = {Table[1, {i, 3}], Table[5, {i, 20}], Table[4, {i, 15}]};

histo1 = Histogram[data1]
histo2a = Show[Histogram[data1, ChartElements -> None],Histogram[data2]]
histo3a = Show[Histogram[data1, ChartElements -> None],Histogram[data3]]

histo2b = Show[Histogram[data1], Histogram[data2, ChartStyle -> Red]]
histo3b = Show[Histogram[data1], Histogram[data3, ChartStyle -> Red]]

I would like to use the same frame/coordinate system for histo2a and histo3a as in histo1. histo3b shows how it should be (only without the grey part) and histo2a how it should not be. histo2bin addition shows the disadvantage of the Show[]-approach (one bar exceeds the frame).
Due to the latter, I was trying to extract the FrameTicks-values from histo1 and to use them for Histogram[data2] and Histogram[data3] but neitherOptions[histo1,FrameTicks],AbsoluteOptions[histo1,FrameTicks]norHistogramList[data1]` return help.
Now I would like to use exactly the same frame ticks, which were calculated based on data1 for histo2.
Neither Options[histo1,FrameTicks], AbsoluteOptions[histo1,FrameTicks] or HistogramList[data1] help. Has anyone an idea?

A: Perhaps:
SetOptions[Histogram, BarOrigin -> Left,
  Frame -> {{True, None}, {True, None}}, FrameTicks -> Automatic];

data1 = Table[BesselJ[1, x], {x, 0, 500}];
data2 = Table[BesselJ[1, x], {x, 0, 100}];
GraphicsGrid[{{
   histo1 = Histogram[data1],
   histo2 = Histogram[data2],
   Show[
    Histogram[data2, ChartElements -> None],
    Histogram[data1, {HistogramList[data2][[1]]}]]}}]

Edit
use just
Show[Histogram[data2, ChartElements -> None], Histogram[data1]]

if you don't want to reuse the same bins:


text:
Q: Ionic Speech Recognition - run time error Object(...) is not a function at hasPermission I'm trying to implement a simple speech recognition service (separately for now, to add it eventually in a bigger app).
I'm getting a weird run-time error, that I couldn't get any answer to it online or in documentation.
here's the code....
app.module.ts
import { SpeechRecognition } from '@ionic-native/speech-recognition/ngx';
.....
providers: [
StatusBar,
SplashScreen,
SpeechRecognition,
{provide: ErrorHandler, useClass: IonicErrorHandler}]

home.ts
import { SpeechRecognition } from '@ionic-native/speech-recognition/ngx';
import { AlertController } from 'ionic-angular';
......
constructor (private sr: SpeechRecognition, private alertCtrl: AlertController)
......
ngonInit() {
try {
      this.sr.hasPermission().then((permission: boolean) => {
        if(!permission) {
          this.sr.requestPermission().then(
            () => console.log("Granted"),
            () => console.log("Denied")
          );
        }
      });
    }
    catch(err) {
      let alert = this.alertCtrl.create({
        title: "x_x",
        message: "Opps! couldn't get permission!",
        buttons: [{
          text: "cancel",
          role: 'cancel',
          handler: () => {}
        }]
      });
      console.log(err);   //ERROR LOGGED
      alert.present();
    }
}

start() {
    try {
      this.sr.startListening().subscribe((matches: Array<string>) => {
        console.log(matches);
        this.msg= matches[0];
      });
    }
    catch(err) {
      let alert = this.alertCtrl.create({
        title: "x_x",
        message: "Opps! something is wrong!",
        buttons: [{
          text: "cancel",
          role: 'cancel',
          handler: () => {}
        }]
      });
      console.log(err);    // ERROR LOGGED if ngOnInit kept empty
      alert.present();
    }
  }

with a simple HTML button to invoke start() & print whatever is getting matched by the recognizer.
Just in case this is a compatibility issue, I'm using

@ionic-native/speech-recognition": "^5.0.0"
cordova-plugin-speechrecognition": "1.2.0"

The error I'm getting is always

TypeError: Object(...) is not a function at SpeechRecognition.hasPermission

needless to say, If i comment out the content of ngOnInit, the error will change to startListening() is not a function.
P.S. This is my first question here at StackOverFlow, hopefully I provided enough info about the problem.
Thanks.

A: As expected, it was a compatibility (version) issue.

Ionic 3 will run speech-recognition up to: "^4.20.0"

/> ionic cordova plugin add cordova-plugin-speechrecognition@4.20.0
/> npm install --save @ionic-native/speech-recognition@4.20.0

import { SpeechRecognition } from '@ionic-native/speech-recognition';

Ionic 4 will run speech-recognition up-to: "^5.0.0"  (latest at the time of writing)

/> ionic cordova plugin add cordova-plugin-speechrecognition
/> npm install @ionic-native/speech-recognition

import { SpeechRecognition } from '@ionic-native/speech-recognition/ngx';

P.S. You can't test that functionality on browser. (since this is a cordova plugin).
Credits to "AJT_82" for pointing this out in the comments.


text:
Q: Quickbuild in Texmaker on Catalina I just updated my running system to macOS Catalina 10.15 and now the quickbuild in Texmaker does not work anymore. More precisely even if I use the PdfLatex command it does not create a document?
Can anyone help me with this and tell me what I need to do to get it running again?
Thanks.

A: I have downloaded the last version of TexMaker here:
https://www.xm1math.net/texmaker/
and I do not have any problem now.


text:
Q: Paste Excel Chart into Powerpoint using VBA I'm trying to create an excel macro that copies charts displayed on an excel sheet, and pastes them (paste special) into a PowerPoint. The problem I'm having is how do I paste each chart on a different slide? I do not know the syntax at all..
This is what I have so far (it works but it only pastes to the first sheet):
Sub graphics3()

Sheets("Chart1").Select
ActiveSheet.ChartObjects("Chart1").Activate
ActiveChart.ChartArea.Copy
Sheets("Graphs").Select
range("A1").Select
ActiveSheet.Paste
     With ActiveChart.Parent
     .Height = 425 ' resize
     .Width = 645  ' resize
     .Top = 1    ' reposition
     .Left = 1   ' reposition
 End With

Dim PPT As Object
Set PPT = CreateObject("PowerPoint.Application")
PPT.Visible = True
PPT.Presentations.Open Filename:="locationwherepptxis"

Set PPApp = GetObject("Powerpoint.Application")
Set PPPres = PPApp.activepresentation
Set PPSlide = PPPres.slides _
    (PPApp.ActiveWindow.Selection.SlideRange.SlideIndex)

' Copy chart as a picture
ActiveChart.CopyPicture Appearance:=xlScreen, Size:=xlScreen, _
    Format:=xlPicture

' Paste chart
PPSlide.Shapes.Paste.Select

' Align pasted chart
PPApp.ActiveWindow.Selection.ShapeRange.Align msoAlignCenters, True
PPApp.ActiveWindow.Selection.ShapeRange.Align msoAlignMiddles, True

A: Given I dont have your file locations to work with I have attached a routine below that

*

*Created a new instance of PowerPoint (late binding, hence the need to define constants for ppViewSlide etc)

*Loops through each chart in a sheet called Chart1 (as per your example)

*Adds a new slide

*Pastes each chart, then repeats

Did you need to format each chart picture before exporting for size, or can you change your default chart size?
Const ppLayoutBlank = 2
Const ppViewSlide = 1

Sub ExportChartstoPowerPoint()
    Dim PPApp As Object
    Dim chr
    Set PPApp = CreateObject("PowerPoint.Application")
    PPApp.Presentations.Add
    PPApp.ActiveWindow.ViewType = ppViewSlide
    For Each chr In Sheets("Chart1").ChartObjects
        PPApp.ActivePresentation.Slides.Add PPApp.ActivePresentation.Slides.Count + 1, ppLayoutBlank
        PPApp.ActiveWindow.View.GotoSlide PPApp.ActivePresentation.Slides.Count
        chr.Select
        ActiveChart.CopyPicture Appearance:=xlScreen, Size:=xlScreen, Format:=xlPicture
        PPApp.ActiveWindow.View.Paste
        PPApp.ActiveWindow.Selection.ShapeRange.Align msoAlignCenters, True
        PPApp.ActiveWindow.Selection.ShapeRange.Align msoAlignMiddles, True
    Next chr
    PPApp.Visible = True
End Sub

A: Code with function for plotting 6 charts from Excel to PPT
Option Base 1
Public ppApp As PowerPoint.Application

Sub CopyChart()

Dim wb As Workbook, ws As Worksheet
Dim oPPTPres As PowerPoint.Presentation
Dim myPPT As String
myPPT = "C:\LearnPPT\MyPresentation2.pptx"

Set ppApp = CreateObject("PowerPoint.Application")
'Set oPPTPres = ppApp.Presentations("MyPresentation2.pptx")
Set oPPTPres = ppApp.Presentations.Open(Filename:=myPPT)
ppApp.Visible = True
Set wb = ThisWorkbook
Set ws = wb.Sheets(1)

i = 1

For Each shp In ws.Shapes

    strShapename = "C" & i
    ws.Shapes(shp.Name).Name = strShapename
    'shpArray.Add (shp)
    i = i + 1

Next shp

Call Plot6Chart(oPPTPres, 2, ws.Shapes(1), ws.Shapes(2), ws.Shapes(3), ws.Shapes(4), ws.Shapes(5), ws.Shapes(6))

End Sub
Function Plot6Chart(pPres As Presentation, SlideNo As Long, ParamArray cCharts())

Dim oSh As Shape
Dim pSlide As Slide
Dim lLeft As Long, lTop As Long

Application.CutCopyMode = False
Set pSlide = pPres.Slides(SlideNo)

For i = 0 To UBound(cCharts)

    cCharts(i).Copy
    ppApp.ActiveWindow.View.GotoSlide SlideNo
    pSlide.Shapes.Paste
    Application.CutCopyMode = False

    If i = 0 Then ' 1st Chart
        lTop = 0
        lLeft = 0
    ElseIf i = 1 Then ' 2ndChart
        lLeft = lLeft + 240
    ElseIf i = 2 Then ' 3rd Chart
        lLeft = lLeft + 240
    ElseIf i = 3 Then ' 4th Chart
        lTop = lTop + 270
        lLeft = 0
    ElseIf i = 4 Then ' 5th Chart
        lLeft = lLeft + 240
    ElseIf i = 5 Then ' 6th Chart
        lLeft = lLeft + 240
    End If

    pSlide.Shapes(cCharts(i).Name).Left = lLeft
    pSlide.Shapes(cCharts(i).Name).Top = lTop

Next i

Set oSh = Nothing
Set pSlide = Nothing
Set oPPTPres = Nothing
Set ppApp = Nothing
Set pPres = Nothing

End Function


text:
Q: Creating a symmetrical 2D array I've been racking my brains over something that must be incredibly simple, as I've not seen it answered anywhere (or I'm very bad at searching).
I want to create a symmetrical 2D array, filled with random numbers from 1 to 100 inclusive... here is what I've got so far
int n = 3;
        int rangeOfWeights = 100;
    double[][] array = new double[n][n];
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            array[i][j] = rand.nextInt((rangeOfWeights)+1);
        }
    }

At the moment, this is giving results like:
44 45 32
9 31 53
25 48 74

when actually the kind of result I want is:
0 34 32
34 0 23
32 23 0

A: As you defined, you're trying to create a 2D array where array[i][j] == array[j][i]. You could a pair of nested loops where one iterates up to the array's size and the other up to the outer array's counter, and in each iteration set the value of the two symmetrical values:
double[][] array = new double[n][n];
for(int i = 0; i < n; i++) {
    for(int j = 0; j < i; j++) {
        int value = rand.nextInt((rangeOfWeights)+1);
        array[i][j] = value;
        array[j][i] = value;
    }
}


text:
Q: How to save user id only once in json file discord.py The code I have saves the same user in the json file again:
@client.command()
async def Shibaku1(ctx, coin1, coin2, coin3, coin4, coin5, coin6):
    with open('Shibaku1.json', 'r') as f:
      coins_data = json.load(f)
    coins_data[ctx.author.id] = (coin1, coin2, coin3, coin4, coin5, coin6)
    with open('Shibaku1.json', 'w') as f:
      json.dump(coins_data, f)

I tried making an if statement in order to not happen, but it didn't seem to work

A: Python automatically updates keys in dictionary if they exist.
You should convert ctx.author.id to str using str(ctx.author.id):
@client.command()
async def Shibaku1(ctx, coin1, coin2, coin3, coin4, coin5, coin6):
    with open('Shibaku1.json', 'r') as f:
      coins_data = json.load(f)
    coins_data[str(ctx.author.id)] = (coin1, coin2, coin3, coin4, coin5, coin6)
    with open('Shibaku1.json', 'w') as f:
      json.dump(coins_data, f)


text:
Q: change the format of DataTable, add two rows with column headers for the table I've to add a top row in my DataTable. Then the column of top rows will be divided in two columns in the next row. After that I've to present my data in the DataTable. Currently my DataTable is showing data that is returned from the database. How can I change the format of my DataTable?
Current DataTable format

My new DataTable requirement

In this new DataTable I've to add top rows with column headers NEW & OLD. And after that, again there will be another row with new headers and from the third row there will be data. How can I get this new DataTable from the above DataTable? Note that the DataTable is generated from database.
I've just retrieve the data from the Database on click.
protected void search_Click(object sender, EventArgs e)
        {
                // code blocks
                if (dt != null && dt.Rows.Count > 0)
                {
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                    div_error.Visible = true;
                    DataTable_Format(dt);
                }
        }

A: You can use OnDataBound event of gridview.
protected void OnDataBound(object sender, EventArgs e)
{
    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
    TableHeaderCell cell = new TableHeaderCell();
    cell.Text = "New";
    cell.ColumnSpan = 4;
    row.Controls.Add(cell);
    cell = new TableHeaderCell();
    cell.ColumnSpan = 2;
    cell.Text = "Old";
    row.Controls.Add(cell);
    GridView1.HeaderRow.Parent.Controls.AddAt(0, row);
}


text:
Q: What is the production url for Ionic 6 I just started an ionic app and dev spins up http:localhost:8081. I will be hitting an api that needs to whitelist the apps url. What will that be? https:localhost:8081?

A: You most likely need to whitelist the IP adress of the app. Which is going to change depending on the phone it is installed on.
For your usecase you most likely want to have a server communicating with both the app and api so you can use it's IP address to whitelist.


text:
Q: Boost Test output spamming with "disabled" when running named test I'm running a Boost Test test/suite by name, using:
./MyTestExe --run_test=my_test

Unfortunately i'm getting hundreds of:
"Test case "bla" is skipped because disabled"

But I didn't disable it, I simply chose to not run it.
Is there a way to remove all these messages? However, if possible I would like to keep them for when I run everything and a test is actually disabled?

A: Would have been nice to provide a repro.
So I made the simplest one:
#define BOOST_TEST_MODULE test module name
#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(Suite)

    BOOST_AUTO_TEST_CASE(A) {
        BOOST_TEST_MESSAGE("Yo A");
        BOOST_TEST(1 == 3);
    }

    BOOST_AUTO_TEST_CASE(B) {
        BOOST_TEST_MESSAGE("Yo B");
        BOOST_TEST(1 == 1);
    }

    BOOST_AUTO_TEST_CASE(C) {
        BOOST_TEST_MESSAGE("Yo C");
        BOOST_TEST(3 == 3);
    }

BOOST_AUTO_TEST_SUITE_END()

Which prints Live On Coliru

Now let's run only test case C: ./a.out -t Suite/C: Live On Coliru

In order to actually see the informational messages you mention, you have to ask for it:
a.out -t Suite/C -l all Live On Coliru

The options are:

  log_level
    Specifies the logging level of the test execution.
    --log_level=<all|success|test_suite|unit_scope|message|warning|error|cpp_exception|system_error|fatal_error|nothing>
    -l <all|success|test_suite|unit_scope|message|warning|error|cpp_exception|system_error|fatal_error|nothing>

Turns out you need at leat unit_scope or test_suite to see it. If you just want to see your own informationals, use -l message: Live On Coliru

Conclusion:
Simply do not enable verbose logging.
Note it is possible that the log configuration is made somewhere implicitly. E.g. in a custom runner entry point or read from a configuration file. Also, if this is on some kind of CI server, check your build/CI scripts.


text:
Q: External Mic not detected Macbookpro 11,1 CS4208 My external combo jack mic always not detected, I used different headphones, And All working fine in OSX but not working when switching to Linux, I tried different distributions using the live boot,  and All the same issue, currently I am on Pop!_OS 21.04
Also Tried the latest version of Popos and the same issue.

pavucontrol

MY alsa info:
http://alsa-project.org/db/?f=1d06b188bb60fe99e9917dacac662d6af24ff4d7


text:
Q: cs50 PSET2 Substitution: Trouble only in encrypts all alphabetic characters using DWUSXNPQKEGCZFJBTLYROHIAVM as key I'm a beginner in cs50. This is my work on week2. This is problem set substitution.
so this is my code. All problems are compiled successfully except this one. The output is "Segmentation fault"
this is my code:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int main (int argc, string argv[])

{
    string key1 = argv[1];

//check for only 2 arguments//
if (argc != 2)
{
    printf("Usage: ./substitution key\n");
    return 1;
}

//check key length, must 26 lenght//
if (strlen(key1) != 26)
{
    printf("Key must contain 26 characters.\n");
    return 1;
}

for (int i=0; i < strlen(key1); i++)
{
    //check for non alphabet//
    if (!(isalpha(key1[i])))
    {
        printf("Key must contain only letters.\n");
        return 1;
    }

    //convert all word to uppercase to make encryption easier//
    else
    {
        key1[i] = toupper (key1[i]);
    }

    //check for not repeated word//
    for (int j=0; j < i; j++)
    {
        if (key1[i] == key1[j])
        {
            printf("Key must not contain repeated letters.\n");
            return 1;
        }
    }
}

//ask input//
string input1 = get_string("plaintext: ");
string input2 = input1;

//check if the word is lower or uppercase//
int checker[25];
for (int s = 0; s < strlen (input1); s++)
{
    if (isupper(input1[s]) == 0)
    {
        checker[s] = 0; //false

        //convert to uppercase to make encryption easier//
        input1[s] = toupper (input1[s]);
    }
    else
    {
        checker[s] = 1; //true
    }

    //printf("Input %d: %c is %d\n", s, input1[s], checker[s]); //debug//

}

//printf("word is %s\n", input1); //debug//

//CONVERTTTT//
int new_ascii = 0;
printf("ciphertext: ");

for (int k = 0; k < strlen(input1); k++)
{
    char x = input1[k];
    int ascii = (int) x;

    //check if it's alphabet or not//
    if (isalpha(x))
    {
        ascii -=  65;
        new_ascii = key1[ascii];

        //restore to upper/lowercase
        if (checker[k]==0)
        {
           new_ascii = (int) tolower ((char) new_ascii); //we use tolower cause all word has converted to upper
        }

    }
    else //if not just continue
    {
        new_ascii = ascii;
    }

    printf("%c", (char) new_ascii);
}

printf("\n");

return 0;
}

and this is the output:
./substitution DWUSXNPQKEGCZFJBTLYROHIAVM

plaintext: The quick brown fox jumps over the lazy dog

Segmentation fault

I don't know where's my problem since this is the only one can't be compiled. Does anyone have clue?

A: (Unfortunately I could not reproduce the Segmentation fault on onlinegdb.com.)
The size of the array checker must be at least the string length of the input. This is problematic because you don't know how long the input will be. Your example input is longer than the size 25 of the array, so your code will write past the end of the array and (try to) overwrite whatever is stored at this memory location. This can result in a segmentation fault.
To avoid this out-of-bounds access to the array you could check the length of the input string and either truncate it or print an error message that informs the user about the limitation.
A better solution would be to integrate the check for uppercase/lowercase in the function that encrypts the input. With this approach you have to know the uppercase/lowercase information only for the character just being processed, not for all characters of the input string.
As this is a task for learning, I don't show a ready-made solution but only an algorithm as pseudo code:
for all characters of the input string
{
    get the next character

    if alphabetic (or better if it is in range 'A'..'Z' or 'a'..'z')
    {
        if lowercase
        {
            set lowercase flag
            key index = character - 'a'
        }
        else
        {
            clear lowercase flag
            key index = character - 'A'
        }

        get encrypted character based on key index

        if lowercase flag
        {
            convert to lowercase
        }

        print encrypted character
    }
    else /* not alphabetic */
    {
        print original character
    }
}

Note that the result of function isalpha depends on your locale settings. For languages other than English, additional characters might be classified as alphabetic ones. This could result in an out-of-bounds access to your key array. To avoid this you could add a check for isascii or use explicit checks for 'A'..'Z' or 'a'..'z'.


text:
Q: PHP MYSQL Query to select values separated by commas I need to display the rows that matches any one of the numbers that are separated by commas.
This is my query,
 query("select * from sample_table where sample_id IN ('1,3,6,4,7,9') ");

My query must select the table containing when any one of the numbers matches.

A: if the sample_id field type is int then: query("select * from sample_table where sample_id IN (1,3,6,4,7,9) ");
if its type is varchar then query("select * from sample_table where sample_id IN ('1','3','6','4','7','9') ");

A: Your query is query("select * from sample_table where sample_id IN ('1,3,6,4,7,9') ");
If you change to this query("select * from sample_table where sample_id IN (1,3,6,4,7,9) "); than it will work.
You only need to remove single quotes ie ('1,3,6,4,7,9') to (1,3,6,4,7,9)


text:
Q: Is 75986⋯69 ever prime or is there a 6 padded prime for every prime $p > 5$? I came across this question:
How can we turn any number into a prime number by simply adding more digits?
While trying different approaches to find an algorithm that increases the chances of finding a prime this way I discovered the six padded primes:
Start with an prime $p>5$ then add a digit 6 before the last digit, repeat the process until the result is prime.
This table shows the results for p up to 100:
\begin{align*}
7 && 67 \\
11 && 16661 \\
13 && 163 \\
17 && 167 \\
19 && 1669 \\
23 && 263 \\
29 && 269 \\
31 && 3666661 \\
37 && 367 \\
41 && 461 \\
43 && 463 \\
47 && 467 \\
53 && 563 \\
59 && 569 \\
61 && 661 \\
67 && 666667 \\
71 && 761 \\
73 && 76666663 \\
79 && 769 \\
83 && 863 \\
89 && 8669 \\
97 && 967 \\
\end{align*}
There were only 2 numbers below $200000$ for which I could not find a result:
$15731$ and $75989$. My computer finally found a solution for the first padded with 7460 sixes resulting in a 7465 digit prime number. $75989$ was checked up to 15000 digits.
Question:

Is $75986\cdots69$ ever prime or can it be proved there is a six padded prime for every prime > 5

A: If you insert an odd number of $6$'s, it is simple to check that the resulting number is a multiple of $11$ (just use the divisibility criterion).
For an even number $n$ of $6$'s, notice that
$$
759866\equiv 3\pmod{13},\quad
1000000\equiv 1\pmod{13},\quad
666666\equiv 0\pmod{13},
$$
and
$$
75986666\equiv 25\pmod{37},\quad
1000000\equiv 1\pmod{37},\quad
666666\equiv 0\pmod{37}.
$$
Hence when $n=2+6k$ the number is a multiple of $13$, and when $n=4+6k$ the number is a multiple of $37$.
At the moment, I can say nothing for the case $n=6k$.
EDIT.
Playing around with Mathematica I noticed some other regularities (which I didn't bother to prove):

*

*for $n=6(1+7k)$ the number is a multiple of $43$;

*for $n=6(4+8k)$ the number is a multiple of $17$;

*for $n=6(4+5k)$ the number is a multiple of $31$.

On the other hand, there are several cases where the number has only two prime factors, both large. At the moment, however, I could find no trace of a prime number.


text:
Q: com.google.android.gms.common.api.ApiException: 17: API: Games.API is not available on this device recently I ported my old Android game developed in Eclipse from 2011-2016, to Android Studio because I was forced to a much higher MinSdk by Google. To the following according to build.gradle:
compileSdk 30
minSdk 26
targetSdk 31

Everything worked fine after the porting, but I am not able to get the GooglePlayServices (Leaderboards, Achievements) working again.
I am able to trigger that the user signs in with it GooglePlay account. This works and I get the account and can log its name. That is working.
mGoogleSignedInAccount = completedTask.getResult(ApiException.class);
Log.e(TAG, "account: " + mGoogleSignedInAccount.getDisplayName());

But when I try open the leaderboard, so that the user can see their highscore compared to other players
LeaderboardsClient lbc = Games.getLeaderboardsClient(v.getContext(),
                         ApplSettings.getInstance()._mainActivity).mGoogleSignedInAccount);
Task<Intent> lbt = lbc.getAllLeaderboardsIntent();
lbt.addOnSuccessListener(new OnSuccessListener<Intent>() {
    public void onSuccess(Intent intent) {
       Log.d(TAG," ..onSuccess");
       ((Activity) (v.getContext())).startActivityForResult( intent, 9004 );
    }
});
lbt.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
       Log.d(TAG,".. onFailure: "+e.toString());
    }
});

I get the following error:
.. onFailure: com.google.android.gms.common.api.ApiException:
 17: API: Games.API is not available on this device.
Connection failed with: ConnectionResult{statusCode=DEVELOPER_ERROR, resolution=null, message=null}

I really don't understand this error. What does it mean? It is independent of the phones I use (OnePlus6T, Samsung Galaxy S9). And of course other game apps on those phones, including my other older games app, can show Leaderboards!
What is also strange, is the following message in the GooglePlayConsole of my app in Play-GamesSevice->Configuration.
It says the 5 tasks have to be done to enable the Play-GameServices, and its states that 4 have been done, and 1 task is remaing:

Play-GameService enabling:

*

*Create a Play GamesService project -> done

*Create OAuth ConfirmationScreen in the Google Cloud Platform -> done

*Create Credentials -> done

*Add the SDK for Google Play-GamesServices to your production APK -> OPEN !!!

*Publish Project -> done

What does point 4 mean? How to add an SDK to my games app?
Is it not enough to mention those play-service 'libraries' in the build.gradle of my app?
buildscript {
    repositories {
        google()
        mavenCentral()
    }
}

dependencies {
    . . .
    implementation 'com.google.android.gms:play-services-games:23.1.0'
    implementation 'com.google.android.gms:play-services-measurement-api:20.0.0'
    implementation 'com.google.android.gms:play-services-auth:20.4.1'
}

So I am not sure if this task (number 4) mentioned by Google as outstanding, is related to the error "Games.API is not available on this device", but it would make sense.
But still I don't understand "not available on this device"? Does not the app is build with libraries that communicate with the Google services in the cloud? What shall be missing on the device? All games app (my other very old game, and also very new apps) can without problem show leaderboards on my devices I use for testing.


text:
Q: I have to create this student data program. There is this warning I just cannot figure out So I wrote out this code and run it through cygwin terminal! I cleared all the errors but it only leaves me with one last warning I just cannot fix.
#include <stdio.h>
int main (int argc, char *argv[]) {
        int phoneNumber;
        char firstName[11];
        char lastName[11];
        char eMail[20];

        printf("Please enter the user's first name:");
        scanf("%s", firstName);
        printf("Please enter the user's last name:");
        scanf("%s", lastName);
        printf("Please enter the user's phone number:");
        scanf("%i", phoneNumber);
        printf("Please enter the user's e-mail:");
        scanf("%s", eMail);
        printf("firstName, lastName, phoneNumber, eMail: %s, %s, %i, %s", firstName, lastName,
phoneNumber, eMail);
}

There is the code. The cygwin error tells me:
warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]
This refers to the last printf line where the %i is.

A: Try scanf("%d", &phoneNumber); and use %d for the printf as well.  In C and its derivatives, functions are all pass-by-value.  In order for a function to modify a variable, you need to pass in the address of that variable rather than its value.  That's why you prefix with & to get the address of phoneNumber into the scanf function.  However, you only use the & for the scanf argument, not for declaring or using the variable locally.


text:
Q: Convert function with for/while loop into Pandas dataframe.apply(lambda ...: ...) method if there is a change in each iteration I am looking for a way to convert structure:
for ... in dataframe:
   while ...:
      if ...:
         do smth
   if ...:
      do smth

to
dataframe.apply(lambda ...: ...)

Here is example of function with for/while loop:
d_test = {
    'name' : ['South Beach', 'Dog', 'Bird', 'Ant', 'Big Dog', 'Beach', 'Dear', 'Cat', 'Fish', 'Dry Fish'],
    'cluster_number' : [1, 2, 3, 3, 2, 1, 4, 2, 2, 2]
}

df_test = pd.DataFrame(d_test)

from rapidfuzz import fuzz

df_test = df_test.sort_values(['cluster_number', 'name'])
df_test.reset_index(drop=True, inplace=True)
df_test['id'] = 0

def loop_in_cluster(index, row, df_test, index_, row_, is_i_used, i):
    while index_ < len(df_test) and df_test.loc[index, 'cluster_number'] == df_test.loc[index_, 'cluster_number'] and df_test.loc[index_, 'id'] == 0:
        if row['name'] == df_test.loc[index_, 'name'] or fuzz.ratio(row['name'], df_test.loc[index_, 'name']) > 50:
            df_test.loc[index_,'id'] = i
            is_i_used = True
        index_ += 1
    return df_test, is_i_used

i = 1
is_i_used = False
for index, row in df_test.iterrows():
    row_ = row
    index_ = index
    df_test, is_i_used = loop_in_cluster(index, row, df_test, index_, row_, is_i_used, i)
    if is_i_used == True:
        i += 1
        is_i_used = False

And here is my attempt to use dataframe.apply() method:
i = 1
df_test.apply(lambda row: loop_in_cluster(i=i+1, index=row.name, row=row, df_test=df_test, index_=index, row_ = row, is_i_used=False) if is_i_used==True else loop_in_cluster(i=i, index=row.name, row=row, df_test=df_test, index_= index, row_=row, is_i_used=True), axis=1)

but I am getting: StopIteration: error in output. I tired other methods such as pandas groupby.GroupBy method but it seems that apply method is more closer to what I am looking for.


text:
Q: what is best ThreeJS loader to use for Animated models? what is the most supported format to load on ThreeJS for Animated models by bones with multi-textures ?
i find most examples (including JSON) are showing models with single texture.
if JSON is the best, where can i find working example model with multi-textures? i tried to export one from Blender but it does not work.

A: Had also problems with multi-textured animated models last time and best solution I've found was
http://www.cgdev.net/json/index.php
There is an exporter and a loader for threejs inside.
Hope this will help.


text:
Q: In what case is PR AUC higher than ROC AUC? I am working on an anomaly detection problem and have come across a paper(https://www.ijcai.org/proceedings/2019/0378.pdf), which shows results where in the ROC AUC value for a dataset is 0.566 and the PR AUC for the same dataset is 0.908. Can someone please explain to me in what case/scenarios this is possible?

A: Without reading the paper, the first scenario that comes to my mind is when you have imbalanced classes (very few instances of one class compared to the other). PR takes into account the provided class imbalance.


text:
Q: Sort by varchar date entry in SQL I want to sort my table by DATE which is a varchar holding date information like this:
January 06, 2023 // format is Month Day, Year

I want to sort by date but it doesn't work since this is not datetime. I've tried casting DATE but it doesn't seem to work. I tried like this:
SELECT * FROM receipt WHERE ID=? ORDER BY CAST(DATE AS datetime) DESC

I also tried convert but it did not work either, I must be using the syntax wrong.
How can I sort by date if my DATE entry is of type varchar.

A: In MySQL you can use str_to_date with the appropriate date format to convert a varchar to a date:
SELECT * FROM receipt WHERE ID=? ORDER BY STR_TO_DATE(date, '%M %d, %Y') DESC


text:
Q: Python read from one CSV file search the corresponding row from another csv if there is a element match I want to read through the first file1.csv and if the policy is present in file2.csv get the specific ID for policy and get the count of that policy ID from file3.csv.
So I have 3 csv files file1.csv file2.csv file3.csv as shown below, which has thousands of similar rows
file2.csv
Name   Policies
Raj    12345, 676, 909
Sam    786
Lucy   899, 7676, 09

file2.csv
Policies       ID
676, 8787      212
909,898,707    342
89, 98,09      345

file3.csv
ID  Count
212 56
342 23
345 07

SO finally my final output  would look something like this stored in a file or csv. Can use panda, numpy or anything
Final.csv
Name  tuple of [Policies, ID, Count]
Raj     [676,212,56]
Raj     [909, 342, 23]
Lucy    [09, 345, 07]

I'm stuck with the below code:
policyid = csv.reader( 'file2.csv', delimiter=',')
with open('file1.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        data = row['Policies'].split(",")
        if data:
            for policy in data:
                for policy, id in policyid:
                    data2 = policy.split(",")
                        if policy in data2:
                            print id

A: One way to do this is to read in all three CSV files, grab a value from file1, and scan through file2 and file3 to obtain those values. This is a extra difficult since comma-delimited lists in a field are an antipattern, forcing us to do some extra work to parse text along the way.
Another way to do this would be to load all three CSV files into either a SQL table or dataframe and do some JOINs, but the comma-delimited lists still make this difficult.
Here's an example of what I'm describing, although this is admittedly messy:
import csv

with open('file1.csv') as f:
    reader = csv.DictReader(f)
    next(reader)  # Skip header
    file1 = [row for row in reader]
with open('file2.csv') as f:
    reader = csv.DictReader(f)
    next(reader)  # Skip header
    file2 = [row for row in reader]
with open('file3.csv') as f:
    reader = csv.DictReader(f)
    next(reader)  # Skip header
    file3 = [row for row in reader]

def get_policy_id(policy):
    for line in file2:
        policies = line['policies'].split(', ')
        if policy in policies:
            return line['ID']

def get_id_count(id):
    for line in file3:
        if id == line['id']:
            return line['count']

output = []
for line in file1:
    policies = line['policies'].split(', ')
    for policy in policies:
        id = get_policy_id(policy)
        count = get_id_count(id)
        output.append({'name': line['name'],
                       'policy': policy,
                       'id': id,
                       'count': count})


text:
Q: NodeJS Load XML into Encoded String I wrote a server in NodeJS that uses DymoJS to print labels to a Dymo printer. When printing, the XML for the label layout must be specified. The documentation outlines the following to declare the label XML:
var labelXml = `
<?xml version="1.0" encoding="utf-8"?>
<DieCutLabel Version="8.0" Units="twips">
  ...

</DieCutLabel>
`;

However in my XML, the <String> elements are dependent on JS variables:
<Element>\
   <String>${name}\n</String>\
   ...
</Element>\

The server I wrote is distributed across multiple endpoints, which use different printers, and therefore different labels, meaning they require different XML specifications.
What I would like, is to be able to load the basic XML from a document, and then replace ${name} and other variables with their JS counterparts. I tried to use a raw fs.readfile(), following this answer, which did not work, as the XML was not parsed as encoded (or that is my best guess as to what went wrong). Most of the rest of the questions I've found are either relating to Site-Mapped-JS, or end up converting the XML to JSON.

A: Did you try to use xml-js?
You can edit structure as js objects and then translate it to xml.
For example:
const fs = require('fs');
const convert = require('xml-js');

const xml = fs.readFileSync('prueba.xml');
const js = convert.xml2js(xml, {compact: true});

js['DieCutLabel']['StyledText']['Element'][0]['String'] = 'Value of name';

console.log(convert.js2xml(js, {compact: true}));


text:
Q: Representation of central extension Let $G$ be a finite abelian group of rank $n$ and $H\rightarrow G$ a central extension with cyclic finite kernel.
Is it true that we can find a faithful representation $H\rightarrow {\rm GL}_{k(n)}(\mathbb{C})$ where $k(n)$ only depends on $n$?
I feel something like this must be true from the fact that $G$ should admit an irreducible projective representation into ${\rm PGL}_{k(n)}(\mathbb{C})$ where $k(n)$ only depends on $n$.

A: Here is an elementary proof of a related general fact. Let $H$ be any finite nilpotent group with $H^{\prime} = Z(H)$ cyclic of order $m$. Let $z$ be a generator of $Z(H)$. Then $\langle z \rangle $ has a (faithful) linear character $\lambda$ such that $\lambda(z)$ is a complex primitive $m$-th root of unity.
Note then that all irreducible constituents of ${\rm Ind}_{Z(H)}^{H}(\lambda)$ are faithful. For let $\chi$ be one such. Then by Frobenius recipirocity (and Clifford' Theorem), ${\rm Res}^{H}_{Z(H)}(\chi) = \chi(1)\lambda$, so that ${\rm Res}^{H}_{Z(H)}(\chi)$  is certainly faithful. On the other hand, if $\chi$ were not faithful, then ${\rm ker} \chi$ contains a minimal normal subgroup $M$ of $H$. Since $H$ is nilpotent, $M \leq Z(H)$ ( for $M \cap Z(H) \neq 1$ and $M$ is minimal), contrary to the fact that $M \leq {\rm ker} \chi$ and ${\rm Res}^{H}_{Z(H)}(\chi)$ is faithful.
Furthermore, ( as is well-known, and may be found in the character theory text of I.M. Isaacs for example), since $H$ is nilpotent, it follows that if $\theta$ is any faithful irreducible character of $H$, then $\theta$ vanishes identically outside $Z(H)$. For choose $a \in H \backslash Z(H)$ and choose $b \in H \backslash C_{H}(a)$ we have
$[a,b] = w$ for some $1 \neq w \in Z(H)$. Then $b^{-1}ab = wa$.
Hence $\theta(a) = \theta(b^{-1}ab) = \theta(wa)$. But by Schur's lemma, $w$ is represented by a scalar matrix in any representation affording character $\theta$, and the scalar, $\alpha$ say, is not $1$ as $\theta$ is faithful . Hence $\theta(a) = \theta(wa) = \alpha \theta(a) $, so that $\theta(a) = 0$.
Hence for our previous faithful irreducible character $\chi$ of $H$, the orthogonality relations yield $|H| = \sum_{ h \in H}|\chi(h)|^{2} = |Z(H)|\chi(1)^{2}$, so that $\chi(1) = \sqrt{[H:Z(H)]}.$

A: The answer is no.
According to Theorem 1.3 of this paper, if $H$ is a nilpotent group of class $2$ with cyclic commutator subgroup, then the minimal degree $m_\mathsf{f}(H)$ of a faithful complex representation of $H$ is given by $$m_\mathsf{f}(H) = \sqrt{|H:Z(H)|} + m_\mathsf{f}(Z(H)) - 1.$$
So, for example, the minimal degree of the group $$G = \langle x,y,z \mid x^n=y^n=[x,z]=[y,z]=1, [x,y]=z \rangle$$ of order $n^3$
is $n$, and $G/Z(G)$ is abelian of rank 2.


text:
Q: TypeError: unsupported operand type(s) for &: 'DatetimeArray' and 'DatetimeArray' - Pandas I want to filter the DF by checking the PCS Column if == 0 and 'ITEM DESC' =='ITEM XL'. If the criteria is met, I will multiply it by the BOX value and multiply it by 48.
DF
     ITEM DESC            PCS                   BOX
     ITEM S               12                     -
     ITEM M               12                     -
     ITEM L               12                     -
     ITEM XS              12                     -
     ITEM XL              0                      1

CODES
    if DF[DF['PCS']==0] & DF[DF['ITEM DESC']=='ITEM XL'] :
       DF['PCS'] = DF['PCS'] * DF['BOX'] * 48
    else:
       DF['PCS']

ERROR
      TypeError: unsupported operand type(s) for &: 'DatetimeArray' and 'DatetimeArray'

A: Either you meant all:
if DF[(DF['PCS']==0) & (DF['ITEM DESC']=='ITEM XL')].all():
   DF['PCS'] = DF['PCS'] * DF['BOX'] * 48

Or any:
if DF[(DF['PCS']==0) & (DF['ITEM DESC']=='ITEM XL')].any():
   DF['PCS'] = DF['PCS'] * DF['BOX'] * 48

Or more probable that you want to do it to specific rows:
 DF.loc[(DF['PCS']==0) & (DF['ITEM DESC']=='ITEM XL'), 'PCS'] = DF['PCS'] * DF['BOX'] * 48

A: Try using .apply
DF['PCS'] = DF.apply(lambda x: x.DF['PCS'] * x.DF['BOX'] * 48 if x.DF['PCS']==0 and x.DF['ITEM DESC']=='ITEM XL' else x.DF['PCS']==0, axis=1)


text:
Q: Android build path
Hi ,This is my first android application , by creating the package , I had a lot of build path errors. and I do not know how to solve,please help me

A: I'm pretty sure its the "appcompat_v7", which is automatically generated in eclipse when setting up an android project. It imports unnecessary features and causes a bunch of build errors.

*

*Delete "appcompat_v7" folder

*
*

*go to your MainActivity

*Delete the import "android.support.v7.app.ActionBarActivity";

*change "MainActivity extends ActionBarActivity" to  "MainActivity extends Activity"

*
*

*add import android.app.Activity;

*add import android.os.Bundle;

*add import android.view.Menu;

*add import android.view.MenuItem;

*go to res folder and then go to your values folder...delete styles.xml

*delete values-v11 folder

*delete values-v14 folder

*go to menu folder, and click on main.xml...go to "item" tag and delete app:showAsAction="never"

*go to AndroidManifest.xml...go to "application" tag...delete  android:theme="@style/AppTheme"

*go to project at the top...clean and build...you should have no more errors.


text:
Q: Can I use Polymer on JSFiddle? I want to create quick prototypes of Polymer elements in a sandbox like JSFiddle or JavaScript Bin, but I can't get it working!

A: Yes, you can, thanks to polygit.
Here's a boilerplate example you can fork: https://jsfiddle.net/kaycebasques/2q3fqehz/
HTML:
<base href="https://polygit.org/components/">

<link href="polymer/polymer.html" rel="import">

<dom-module id="x-example">
  <template>

polyfiddle

  </template>
</dom-module>

<x-example></x-example>

JS:
// only need this when in the main document and on non-Chrome
addEventListener('WebComponentsReady', function() {
  Polymer({
    is: 'x-example'
  });
});


text:
Q: Multiple columns in container I am learning Flutter, I want to achieve this look:
Does Container only allow one child? I want to have multiple of columns, like on the picture I will need 3 for logo, text box and for two buttons. How do I set this up properly? Maybe I should not use container?
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          Text("test"),
          Text("test")
        ]
      )

Also, what does this code do?
const MyApp({Key? key}) : super(key: key); I haven't seen that in any of the tutorials. is that some sort of constructor?

A: For the top logo part, you can simply use appBar of Scaffold.
Next comes the large box TextBox, you can use Expanded with Align widget inside column for this.
While we used Expanded it will take available height.
Therefore next two button will be at the bottom side.
I will suggest visiting and learn more about widgets, there are many ways you can handle this UI. You can search and read about every widget.
class TX extends StatelessWidget {
  const TX({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: Text("logo"),
      ),
      body: LayoutBuilder(
        builder: (context, constraints) => Column(
          children: [
            Expanded(
              child: Container(
                color: Colors.cyanAccent,
                child: const Align(
                  alignment: Alignment(0, .5),
                  child: Text("TextBox"),
                ),
              ),
            ),
            SizedBox(
              width: constraints.maxWidth,
              child: ElevatedButton(
                onPressed: () {},
                child: Text("Button"),
              ),
            ),
            SizedBox(
              height: 10,
            ),
            SizedBox(
              width: constraints.maxWidth,
              child: ElevatedButton(
                onPressed: () {},
                child: Text("Buttonx"),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

And for the key constructor already describe on comments by @Midhun MP. It is used to identify the widget tree. Check this video

A:
Does Container only allow one child?

Yes, Container() can only have one child widget.
Widgets are like lego blocks. You have to pick a widget that best suits your requirements. For Showing widgets in a single column, You can use Column() Widget. Similarly in case of row, You can represent widgets in single Row using Row() Widget. Similarly for stacking of widgets, use Stack() widget. This list goes on just like the availablility of lego blocks.
Now back to your implementation, you are going the right way. You don't need Container() at the top, Just add 4 child widgets in Column.
Column(
  children: [
    Image(),
    TextField(),
    TextButton(),
    TextButton(),
  ],
)

Study about the available customization options of these widgets and you will be able to implement this UI as per your requirements.
P.S. There are many type of buttons available in flutter. If TextButton() doesn't work for you, you can pick any other button.


text:
Q: How to update dateISO function in Jquery validation plugin In its current state, the dateISO function in the Jquery validation plugin is as follows:
dateISO: function(value, element) {
  return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);
}

I have noticed that when a user enters a date like 1991-99-99, it is seen  as a "valid date", when it obviously is not.
How would I change this code to have it validate that the month is in the range of 01-12 and the day is in the range of 1-31?

A: In general, good date validation is very difficult.  From Time and the Art of Living (as quoted in the GNU date documentation), I quote Robert Grudin:

Our units of temporal measurement,
  from seconds on up to months, are so
  complicated, asymmetrical and
  disjunctive so as to make coherent
  mental reckoning in time all but
  impossible. Indeed, had some
  tyrannical god contrived to enslave
  our minds to time, to make it all but
  impossible for us to escape subjection
  to sodden routines and unpleasant
  surprises, he could hardly have done
  better than handing down our present
  system.

However, if you only want to accept dates in that YYYY-MM-DD format, the work gets a little easier.  How about something like:
dateISO: function(value, element) {
  if (this.optional(element)) return true;
  var regexp = new RegExp('^\d{4}[\/-](\d{1,2})[\/-](\d{1,2})$');
  var matches = regexp.exec(value);
  if (!matches) return false;
  if (matches[2] > 31) return false;

  if (matches[1] == 2 && matches[2] > 28) return false;
  if ((matches[1] == 1 || matches[1] == 3 || matches[1] == 5 || matches[1] == 7 || matches[1] == 8 || matches[1] == 10 || matches[1] == 12) && matches[2] > 30) return false;

  return true;
},


text:
Q: threads package for python3.6 This is what I encountered when trying to import thread package:
>>> import thread
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packag
es/thread.py", line 3
    print('This is ultran00b's package - thread')
I tried uninstalling and install again but it won't work.

A: thread module was deprecated in python 3. Try threading instead:
import threading

A: You are trying to import the thread class ?
Use :
from threading import Thread


text:
Q: Content view binding not working I have ContentView which need ViewModel binding

Test.xaml
<ContentView.Content>
 <Frame x:Name="HelpBaseFrame" BackgroundColor="White" CornerRadius="16" HorizontalOptions="Fill" VerticalOptions="Center">
                <StackLayout>
                 <ListView HasUnevenRows="True" x:Name="lstview" SeparatorColor="White">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <ViewCell IsEnabled="False">
                                    <ScrollView x:Name="ScrollView" Orientation="Vertical" Padding="0, 1, 0, 0" BackgroundColor="Transparent" HorizontalOptions="Center">
                                        <StackLayout>
                                            <Label x:Name="LabelHeader" FontAttributes="Bold" Font="HiraginoSans-W6, 16"
                                                HorizontalOptions="Center" Margin="0,20,0,0">
                                                <Label.Text>
                                                    <Binding Path="HeaderData"></Binding>
                                                </Label.Text>
                                            </Label>
                                            <local:LineSpacingLabel x:Name="LabelHeaderDesceiption" LineSpacing="6"
                                                Font="HiraginoSans-W3, 16" FontAttributes="None" Margin="0,20,0,0">
                                                <Label.Text>
                                                    <Binding Path="DescriptionData"></Binding>
                                                </Label.Text>
                                            </local:LineSpacingLabel>
                                        </StackLayout>
                                    </ScrollView>
                                </ViewCell>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
            </StackLayout>
            </Frame>
</ContentView.Content>

BindingClass
public void SetData(Dictionary<string, string> dictionary)
    {
         ............
        lstview.ItemsSource = HelpDataList;  // HelpDataList is observable collection of HElp Data
    }

Model class :
public class HelpData : BaseViewModel
    {
        private string Header = string.Empty;
        private string Description = string.Empty;

        public string HeaderData
        {
            get { return Header; }
            set
            {
                Header = value;
                OnPropertyChanged("HeaderData");
            }
        }
        public string DescriptionData { get; set; }
    }

This view model for above view.
 This binding is not working.
 Is anything  wrong?
 This view model for above view.
 This binding is not working.
 Is anything  wrong?
 This view model for above view.
 This binding is not working.
 Is anything  wrong?

A: *

*You have to set bindingContext on the target control by using x:Reference markup extension.
BindingContext="{x:Reference Name=ViewModelField}"

Or
BindingContext="{x:Reference ViewModelField}"

*Label.Text should be binding with string not viewModel.
Text="{Binding Path=Value}"

Or
Text="{Binding Value}"  ( "Path=" part of the markup extension can be omitted if the path is the first item in the Binding markup extension)

Refer to Bindings
Update
<Binding>  is not a valid tag.
Modify the label :
<Label Text="{Binding Path = HeaderData}">


text:
Q: how to install (bower) an angular directive to a Meteor application? I have a Meteor application with an Angular frontend. I want to check for any unsaved data in forms before navigation. Found this Angular directive angular-unsavedChanges but it requires to be added with Bower. How can i use this in Meteor? (Went through previous questions, and seperately downloaded and placed the directive in lib, still not woking)
New bee to both Javascript and Angular, appreciate if you could be a little descriptive.

A: According to the basic usage instructions, you do not necessarily need to install this using Bower. You just need a hard copy of the files available in your project that can be referenced.
You should be able to set up this up with the following steps:

*

*In your Meteor project, navigate to or create a directory named public in the root directory of the project.

*Navigate to the public directory and create a new directory named bower_components.

*Copy the files from the Github repo to this directory.

*

*If using the command line, run the command git clone git@github.com:facultymatt/angular-unsavedChanges.git.

*If manually copying the files, create a new directory named angular-unsavedChanges, and save the files to this directory.

*Inside the <head></head> tags that will be rendered on the page you want to use the code on (in your component, index file, head file, etc), add <script src="/bower_components/angular-unsavedChanges/dist/unsavedChanges.js"></script>.


text:
Q: Is it always safe to assume that values of ..stream::int_type are >= 0 except for eof I want to parse a file and use an std::stringstream to parse its contents. I use get() to read it character by character, which yields an std::stringstream::int_type. Now in certain cases I want to use a lookup table to convert ascii characters into other values (for example, to deterime whether a certain character is allowed in an identifier or not).
Now can I assume that the values I get from get() are non-negative, unless it is std::stringstream::traits_type::eof()? (And hence use them as indices for the lookup tables).
I couldn't find anything in the standard regarding that, which might be due to a lack of understanding on my part how this whole bytes to characters thing works in C++.

A: First let look at the more general case of basic_stringstream.
You can't assume that eof() is negative (I see the constraint nowhere and the C standard states The value of the macro WEOF may differ from that of EOF and need not be negative.)
In general, int_type comes from the trait parameter and the description of int_type for character traits doesn't mandate that to_int_type returns something positive.
Now, stringsteam is basic_stringstream<char> and thus use char_traits<char>; eof is negative but I haven't found a mandate that to_int_type has to non-negative values (it isn't in 21.2.3.1 and I see no way to deduce it from other constraints), but I wonder if I miss something as my expectation was that to_int_type(c) had to be equivalent to (int)(unsigned char)c -- it is the case for the GNU standard C++ library and I somewhat expect to get the same behavior as in C where functions taking or returning characters in int return non-negative values for characters.)
For information, the other standard specialization of char_traits:

*

*char_traits<char16_t> and char_traits<char32_t> have an unsigned int_type, so even eof() is positive;

*char_traits<wchar_t>::to_int_type isn't mandated to return a positive value for non eof() input either (but in contrast with char_traits<char> I didn't expect such mandate to be there).


text:
Q: A group that has a $\frac{3}{2}$-transitive subgroup Do you know a group that has a $\frac{3}{2}$-transitive subgroup and it is not  $\frac{3}{2}$-transitive itself?

A: I found this group using GAP.
Let
$$ \begin{align*}
a &= (29)(36)(48)(57)\\
b &= (136)(247)(589) \\
c &= (192)(354)(687).
\end{align*}$$
And let $H=\langle a,b,c\rangle$.  This is a $\frac{3}{2}$-transitive subgroup of $S_9$ (it is a Frobenius group, with kernel $\langle b,c\rangle$). It is contained in a larger group $G$, generated by $H$ and the two elements
$$ \begin{align*}
d &= (129) \\
e &= (12)(45)(78).
\end{align*}$$
This group, just like $H$, is transitive.  But the point stabilizer of $1$ only permutes $2$ and $9$ amongst themselves, while transitively moving the other $6$ points amongst themselves.  In other words, it is not $\frac{3}{2}$-transitive.
To clarify my search, I simply looked for transitive, but not primitive, subgroups of a symmetric group (I chose $S_9$ because neither $9$ nor $9-1$ is prime). I then looked in those groups for subgroups that were Frobenius (as all $\frac{3}{2}$-transitive groups are either Frobenius or primitive).


text:
Q: How to create document upload and document list pages in Composite C1 I'm new to C1 and I'm developing a simple site, now I need to add Documents page which one lists a bunch of PDF files and document view page to display PDF in Issuu player.
First I'll ask for the part 1:
a) How to upload PDF docs? I mean how to create an Upload PDF page which one includes file upload box and description box, it would be nice if it's isolated from the backend interface.
b) How to create Documents page which one dynamically lists uploaded PDF docs?

A: 1) F.e. you have the Media Folder Path where you will store the PDFs, for example "/Uploads/PDF Documents"
Below is a sample code how to upload HttpPostedFile  to the C1 Media Archive:
public static void UploadFileToMediaArchive(HttpPostedFile file, string mediaFolderPath)
    {
        try
        {
            WorkflowMediaFile mediaFile = new WorkflowMediaFile();
            mediaFile.FileName = file.FileName;
            mediaFile.FolderPath = mediaFolderPath;
            mediaFile.Title = "";
            mediaFile.Description = "";
            mediaFile.Culture = Thread.CurrentThread.CurrentCulture.Name;
            mediaFile.Length = file.ContentLength;
            mediaFile.MimeType = MimeTypeInfo.GetCanonical(file.ContentType);

            if (mediaFile.MimeType == MimeTypeInfo.Default)
            {
                mediaFile.MimeType = MimeTypeInfo.GetCanonicalFromExtension(System.IO.Path.GetExtension(mediaFile.FileName));
            }
            using (System.IO.Stream readStream = file.InputStream)
            {
                using (System.IO.Stream writeStream = mediaFile.GetNewWriteStream())
                {
                    readStream.CopyTo(writeStream);
                }
            }
            IMediaFile addedFile = DataFacade.AddNew<IMediaFile>(mediaFile);
        }
        catch (Exception ex)
        {
            Composite.Core.Log.LogError("UploadFileToMediaArchive", ex.Message);
        }
    }

2) To display PDFs files on the page you can create a simple XSLT function, then use "data-centric" function call "GetIMediaFileXml" and use MediaFolderFilter filter. Below is the source code of the "GetIMediaFileXml" function call:
    <f:function name="Composite.Data.Types.IMediaFile.GetIMediaFileXml" localname="GetIMediaFileXml">
    <f:param name="PropertyNames">
        <f:paramelement value="KeyPath" />
        <f:paramelement value="CompositePath" />
    </f:param>
    <f:param name="Filter">
        <f:function name="Composite.Data.Types.IMediaFile.MediaFolderFilter">
            <f:param name="MediaFolder" value="MediaArchive:7dce5da6-ae73-417a-86a3-dfb7a3f05cf3" />
        </f:function>
    </f:param>
</f:function>


text:
Q: HTTP OPTIONS verb handling with LIFT I'm using LIFT to serve a RESTful API, and I want this API to allow requests using CORS (Cross-Origin Resource Sharing) for POST. I do have CORS working with GET requests.
I'm having trouble because cross-origin POSTs first call OPTIONS on the given URL, and I haven't figured out how to accept OPTIONS requests with LIFT.
My question is: What do I need to mixin or write to my serve{} block such that I can allow the HTTP verb OPTIONS for a given path in LIFT?
Right now using curl I get:
curl -X OPTIONS http://localhost:8080/path => [404]

I'm using LIFT 2.4-M5 and Scala 2.9.1
EDIT: Based on pr1001's suggestion, I was trying to extend RestHelper like so:
import net.liftweb.http.provider._
import net.liftweb.http._

trait RestHelper extends net.liftweb.http.rest.RestHelper {
    protected object Options {
        // Compile error here with options_?
        // because net.liftweb.http.Req uses LIFT's RequestType
        def unapply(r: Req): Option[(List[String], Req)] =
            if (r.requestType.options_?) Some(r.path.partPath -> r) else None
    }
}

@serializable
abstract class RequestType extends net.liftweb.http.RequestType {
    def options_? : Boolean = false
}

@serializable
case object OptionsRequest extends RequestType {
    override def options_? = true
    def method = "OPTIONS"
}

object RequestType extends net.liftweb.http.RequestType {
    def apply(req: HTTPRequest): net.liftweb.http.RequestType = {
        req.method.toUpperCase match {
            case "OPTIONS" => UnknownRequest("OPTIONS")
            case _ => net.liftweb.http.RequestType.apply(req)
        }
    }

    def method = super.method
}

I feel like this is more work then I should need to do because I don't want to have to extend Req with my own RequestType impl.
I'm definitely on the lower level of skill set when it comes to Scala, so I'm hoping someone can provide a bit simpler solution because I'm sure there's something I'm missing.

A: Are you using RestHelper? If so you'd specify the type of request you want to respond to and return a LiftResponse. There's no OptionRequest in Lift (yet) to use in the partial function you pass to serve() but you should be able to extend RequestType with your own version. Using UnknownRequest – as in UnknownRequest("OPTION") – might also do the trick.
This might also be worth bringing up on the mailing list, as CORS support would be a useful addition...

A: Many thanks to pr1001 for his suggestion. I was able to get it working with the following:
import net.liftweb.http._

class RequestTypeImproved(requestType: RequestType) {
    def options_? : Boolean = requestType.method == "OPTIONS"
}

trait RestHelper extends net.liftweb.http.rest.RestHelper {
    implicit def req2ReqImproved(requestType: RequestType): RequestTypeImproved = {
        new RequestTypeImproved(requestType)
    }

    protected object Options {
        def unapply(r: Req): Option[(List[String], Req)] =
            if (r.requestType.options_?) Some(r.path.partPath -> r) else None
    }
}

Then:
serve {
    case req @ "path" Options _ => {
        LiftResponse(...)
    }
}


text:
Q: jquery validate - redefine registration/settings after initial call to validate()? I am running into issues with using the jquery validate plugin on a page where I am asynchronously loading content with .load(). I am reloading a section of the page where my registered errorContainer exists, and I can't figure out a way to re-register the setting after the content is loaded with another call to validate(). I took a look at the internals of the plugin and it looks like the initialization/registration of the settings and properties isn't happening in the validate method because the validator object exists and the initialization is skipped over. Is there any supported way to reregister or edit these settings? I am using version 1.8.1.
Edit: I understand I can probably work around this by using the showErrors callback or using some custom css class to position the auto-generated label where I need it, but I'm interested in knowing if there is a way to maintain the use of errorContainer by modifying the setting I've provided in validate() without having to resort to a workaround.

A: The short answer is "no".
Once the .validate() method is invoked, the plugin is initialized.  Since any subsequent call to .validate() is ignored, there is no way to change any of the options.  There are no workarounds.
The only exception to this are the rules & messages options which can be modified at any time using the .rules('add') and .rules('remove') methods.

Any contact with the developer, bug reports, feature requests, etc, should be done at his GitHub page:
https://github.com/jzaefferer/jquery-validation/issues


text:
Q: ControlTemplate.Trigger not working on CellValuePresenter (TargetType) I 'm using Infragistics 2014.2. I have a XamDataGrid which display the data with dynamic columns, the grid is formatted by its default style and in addition, some of the columns having alignment set to Right (decimal type columns) with some value masking on it and the rest are set alignment to Left.
I want to remove the default CellValuePresenter style of XamDataGrid and write a new style with only TextBlock/ContentPresenter on it instead of CellValuePresenter for each cell and after applying new style, the alignment and masking of the cells should remain same. The reason behind applying this new style is i want the copy of the same grid to display it on another window with no data manipulation in it.
Can you please look at the following code that i have tried to achieve the same(even with many of the changes in it), but it doesn't seems to work anyhow.
    <Style x:Key="PreviewCellValuePresenterStyle" TargetType="{x:Type igDP:CellValuePresenter}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate x:Name="CellValuePresenterControlTemplate" TargetType="{x:Type igDP:CellValuePresenter}">
                    <ContentPresenter x:Name="ContentValuePresenter"
                                     VerticalAlignment="Center"
                                     ContentSource="Value"
                                     Margin="4,3,4,4"/>
                    <ControlTemplate.Triggers>
                        <Trigger Property="HorizontalAlignment" Value="Right">
                            <Setter TargetName="ContentValuePresenter" Property="TextBlock.TextAlignment" Value="Right"></Setter>
                        </Trigger>
                        <Trigger Property="HorizontalContentAlignment" Value="Right">
                            <Setter TargetName="ContentValuePresenter" Property="TextBlock.TextAlignment" Value="Right"></Setter>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Right now, i'm only setting the alignment property for testing. In the above code, have tried TextBlock in place of ContentPresenter but the trigger never gets invoked. I don't where i'm doing wrong.
Can you anyone help me to get out of this?
Thanks

A: If your intention of using text block is only for alignment/appearance, then you can just use setters to set these values.

            <Style x:Key="PreviewCellValuePresenterStyle" TargetType="{x:Type igDP:CellValuePresenter}" >
                    <Setter Property="FontWeight" Value="DemiBold"/>
                    <Setter Property="Height" Value="24"/>
                    <Setter Property="HorizontalContentAlignment" Value="Center"/>
                    <Setter Property="VerticalContentAlignment" Value="Top"/>
             </Style>

But, If you need some other implementations like value masking, or need text block to be there,

 <Style x:Key="PreviewCellValuePresenterStyle" TargetType="{x:Type igDP:CellValuePresenter}">
                                                    <Setter Property="Template">
                                                        <Setter.Value>
                                                            <ControlTemplate TargetType="{x:Type igDP:CellValuePresenter}">
                                                                <TextBlock HorizontalAlignment="Center" Style="{DynamicResource TextStyle}">
                                                                </TextBlock>
                                                            </ControlTemplate>
                                                        </Setter.Value>
                                                    </Setter>
                                                </Style>

    <Style x:Key="TextStyle" TargetType="{x:Type TextBlock}">

            <Setter Property="BorderThickness" Value="1"/>

            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
      </Style>


text:
Q: Why a provider combination will not notify its new state in a dart test? I am new to riverpod and I am following the documentation on the providers combination.
I get a behaviour that I don't understand when combining providers and testing the output in a dart test (outside test_widgets).
I tried to outlined it in a simple code as below :
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:riverpod/riverpod.dart';

final positiveProvider = StateProvider<int>((ref) => 0);

final negativeProvider = StateProvider<int>((ref) => 0);

final combinedProvider = Provider<int>((ref) {
  final positive = ref.watch(positiveProvider);
  final negative = ref.watch(negativeProvider);

  print('Counter state: ${positive - negative}');
  return positive - negative;
});

class CounterListener extends Mock {
  void call(int? previous, int value);
}

void main() {
  test('Test riverpod provider combination', () {
    final container = ProviderContainer();
    addTearDown(container.dispose);

    final counterListener = CounterListener();

    container.listen(combinedProvider, counterListener, fireImmediately: true);

    verify(counterListener.call(null, 0)).called(1);

    container.read(positiveProvider.state).state = 1;

    verify(counterListener.call(0, 1)).called(1);
  });
}

I am getting this results :
Counter state: 0 No matching calls. All calls: [VERIFIED] CounterListener.call(null, 0) (If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.) package:test_api              fail
_VerifyCall._checkWith
_makeVerify.<fn> main.<fn>

✖ Test riverpod provider combination Exited (1)

The behaviour is that the combined provider does not automatically fire its  inner function, which I thought it would do.
I am not sure if I misunderstood the coding pattern required for combining providers, or if it comes from the container logic in a test that is not "watched" but "listened to".
Thanks for your help,

A: The provider code was right but the test's one wasn't.
The container tear down and the second verification after method called happened before the all code finished executing.
Puting the tear down at the end and a simple Future.delayed after method called resolves the issue.


text: Q: how to upgrade to Qt 5.5.1 I already have Qt 5.5.0 on my Ubuntu 18.04.6 LTS (32-bit) and want to upgrade it to Qt 5.5.1 (I don't need to install Qt creator necessarily). Can anyone help me to find a proper way? I'm new in Qt.