text:
Q: Scala for loop with multiple variables How can I translate this loop (in Java) to Scala?
for(int i = 0, j = 0; i < 10; i++, j++) {
  //Other code
}

My end goal is to loop through two lists at the same time.
I want to get both elements at the same time at each index in the iteration.
for(a <- list1, b <- list2) // doesn't work

for(a <- list1; b <- list2) // Gives me the cross product

A: Use .zip() to make a list of tuple and iterate over it.
val a = Seq(1,2,3)
val b = Seq(4,5,6)
for ((i, j) <- a.zip(b)) {
  println(s"$i $j")
}
// It prints out:
// 1 4
// 2 5
// 3 6

A: If you have multiple list to iterate over, just use .zipped on the tuple of the lists.
val l1 = List(1, 2, 3)
val l2 = List(4, 5, 6)
val l3 = List("a", "b", "c")

for ((c1, c2, c3) <- (l1, l2, l3).zipped) {
    println(s"$c1, $c2, $c3")
}

//Prints
1, 4, a
2, 5, b
3, 6, c


text:
Q: Intellij android studio (Flutter) code completion suggestions are not sorted properly I have an annoying problem,  Code Completion in Flutter (Dart) suggestions are not sorted properly , when i start to type, suggestions sorted are not order then expected, i have to type all the words to get the relevant suggestion, you can see in the picture. This problem occurs all of the suggestions.
Expected result (I was following a training online): .push comes up in the first place
In my situation:
.push is in the 10th place
I search and the internet but couldn't find a solution, i try to reinstall flutter and dart plugin. Invalidate cache but no luck. Please help me to solve this annoying problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rewrite urls ending with _word.html into ?word How to rewrite a url via .htaccess so that urls ending with:
_slides.html

become accessible via
?slides

a typical url looks like this on the server:
website.com/directory1/_slides.html

A: Try adding this to the htaccess file in your document root:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^([^=]+)$
RewriteRule ^([^/])*/$ /$1/_%1.html [L]

That should take a request like http://website.com/directory1/?slides and serve the content at /directory1/_slides.html.
To redirect direct access to _ files, you can also add:
RewriteCond %{THE_REQUEST} \ /([^/]*)/_([^.\ \?]+)\.html(\ |$)
RewriteRule ^ /%1/?%2 [L,R=301]

A: Do you mean you want to rewrite "/$any/_slides.html" into "/$any/?slides" ? Then please try this:
RewriteEngine on
RewriteRule ^/?([^/]+)/_slides.html$ /$1/?slides [L]

Or the opposite? Like this (for I'm confused in your question):
RewriteEngine on
RewriteRule ^/?([^/]+)/\?slides$ /$1/_slides.html [L]

Last Attempt
Now I know that you want to view "/$any/?slides" with the content of "/$any/slides_html", now try to make sure that your .htaccess file is located in the root of your domain and try this:
RewriteEngine on
RewriteCond %{QUERY_STRING} ^slides$
RewriteRule ^/?([^/]+)/$ /$1/_slides.html [L]

If these directives didn't work, then it's not possible for a dynamic directory with query string to be rewritten.


text:
Q: Aurora reader storage cost that should be simple, but I cannot figure that out
Amazon bills the real used storage amount for Aurora databases, not the allocated storage like for non-Aurora.
there is a metric VolumeBytesUsed - The amount of storage used by your Aurora DB instance. This metric applies to an entire Aurora DB cluster, not for instance.
https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Monitoring.html
I have a cluster of 1 Arora Writer and 2 Readers. DB size is about 10 Gb and VolumeBytesUsed shows 10Gb.
According to documentation, each Aurora node has its own data copy - https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.html
So if I have 10Gb DB - Aurora Writer and 2 Readers should be using 10x3 = 30 Gb of storage, but VolumeBytesUsed shows 10Gb
Will I be billed for 10 Gb or 30 Gb in that case?

A: From the Aurora MySQL FAQ, which I found linked from the pricing page.

Q: Amazon Aurora replicates each chunk of my database volume six ways
across three Availability Zones. Does that mean that my effective
storage price will be three or six times what is shown on the pricing
page?
No. Amazon Aurora's replication is bundled into the price. You are
charged based on the storage your database consumes at the database
layer, not the storage consumed in Amazon Aurora's virtualized storage
layer.

Based on what I know about AWS (quite a bit) and what I've read (not a lot) I think each database is charged once for storage. That means if you have a 10GB database service with two 10GB read replicas you'll be charged for 30GB of storage.

A: here is what I got from support:

Aurora by design, is managed in a clustered format. Both writer and
reader instances of aurora cluster are associated with same storage
layer hence there will not be any extra charge for storage when you
provision additional reader instance. The charges to aurora cluster
are calculated on a cluster level so if you have one writer and one
(or more) reader instance, you will be charged as below:

*

*Cost of DB instances (if you have one writer and one reader, you
will be charged for two instances)

*Total storage on cluster level

*Total IO consumed on cluster level

*Charges for backtrack feature (if applicable)

*Charges for Snapshot export (if applicable)

*Charges for cross-AZ data transfer in same region (if applicable)


text:
Q: JavaScript array handling: What am I doing wrong? I have the following code:

I want to show all the five div's with this JavaScript code. But it isn't working. The div's don't show up. What am I doing wrong? Many thanks in advance.


text:
Q: How do I write an encoded jpeg as bytes to Tensorflow tfrecord and then read it? I am trying to use tensorflows tfrecords format to store my datasets.
I managed to read in jpeg images and decode them to raw format and write them to a tfrecord file. I can then later read them using tf.decode_raw.
The problem is that this leads to huge file sizes because I am storing the images as raw. Now I have seen many tutorials and blogs saying I can store them in an encoded format and then when reading them just decode them. I can't find any example of this. I have been trying for a while but no matter what way I do it I'm getting formatting errors.
TLDR
Does anyone know how to write images to a tfrecord file as jpegs and not as raw.
Thank You,
David.
My writing function.
def convert(image_paths, labels, out_path):

num_images = len(image_paths)

with tf.python_io.TFRecordWriter(out_path) as writer:
    for i, (path, label) in enumerate(zip(image_paths, labels)):

        print_progress(count=i, total=num_images-1)
        img = open(path, 'rb').read()

        data ={'image': wrap_bytes(img),
            'label': wrap_int64(label)}

        feature = tf.train.Features(feature=data)
        example = tf.train.Example(features=feature)
        serialized = example.SerializeToString()
        writer.write(serialized)

Convert dataset with this:
{convert(image_paths=image_paths_train,
    labels=cls_train,
    out_path=path_tfrecords_train)}

My Reading Function
def parse(serialized):

features = \
    {
        'image': tf.FixedLenFeature([], tf.string),
        'label': tf.FixedLenFeature([], tf.int64)
    }
parsed_example = tf.parse_single_example(serialized=serialized,
                                         features=features)

# Get the image as raw bytes.
image_raw = parsed_example['image']

# Decode the raw bytes so it becomes a tensor with type.
image = tf.image.decode_image(image_raw,channels=3)

#image = tf.decode_raw(image_raw, tf.uint8)

# The type is now uint8 but we need it to be float.
image = tf.cast(image, tf.float32)

# Get the label associated with the image.
label = parsed_example['label']

# The image and label are now correct TensorFlow types.
return image, label

A: For writing, just open the file as a binary file (fp = open('something.jpg', 'rb')) and .read() its content. Store that content in the tfrecord Example as you store the image now (i.e., as a bytes feature).
For reading, instead of doing decode_raw, use tf.image.decode_image and pass in the tensor you get from the sample reader.
If you post your code, I can provide better code examples, but not knowing how your code looks like this is as detailed as I can get.


text:
Q: Java okhttp3 How can I parse dynamic web content? When visiting a website with dynamic content, how do I get the  URL content that would appear in a browser after it has finished processing JavaScript?
For example, okcupid.com/visitors displays the names of users that most recently visited your profile.  Using okhttp3's standard request/response methods, the URL contents just has placeholders for where the the users name/picture should be.
*EDIT: I've added the that handles all requests in my project.  In general this coade handles requests with session cookie and access token without a hitch. It's only the contents of URL's that return dynamic content.
public void sendRequest(String URL, String method, String params) {
    okhttp3.Request request;
    if(method.equals("POST")) {
        RequestBody formBody = new FormBody.Builder()
                .build();
        request = new okhttp3.Request.Builder()
                .url(URL)
                .post(formBody)
                .addHeader("Cookie", this.sessionCookie)
                .addHeader("Authorization", "Bearer " + this.accountManager.accessToken)
                .build();
    } else {
        request = new Request.Builder()
                .url(URL)
                .get()
                .addHeader("Cookie", this.sessionCookie)
                .build();
    }
    try {
        this.response = client.newCall(request).execute();
        ResponseBody responseBody = this.response.body();
        this.contentsOfUrl = responseBody.string();

        try {
            if(this.sessionCookie.equals("")) {
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    String headerKey = headers.name(i);
                    String headerValue = headers.value(i);
                    if (headerKey.equals("Set-Cookie")) {
                        if (headerValue.startsWith("session=")) {
                            this.sessionCookie = utils.findString(headerValue, "(session=[a-zA-Z0-9,%]+);", 1);
                        }
                    }
                }
            }
        } finally {
            responseBody.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}


text: Q: URL redirection within WARs in the EAR file Have an EAR file which has multiple WARs. Want to redirect using jsp, from war1 to war2 with context root to load its jsp and consequently the scripts of that war. And also be able to redirect as necessary. The URL should not change during this redirection (due to limitations...)  using Websphere as the app server. Please advise - thanks in advance!


text:
Q: Apple's own instructions on how to make horizontally scrollable UIScrollView with Auto-layout do not work? I am trying to make simple UIScrollView containing single "Content View" and scrolling horizontally only. It should be fairly easy given there are step-by-step instructions from Apple. Only, it does not seem to work - the UIScrollView still scrolls both directions.
Here is screenshot of complete view hierarchy with all constants. Selected is the constant that should (according to 6. in Apple's docs linked above) prevent vertical scrolling.

Here is screenshot from device proving that the "Content View" can still be scrolled vertically. I set background color of the scroll view to white, background of the "Content View" to black and a view that contains scorllview (top-most container) is light grey. Because you can see white strip over black "Content View" you can also scroll black "Content View" up.

Is there something I am missing? If not is there a workaround?

A: Most likely the view controller is set to automatically inset the scroll view. This setting is useful if the scroll view sits behind a navigation bar but is sometimes problematic. In the storyboard check the setting on the view controller and remove it.


text:
Q: Returning local variable from a function in c++? This is excerpted from one of the c++ tutorials:
// vectors: overloading operators example
#include <iostream>
using namespace std;

class CVector {
  public:
    int x,y;
    CVector () {};
    CVector (int,int);
    CVector operator + (CVector);
};

CVector::CVector (int a, int b) {
  x = a;
  y = b;
}

CVector CVector::operator+ (CVector param) {
  CVector temp;
  temp.x = x + param.x;
  temp.y = y + param.y;
  return (temp);
}

int main () {
  CVector a (3,1);
  CVector b (1,2);
  CVector c;
  c = a + b;
  cout << c.x << "," << c.y;
  return 0;
}

In the operator overloading function, it creates a local var temp then returns it, I am quite confused, is this the right way?

A: "is this the right way?"
Yes it is. Note that it is not local variable, but a copy of local variable that is actually returned, which is perfectly valid and right thing to do. Be cautious about returning local variables while returning by pointer or reference, not while returning by value.

A: Yes, because it's returned by value. Had the function had the signature that follows, it would not have been correct:
CVector& CVector::operator+(CVector param);

By the way, a more efficient implementation would look like:
CVector CVector::operator+(const CVector &param) const;


text:
Q: Create one partition occupying all the space on the drive with gparted? I am following the instructions here: https://help.ubuntu.com/community/InstallingANewHardDrive
It says:

4) Create one partition occupying all the space on the drive:
(parted) mkpart primary 0 0
5) Check that the results are correct:
(parted) print

However when I do this I get:
$sudo parted /dev/sda
GNU Parted 3.2
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) mklabel gpt
(parted) unit GB
(parted) mkpart primary 0 0
(parted) print
Model: ATA Some SSD (scsi)
Disk /dev/sda: 240GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags:

Number  Start   End     Size    File system  Name     Flags
 1      0.00GB  0.00GB  0.00GB               primary

The Start and End of 0GB and Size of 0GB is making me think this isn't correct.  I would have thought the size should have been 240GB (or close to it).  Are these instructions correct? If not, what is the correct way to make a single partition that covers the entire disk?

A: Your mkpart line is wrong. The parameters are: partition-name, start-position and size.
In parted, run
`rm primary`
`mkpart primary 2048s 100%`

to remove the old, wrong, partition and recreate a new that spans the whole disk.

A: Using 0% for the start causes parted to automatically align the sectors for best performance:
(parted) mkpart primary 0% 100%
Credits to comments in article at https://rainbow.chard.org/2013/01/30/how-to-align-partitions-for-best-performance-using-parted/
PS: u could also specify the filesystem type in same command, e.g for xfs:
(parted) mkpart primary xfs 0% 100%


text:
Q: Prestashop 1.6 - edit site in code I am using PRESTASHOP 1.6 and i am  trying to edit some page content like class in header. I try edit or delete all TPL files in directory /themes/default-bootstrap and no one make changes on my web page?
How i can edit header or any other part of my page with code?

A: As mentioned by ébewè in the comment section, first check that you are using the right theme in Preferences > Themes in your backoffice. Then check in Advanced Parameters > Performance that in Smarty section Never recompile template files isn't checked or use the clear cache option.


text:
Q: Finding the Isomomorphism(honomorphism) from $S_n$ to $S_n$ To find the homomorphsim $\tau$ (or isomorphism $\phi$), Only just I do is observing the mapping of the generator of the group. Plus, the group $S_n = \langle (1,2),(1,2,...,n) \rangle = \langle (1,2),(1,3),...,(1,n) \rangle$
Let me take the case for $n=3$
It is well known fact that the number of the homomorphsim is $10$, isomorphism is $6$ considering the generator $S_3 = \langle (1,2),(1,2,3) \rangle $
So, I tried different way considering the generator $S_3 = \langle (1,2),(1,3) \rangle$
First isomorphism $\phi : S_3 \to S_3 $, Each generating set of $S_3$ maps to another generating set of $S_3$
Therefore, there are two cases firstly "$\phi(1,2) =(1,2) $ and $\phi(1,3) =(1,3)$" Secondly  "$\phi(1,2) =(1,3) $ and $\phi(1,3) =(1,2)$".
So there are two isomorphism $S_3 \to S_3$ contradicted with the answer is $6$
Second homomorphism $\tau : S_3 \to S_3$, both of the the order of the $\tau(1,2)$ and $\tau(1,3)$ should be divisor of the $2$.
Hence $\tau (1,2), \tau (1,3) \in \{id,  (1,3), (1,2), (2,3) \} $. The number of the homomorphism is $16$
Again this is contradict with the fact that $10$
I confidently do say my answer $2$ and $16$ is wrong, But the problem is I can't find which point I was wrong.
Any advice and answer always appreciated.
Thanks.

A: Note that if $\tau(1,2)=e$ (where $e$ is the identity), then $$\tau(1,2,3)=\tau((1,2)(1,3))=\tau(1,2)\tau(1,3)=\tau(1,3)$$ but $\tau(1,2,3)$ has order dividing three while $\tau(1,3)$ has order dividing two, so they both must have order one, that is, necessarily $\tau(1,3)=e$, whence $\tau$ is the trivial homomorphism mapping everything to the identity. That cuts down your count of homomorphisms considerably.


text:
Q: Pro*C program run properly in AIX but not in RHEL I have some trouble running a binary done with proC code. I can compile it (without warnings) in my new server RHEL (7.8) but it loops until it failed. I made a simple proC script to test the compilation (see below). This script runs easily in my previous server AIX (6.1.0.0). The DB is Oracle 11c.

*

*Oracle client in AIX : .../oracle/10.2

*Oracle client in RHEL : .../oracle/12102/cli64

Here my simple code I want to compile and execute :
#include "demo.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sqlca.h>
#include <oraca.h>

int code_erreur;
char libelle_erreur[200];

EXEC ORACLE OPTION (ORACA=YES);

EXEC SQL BEGIN DECLARE SECTION;
    VARCHAR username[30];
    VARCHAR password[30];
    VARCHAR host[30];

    VARCHAR dynstmt[80];
    VARCHAR mData[81];

EXEC SQL END DECLARE SECTION;

int connect()
{
    printf("\nConnection to %s@%s\n",username.arr,host.arr);

    EXEC SQL CONNECT :username IDENTIFIED BY :password USING :host;

    printf("Connection established\n");
    return 0;
}

void sqlerr()
{
    code_erreur = sqlca.sqlcode;
    strcpy(libelle_erreur,sqlca.sqlerrm.sqlerrmc);
    printf("SQL ERROR : %d,%s ;\n", code_erreur,libelle_erreur);
    printf("sqlca.sqlerrd : %d\n",sqlca.sqlerrd[2]);
}

int loadData()
{
    int lIter;

    strcpy(dynstmt.arr, "SELECT BANNER FROM V$VERSION\n");
    dynstmt.len = strlen(dynstmt.arr);

    printf("%s", (char *)dynstmt.arr);

    EXEC SQL PREPARE S FROM :dynstmt;
    EXEC SQL DECLARE lCursorData CURSOR FOR S;
    EXEC SQL OPEN lCursorData;

    for (lIter=0;lIter<10;lIter++)
    {
        EXEC SQL WHENEVER NOT FOUND DO break;
        EXEC SQL FETCH lCursorData INTO :mData;
        printf("%s\n", mData.arr);
    }
    EXECL SQL CLOSE lCursorData;
    return 0;
}

void main()
{
    int lRetour=0;
    printf("Start demo\n");

    strcpy((char *)username.arr,"USER");
    username.len=(unsigned short)strlen((char *)username.arr);

    strcpy((char *)password.arr,"PASS");
    password.len=(unsigned short)strlen((char *)password.arr);

    strcpy((char *)host.arr,"HOST");
    host.len=(unsigned short)strlen((char *)host.arr);

    EXEC SQL WHENEVER SQLERROR do sqlerr();
    lRetour = connect();
    lRetour = loadData();

    EXEC SQL COMMIT WORK RELEASE;

    printf("End demo\n");
    exit(0);
}

When I compile it and execute it on my AIX server, here what I got :
Start demo

Connection to USER@HOST
Connection established
SELECT BANNER FROM V$VERSION
[...]
End demo

But when I compile it on RHEL and execute it, the binary loops until a memory fault :
[...]
Connection to USER@HOST

Connection to USER@HOST

Connection to USER@HOST
Memory fault

Of course I want the same AIX result in RHEL.

A: Your connect function should be defined as static, otherwize it replaces connect(2) library function from libc.
@@ -20,7 +20,7 @@

 EXEC SQL END DECLARE SECTION;

-int connect()
+static int connect()
 {
     printf("\nConnection to %s@%s\n",username.arr,host.arr);

@@ -57,7 +57,7 @@


text:
Q: Resolvent Operator in QM In a lecture, the tutor mentioned that

"when the discrete energy spectrum becomes continuous and the poles of the resolvent shrink into a continuous line. Therefore it becomes a branch cut".

This is not clear to me. I understand that the poles of the resolvent are the energy eigenvalues, but how come the singularity become a branch point in the continuous case? It would be great if someone could make this clear to me.

A: As nicely explained by Ron Maimon in this answer, one can think of a branch cut as a continuous line of poles each with an infinitesimal residue. For example, quoting him, $$\int_a^b \frac{1}{z-u} \mathrm du= \log \left( \frac{z-a}{z-b} \right)$$
with the latter indeed having a branch cut between $z =a $ and $z=b$.
For example if $b= - a$, the multi-valued function on the right-hand side looks like

(image courtesy of MIT OpenCourseWare)


text:
Q: How to delete data that has foreign key in jpa java I have use case, a Book has one Category and a Category could belong to a lot of Books. One Book could belong to multi Authors and an Author could belong to multi books. So, here is their relationship:

*

*Book to BookCategory => many-to-one

*BookCategory to Book => one-to-many

*Book to Author and Author to Book => many-to-many
So, I have 4 table:

*

*book

*book_category

*author

*book_author (book_id, author_id)

Case:

*

*if I delete a Book, there should nothing happen to the book_category table

*If I delete a Book, the Author should be deleted if the Author not belong to any books anymore. For example, I have book1 and book2 with same Author named John. If I delete book1, it wont delete John. But if I delete book2 also, then John will be deleted from Author table. Also, any book deletion will affect book_author table.

here is how I declare the entity
Author
@Entity(name = "author")
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "name", nullable = false)
    private String name;
    @Column(name = "address", nullable = false)
    private String address;
    @ManyToMany(mappedBy = "author", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JsonBackReference
    private Set<Book> book;
}

Book
@Entity(name = "book")
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "title", nullable = false)
    private String title;
    @Column(name = "year", nullable = false)
    private String year;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(
      name = "book_author",
      joinColumns = @JoinColumn(name = "book_id", referencedColumnName = "id"),
      inverseJoinColumns = @JoinColumn(name = "author_id", referencedColumnName = "id"))
    @JsonManagedReference
    private Set<Author> author;
    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "category_id", referencedColumnName = "id", nullable = false)
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    private BookCategory category;
}

Book Category
@Entity(name = "book_category")
public class BookCategory {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "category", nullable = false)
    private String category;
}

and here is how I try to delete the book. Just a simple method. But, after I run this, it show error said org.postgresql.util.PSQLException: ERROR: update or delete on table "book_category" violates foreign key constraint "fk5jgwecmfn1vyn9jtld3o64v4x" on table "book", which seems like the method try to also delete the book_category table.
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<?> delete(@PathVariable(value = "id") Long id) throws Exception {
        try {
            bookService.deleteById(id);
            return ResponseEntity.ok().body("delete done");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

Then, how to achieve it? Any clue, please?

A: I guess the problem is the cascade = CascadeType.ALL in the category field in Book class.
Using CascadeType.ALL, whenever you try to delete a Book, its category must be deleted too. The problem is that it might exist other books instances with the category you want to delete in your database. Then, a constraint database error will be thrown.
So, I would recommend using cascade = CascadeType.PERSIST or cascade = CascadeType.MERGE in the category field. In this way, when you delete a book, the category will not be deleted.
This link will give you a better understanding of cascade types, showing how it works.
I tend to avoid using cascades, especially CascadeType.ALL and CascadeType.REMOVE. I prefer to make several calls to the persistence layer in order to perform some business task (similar to those at the beginning of your question in the enumerated items - if I delete a book ..). Besides, Spring allows you to put all calls in a transaction using @Transactional in any method of your business layer.


text:
Q: Retrieving child from a Foreign Key in Salesforce I've a parent object (Product) and a child (Inventory). I'm trying to retrieve the value of the child object from a DisplayProducts class that I've created.
public class DisplayProducts {
    private Product__c products;

public DisplayProducts(Product__c item) {
    this.products = item;

}

// Properties for use in the Visualforce view
public String name {
    get { return products.Name; }
}

public String colour {
//error here
        get { return  products.Inventorys__r.Colour__c; }

    }

public class Product {

public List<DisplayProducts> getProducts() {

        if(products == null) {
            products = new List<DisplayProducts>();

            for(Product__c item : [Select ProductID__c,Name, Price__c, (SELECT Inventory__c.Size__c, Inventory__c.Colour__c,  Inventory__c.Quantity__c FROM Product__c.Inventorys__r)
                From Product__c WHERE ProductID__c = :prodID]) {

                products.add(new DisplayProducts(item));
            }
    }
    return products;
}

}

I keep getting a compile error: invalid FK relationship.
I tried
products.Inventorys__r[0].Colour__c;
but it will only retrieved the first element.
How do I retrieve the child item via the DisplayProducts Class? Any help will be greatly appreciated.
Thank you.


text:
Q: JFreeChart Candlestick pointer I have JFreeChart like this:

And I want to add mouse pointer to the chart similar to the HighCharts uses:

Here is my variation of the code shown here that creates the JFreeChart:
import org.jfree.data.xy.AbstractXYDataset;
import org.jfree.data.xy.DefaultOHLCDataset;
import org.jfree.data.xy.*;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.CandlestickRenderer;
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.text.*;
import java.util.*;

public class ChartOHLC extends ChartPanel {

    public ChartOHLC() {
        super(dajGraf());
        setMaximumDrawHeight(2000);
        setMaximumDrawWidth(3000);
    }

    public static JFreeChart dajGraf() {

        // premenne
        String stockSymbol = "AAPL";
        final DateAxis domainAxis = new DateAxis("Date");
        NumberAxis rangeAxis = new NumberAxis("Price");
        CandlestickRenderer renderer = new CandlestickRenderer();
        XYDataset dataset = getDataSet(stockSymbol);
        XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);

        //Do some setting up, see the API Doc
        renderer.setSeriesPaint(0, Color.BLACK);
        renderer.setDrawVolume(false);
        rangeAxis.setAutoRangeIncludesZero(false);

        //Now create the chart and chart panel
        JFreeChart chart = new JFreeChart(null, null, mainPlot, false);
        mainPlot.setDomainPannable(true);
        mainPlot.setRangePannable(true);
        return chart;
    }

   private static AbstractXYDataset getDataSet(String stockSymbol) {
        //This is the dataset we are going to create
        DefaultOHLCDataset result;
        //This is the data needed for the dataset
        OHLCDataItem[] data;
        //This is where we go get the data, replace with your own data source
        data = getData(stockSymbol);
        //Create a dataset, an Open, High, Low, Close dataset
        result = new DefaultOHLCDataset(stockSymbol, data);
        return result;
    }

   private static OHLCDataItem[] getData(String stockSymbol) {
        ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
        try {
            String strUrl = "http://ichart.yahoo.com/table.csv?s=" + stockSymbol + "&a=2&b=1&c=2014&d=3&e=1&f=2014&g=d&ignore=.csv";
            System.out.println(strUrl);
            URL url = new URL(strUrl);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            DateFormat df = new SimpleDateFormat("y-M-d");
            String inputLine;
            in.readLine();
            while ((inputLine = in.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(inputLine, ",");
                Date date = df.parse(st.nextToken());
                double open = Double.parseDouble(st.nextToken());
                double high = Double.parseDouble(st.nextToken());
                double low = Double.parseDouble(st.nextToken());
                double close = Double.parseDouble(st.nextToken());
                double volume = Double.parseDouble(st.nextToken());
                double adjClose = Double.parseDouble(st.nextToken());
                OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
                dataItems.add(item);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }

        //Data from Yahoo is from newest to oldest. Reverse so it is oldest to newest
        Collections.reverse(dataItems);

        //Convert the list into an array
        OHLCDataItem[] data = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
        return data;
    }

}

Is is possible to add the mouse pointer to CandleStick JFreeChart?


text:
Q: how to fool jqXHR to succeed always I'm trying to make jQuery's ajax calls always return as if they succeeded,
e.g. even when I don't have network, I will return some locally saved data
It that possible?
I tried using the $.ajaxPrefilter and calling the success function of the jqXHR,
but still it won't behave as if the request has finished :(
Thanks!

A: If im understanding you correctly, you want to make the jqXHR act like it succeeded, when it actually failed?
If so, .pipe is your friend :)
var jqDeferred = $.ajax(...something something);

//make the deferred always resolve as success, calling all success callbacks on original.
//AFAIK, dosent pass any arguments to the original success callbacks.
jqDeferred.pipe( null, function(args){ return $.Deferred().resolve(); });

//same as above, but try to pass all arguments through to the success callbacks.
jqDeferred.pipe( null, function(args){ return $.Deferred().resolve.apply(this, arguments); });

I wanted to do this recently and couldnt find any easy instructions, hope it helps.
Im not super sure about the argument passing, as I have only used the first form in anger - we didn't need any arguments passed to our success callbacks.
Pipe is wicked.

A: I think you should handle that ajax error with any code for your needs.

error(jqXHR, textStatus,
  errorThrown)

Function A function to be
    called if the request fails. The
    function receives three arguments: The
    jqXHR (in jQuery 1.4.x,
    XMLHttpRequest) object, a string
    describing the type of error that
    occurred and an optional exception
    object, if one occurred. Possible
    values for the second argument
    (besides null) are "timeout", "error",
    "abort", and "parsererror". When an
    HTTP error occurs, errorThrown
    receives the textual portion of the
    HTTP status, such as "Not Found" or
    "Internal Server Error." As of jQuery
    1.5, the error setting can accept an array of functions. Each function will
    be called in turn. Note: This handler
    is not called for cross-domain script
    and JSONP requests. This is an Ajax
    Event.

Example
 error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            if (err.Message == 'SomeMessage') {
               //Return Your data, handle this error...
            }
        }

A: You can use .ajaxSetup with your own custom beforeSend handler. In your handler you can check if the url is accesible, if it's not you can cancel the request and emulate a call to success with your own data.

A: Well, a quick update: non of the solutions above worked.
What I eventually had to do to walk around this problem, is replace jQuery's ajax function with my implementation, that checks if there is network connection.
if there is, I proxy the request back to the original ajax function, else, I create the same return structure as ajax's would and return it
Again, I hate answering my own questions, especially when it's not really an answer but more of a workaround.
sad...


text: Q: Диски внутри раздела? В порядке обучения надо создать на диске раздел. На диске уже два раздела с системой. Однако, во втором как-то странно определяются еще два "диска". Систему ставил автоустановщиком, до этого две системы ставил сам разделяя диск.


text:
Q: 0000-00-00 00:00:00 entered as MySQL DateTime Below is the CREATE TABLE statement used to create my table:
CREATE TABLE IF NOT EXISTS `data_received` (
 `id` int(10) unsigned NOT NULL,
 `edit_time` datetime NOT NULL}

Below is how data is saved in table if 'edit_time' value is not provided:
id  edit_time
1   0000-00-00 00:00:00

Now, if I execute the following statement:
SELECT TIMESTAMPDIFF( HOUR , edit_time, NOW( ) ) AS diff_in_hours
FROM data_received;

I get result: NULL
Can someone please help me understand what is happening?

A: That is because 0000-00-00 00:00:00 is not a valid DATETIME expression accepted by the function.
Please check documentation.

A: Use this method to keep edit-time in mysql
`edit_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Auto-update time'

A: Mysql tends to insert rubbish in an attempt to be "helpful". Best to tell it not to do that by settings mysql to STRICT mode so it behaves more like a database should.
SET sql_mode='STRICT_ALL_TABLES'

For details please read the manual.

A: 0000-00-00 00:00:00 will probably interpreted as null. And comparing null in a TIMESTAMPDIFF will lead to null result.
MySQL doc says

In MySQL, the zero date is defined as '0000-00-00', even though this date is itself considered invalid.

A: There is no zeroth of zero in year zero, so you cannot calculate the time since then:
SELECT TIMESTAMPDIFF(HOUR, '0000-00-00 00:00:00', NOW())

NULL

Apparently MySQL does not have a problem with year 0 itself, as this returns a result:
SELECT TIMESTAMPDIFF(HOUR, '0000-01-01 00:00:00', NOW())

17643758


text:
Q: Scrapy over-writes results when requests are run concurrently? I have been running a Scrapy scraper, and noticed that it is returning duplicate results. In other words, it is assigning results for an item from another item.
My settings file has CONCURRENT_REQUESTS = 100 and does not set DOWNLOAD_DELAY.
This is my spider code:
def start_requests(self):
    settings = get_project_settings()
    ids = settings.get('IDS', None)
    for i, id in enumerate(ids):
        yield FormRequest(
            url=self._FORM_URL,
            formdata={ 'id': id },
            meta={'id': id},
        )

def parse(self, response):
    addr_xpath = '//div[@class="w80p  left floatRight"]//text()'
    addresses = response.xpath(addr_xpath).extract()
    if not addresses:
        raise DropItem("Can't find address")

    item = MyItem()
    item['address'] = ', '.join(addresses)
    return item

This is my item code:
class MyItem(scrapy.Item):
    id = scrapy.Field()
    address = scrapy.Field()

Some of my items have different IDs but the same address, even though the web page I'm scraping returns different addresses for the different IDs. I think results are being returned in parallel and accidentally over-writing each other.
What am I doing wrong? I'm using Scrapy v0.24.6 and Twisted v16.6.0.

A: It's probably happening because cookie sessions. To use multiple cookie session in one spider you need to use cookiejar meta parameter in your request:
for i, url in enumerate(urls):
    yield scrapy.Request(url, meta={'cookiejar': i},
                         callback=self.parse_page)

As per Multiple cookie sessions per spider:

There is support for keeping multiple cookie sessions per spider by using the cookiejar Request meta key. By default it uses a single cookie jar (session), but you can pass an identifier to use different ones.


text:
Q: Tokyo Cabinet behaviour without explicit transactions Haven't found anything on subject in docs. I wonder how reliable and concurrent TC is when I don't start/commit transactions explicitly, i.e. in "implicit transaction" mode.
I need to write only one record per transaction, i.e. no batch writes. But I want that record be written reliably to disk before writer function returns. Still, I'd like to avoid WAL files if possible.
Interested in Hash DB, B+ Tree DB, Fixed-Length DB.
EDIT. To be explicit:

*

*Docs say that "database file is not corrupted even under catastrophic situation". But I'm not sure "no corruption" does mean that data is ACIDly written.

*Functions ...dbopen() for all DB types take flag HDBOTSYNC, "which means every transaction synchronizes updated contents with the device". Will this flag still work if I don't start transaction explicitly?
// BTW, are there worthy alternatives to TC? I mean embedded C/C++ libraries with same functionality and speed. KyotoCabinet is no way: it's GPL; https://fallabs.com/license/ is 404, and my email about that 404 was not answered; not to mention they removed Fixed-Length DB from KC.

A: Got an answer on a forum:

*

*To be sure data is written completely and consistently, one must use BOTH explicit transactions and HDBOTSYNC.

*Was advised to take a look at https://github.com/erthink/libmdbx (including https://github.com/erthink/libfpta).


text:
Q: Excluding Lower levels in Nlog in Nlog
i know there are
trace
debug
info
warn
error
fatal

levels, and that if i printed "warn" by example higher levels wont be printed , now problem is how do i disable lower levels too ?!
thanks in advance....

A: i got it
i used minlevel , maxlevel and level(only log specific level)...

A: Use Minlevel
example  <logger name="*" minlevel="Error" writeTo="file" />
This will disable all levels lower than "Error"


text:
Q: UISwipeGestureRecognizer - perform action with 2 finger and 3 finger swipe - iOS How to detect UISwipeGestureRecognizer 2 finger swipe or 3 finger swipe on the same View- iOS
any one have idea ?

A: I have created a gesture for 2 and 3 finger swipe.
       func addTwoFingerSwipeGesture() {
            let gesture = UISwipeGestureRecognizer(target: self, action: "handleTwoFingerSwipe")
            gesture.direction = .Left
            gesture.numberOfTouchesRequired = 2 // 2 finger swipe
            self.view.addGestureRecognizer(gesture)
        }

       func addThreeFingerSwipeGesture() {
            let gesture = UISwipeGestureRecognizer(target: self, action: "handleThreeFingerSwipe")
            gesture.direction = .Left
            gesture.numberOfTouchesRequired = 3 // 3 finger swipe
            self.view.addGestureRecognizer(gesture)
        }

    // Handle Swipe
        func handleTwoFingerSwipe() {
            print("2 finger swipe recognized")
        }

        func handleThreeFingerSwipe() {
            print("3 finger swipe recognized")
        }

A: Here   "setMinimumNumberOfTouches" depends on your fingers(Eg:2/3/4/5). Try it once ..it may help to u
  UIPanGestureRecognizer *pan;
 pan = [[UIPanGestureRecognizer alloc] initWithTarget:self     action:@selector(Swipe4ScrollViews:)];
[pan setMinimumNumberOfTouches:2];
 [_scroll1 addGestureRecognizer:pan];
  [pan release];


text:
Q: Segment tree with lazy propagation for multiple of 3 Abridged problem: You're given an array of n elements, initially they are all 0.
You will receive two types of query: 0 index1 index2, in this case you have to increase by one all elements in range index1 index2(included).
Second type: 1 index1 index2, in this case you have to print a number rapresenting how many elements between index1 and index2(included) are divisible by 3.
Of course, as n is very large(10^6) the good approach is to use segment tree to store intervals, and also to use lazy propagation to update the tree in log n.
But I actually really don't know how to apply lazy propagation here, because you have to keep into account three possible states for every number( may be 3k,3k+1,3k+2), and not just two as the flipping coins problem.
If I put a flag on some interval that is included in the interval of my query, I have to update it looking at the original array and at its value, but when I have to update the son of this interval I have to do the same again and this is a wasteful of time....
Any better idea? I search on the net but found nothing ...
EDIT: I follow your suggestions and I code this( C++), and works for some base cases, but when I submit it I get just 10/100 points, what is wrong with it ? (I know it's a bit long and there are no much comments but it's a simple Segment Tree with lazy propagation, if you don't understand something, please tell me!
NOTE: st[p].zero contains elements that are 0 mod 3 in interval stored in index p, st[p].one elements 1 mod 3, and st[p].two elements 2 mod 3; When I update I shift of one position these elements(0->1, 1->2, 2->0) and I use lazy. On updating, I return a pair < int , pair< int, int > >, just a simple way to store a triple of numbers, In this way a can return the difference of numbers 0,1,2 mod 3.
int sol;

struct mod{
    mod(){ zero=0; one=0;two=0;}
    int zero;
    int one;
    int two;
};

class SegmentTree {
public: int lazy[MAX_N];
  mod st[MAX_N];
  int n;
  int left (int p) { return p << 1; }
  int right(int p) { return (p << 1) + 1; }

  void build(int p, int L, int R){
        if(L == R)
            st[p].zero=1;
        else{
            st[p].zero = R - L + 1;
            build(left(p), L, (L + R) / 2);
            build(right(p), ((L + R) / 2) + 1, R);
        }
        return;
  }

  void query(int p, int L, int R, int i, int j) {
    if (L > R || i > R || j < L) return;

    if(lazy[p]!=0){     // Check if this no has to be updated
        for(int k=0;k<lazy[p];k++){
            swap(st[p].zero,st[p].two);
            swap(st[p].one, st[p].two);
        }
        if(L != R){
            lazy[left(p)] = (lazy[left(p)] + lazy[p]) % 3;
            lazy[right(p)] = (lazy[right(p)] + lazy[p]) % 3;
        }
        lazy[p] = 0;
    }

    if (L >= i && R <= j) { sol += st[p].zero;   return; }

    query(left(p) , L              , (L+R) / 2, i, j);
    query(right(p), (L+R) / 2 + 1, R          , i, j);

    return;
  }

  pair < int, ii > update_tree(int p, int L, int R, int i, int j) {

    if (L > R || i > R || j < L){
      pair< int, pair< int, int > >  PP; PP.first=PP.second.first=PP.second.second=INF;
      return PP;
    }

    if(lazy[p]!=0){     // Check if this no has to be updated
        for(int k=0;k<lazy[p];k++){
            swap(st[p].zero,st[p].two);
            swap(st[p].one, st[p].two);
        }
        if(L != R){
            lazy[left(p)] = (lazy[left(p)] + lazy[p]) % 3;
            lazy[right(p)] = (lazy[right(p)] + lazy[p]) % 3;
        }
        lazy[p] = 0;
    }

    if(L>=i && R<=j){
        swap(st[p].zero, st[p].two);
        swap(st[p].one, st[p].two);
        if(L != R){
            lazy[left(p)] = (lazy[left(p)] + 1) % 3;
            lazy[right(p)] = (lazy[right(p)] + 1) % 3;
        }
        pair< int, pair< int, int > > t; t.first = st[p].zero-st[p].one; t.second.first = st[p].one-st[p].two; t.second.second = st[p].two-st[p].zero;
        return t;
    }

    pair< int, pair< int, int > > s = update_tree(left(p), L, (L+R)/2, i, j); // Updating left child
    pair< int, pair< int, int > > s2 = update_tree(right(p), 1+(L+R)/2, R, i, j); // Updating right child
    pair< int, pair< int, int > > d2;
    d2.first = ( (s.first!=INF ? s.first : 0) + (s2.first!=INF ? s2.first : 0) ); // Calculating difference from the ones given by the children
    d2.second.first = ( (s.second.first!=INF ? s.second.first : 0) + (s2.second.first!=INF ? s2.second.first : 0) );
    d2.second.second = ( (s.second.second!=INF ? s.second.second : 0) + (s2.second.second!=INF ? s2.second.second : 0) );
    st[p].zero += d2.first; st[p].one += d2.second.first; st[p].two += d2.second.second; // Updating root
    return d2;  // Return difference
  }

  public:
  SegmentTree(const vi &_A) {
    n = (int)_A.size();
    build(1, 0, n - 1);
  }

  void query(int i, int j) { return query(1, 0, n - 1, i, j); }

  pair< int, pair< int, int > > update_tree(int i, int j) {
    return update_tree(1, 0, n - 1, i, j); }
};

int N,Q;

int main() {
    FILE * in; FILE * out;
    in = fopen("input.txt","r"); out = fopen("output.txt","w");

    fscanf(in, "%d %d" , &N, &Q);
    //cin>>N>>Q;
    int arr[N];
    vi A(arr,arr+N);

    SegmentTree *st = new SegmentTree(A);

    for(int i=0;i<Q;i++){
        int t,q,q2;
        fscanf(in, "%d %d %d " , &t, &q, &q2);
        //cin>>t>>q>>q2;
        if(q > q2) swap(q, q2);
        if(t){
            sol=0;
            st->query(q,q2);
            fprintf(out, "%d\n", sol);
            //cout<<sol<<endl;
        }
        else{
            pair<int, pair< int, int > > t = st->update_tree(q,q2);
        }
    }

    fclose(in); fclose(out);
    return 0;
}

A: You can store two values in each node:
1)int count[3] - how many there are 0, 1 and 2 in this node's segment.
2)int shift - shift value(initially zero).
The operations are performed in the following way(I use pseudo code):
add_one(node v)
    v.shift += 1
    v.shift %= 3

propagate(node v)
    v.left_child.shift += v.shift
    v.left_child.shift %= 3
    v.right_child.shift += v.shift
    v.right_child.shift %= 3
    v.shift = 0
    for i = 0..2:
        v.count[i] = get_count(v.left, i) + get_count(v.right, i)

get_count(node v, int remainder)
    return v.count[(remainder + v.shift) % 3]

The number of elements divisible by 3 for a node v is get_count(v, 0).
Update for a node is add_one operation. In general, it can be used as an ordinary segment tree(to answer range queries).
The entire tree update looks like that:
update(node v, int left, int right)
    if v is fully covered by [left; right]
        add_one(v)
    else:
        propagate(v)
        if [left; right] intersects with the left child:
            update(v.left, left, right)
        if[left; right] intersects with the right child:
            update(v.right, left, right)
        for i = 0..2:
            v.count[i] = get_count(v.left, i) + get_count(v.right, i)

Getting the number of elements divisible by 3 is done in similar manner.

A: It seems that you never have to care about the values of the elements, only their values modulo 3.
Keep a segment tree, using lazy updates as you suggest.  Each node knows the number of things that are 0, 1, and 2 modulo 3 (memoization).
Each update hits log(n) nodes.  When an update hits a node, you remember that you have to update the descendants (lazy update) and you cycle the memoized number of things in the subtree that are 0, 1, and 2 modulo 3.
Each query hits log(n) nodes; they're the same nodes an update of the same interval would hit.  Whenever a query comes across a lazy update that hasn't been done, it pushes the update down to the descendants before recursing.  Apart from that, all it does is it adds up the number of elements that are 0 modulo 3 in each maximal subtree completely contained in the query interval.


text:
Q: Need the bootstrap class "embed-responsive-item" to work with the fabric canvas element So I am using bootstrap's embed-responsive structure that involves a wrapper with embed-responsive class & an additional class for defining aspect ratio & the child element with embed-responsive-item class. The problem is that it works for canvas, but when I initialize it as a fabric.Canvas it breaks.
<div class="embed-responsive embed-responsive-16by9">
  <canvas id="popupEditorCanvas" class="embed-responsive-item"></canvas>
</div>

A: Since canvas is kind of a static DOM object that doesn't really go easy with css changes. It is better to have it at a fixed res, if you really need to maintain the aspect ratio. You can always make it dirty by reloading the page everytime someone trigger window.resize. It's upto You! For me, fixing resolution for the canvas was the option.


text:
Q: Proper database schema select sum(c.cost)
from (select x.num as x, y.num as y, max(priority) as maxpriority
      from numbers x cross join
           numbers y join
           costs c
           on x.num between c.x and c.x + c.deltax and y.num between c.y and c.y + c.deltay
      where x.value between PIXELX and PIXELX and DELTAX and
            y.value between PIXELY and PIXELY and DELTAY
      group by x.num, y.num
    ) xyp join
    costs c
    on xyp.x between c.x and c.x + c.deltax and xyp.y between c.y + c.deltay and
        xyp.maxpriority = c.priority

I have been given this as an answer when looking for a "cost" between two points in a database populated by areas with every area having a different cost. I have been trying to get this to work along with figuring out the database schema, currently I'm getting #1054 - Unknown column 'x.value' in 'where clause' with
Name    Type    Collation   Attributes  Null    Default Extra   Action
     1  num int(11)         No  None          Change      Drop    Browse distinct values     More

As numbers and
#   Name    Type    Collation   Attributes  Null    Default Extra   Action
 1  x   int(11)         No  None          Change      Drop    Browse distinct values     More
 2  y   int(11)         No  None          Change      Drop    Browse distinct values     More
 3  deltax  int(11)         No  None          Change      Drop    Browse distinct values     More
 4  deltay  int(11)         No  None          Change      Drop    Browse distinct values     More
 5  priority    int(11)         No  None          Change      Drop    Browse distinct values     More

As costs. Have been trying to figure this out for a while so big thanks to anyone for pointers.
Okay it doesn't throw an error now but it returns null instead of the cost within a selected area.

A: Your numbers table does not have a column called value and you are trying to reference a column that does not exist so you get an error. Your current code:
where x.value between PIXELX and PIXELX and DELTAX and

I am guessing that you want to use num instead:
where x.num between PIXELX and PIXELX and DELTAX and
      y.num between PIXELY and PIXELY and DELTAY


text:
Q: How do I sign click once applications? I have written an application, that I'm publishing to my webpage everytime I make changes via the "Publishing Assistant" in VS13. If I'm going to install it on my PC from my website Windows tells me that the application would not be trustful. How do I change this? Where do I get an certificate for signing it?

A: You buy a certificate from any trusted certificate provider. To not to promote any specific provider, I'll just recommend you to google for "buy code signing certificate", if you really can't find a provider on your own.
Then, at the properties tabs, navigate to the "Signing" tab and point to your certificate file. The package will be signed upon building.


text:
Q: Union of two full graphs gives "Cannot add unknown type to igraph graph" I am trying to join two fully connected graphs in igraph to one graph via union.
There are no edges between the two graphs (because I want to rewire them later)
However this code doesn't seem to work
g1 <-make_full_graph(10, directed = FALSE, loops = FALSE)
V(g1)$name <- c(1:10)

g2 <-make_full_graph(10, directed = FALSE, loops = FALSE)
V(g2)$name <- c(11:20)

u1 <- union(g1,g2)

I get the ERROR:

"Error in +.igraph(g, setdiff(uninames, V(g)$name)) :
    Cannot add unknown type to igraph graph"

Cane somebody clarify?


text:
Q: Disable suexec for specific part of an Apache vhost In an Apache 2.4 vHost, I want to use CGI with the default user (www-data), as the script is located outside of suexec's document root. Additionally, I want to execute a script with suexec (via ScriptAlias). Both tasks work fine (the CGI one with the SuexecUserGroup Line disabled, the ScriptAlias one with it enabled) on their own, but are mutually exclusive right now. I wondered whether it is possible to disable suexec for the CGI part of my vHost conf.
How would one do that?
Context: I want to access Gitolite3 via Gitweb (→ CGI) and Smart HTTP (→ suexec).

A: Now, after even more research, I assume that the thing I want to achieve in my question is not possible.
In my specific scenario, I added the www-data user to the gitolite3 group and gave the gitolite-shell the group execute permission. Then, I could remove the Suexec statement in my vHost and everything works.


text:
Q: performing a thread using jcomponets am back again!. i have a probrem here. am making uneditable jcombobox. i have a list of items in it("crus","davy","shawn") and i want if someone clicks on crus, a thread of images with a Thread.sleep of 2 seconds will appear at a jlabel called picturelabel. when i try to put method run() inside method actionperformed, i get "illegal start of expression". i also get an error "not a statement" when i try to create an array of imageicon.
public class Myjcombobox extends JFrame implements ActionListener,Runnable {
JComboBox job;
String[] items={"crus","shawn","davy","others"};
JLabel picturelabel;
public Myjcombobox(){
super("oh mymy");
setSize(1000,1000);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout border=new BorderLayout();
setLayout(border);
job=new JComboBox(items);
job.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
JComboBox combo=(JComboBox)event.getSource();
String name=(String)combo.getSelectedItem();
if(name=="crus"){
 public void run(){//i get an error illegal start of expression//
 JImageIcon[] crusimages= new JImageIcon{"crus reading.jpg","crus playing.jpg","crus in class.jpg"}; //i get an error "not a statement","( or[ expected"//
 }
}
}

public static void main(String[] args) {
    Myjcombobox jcomb=new Myjcombobox();

}

A: You can't just run() the thread, if you want to start it for the first time, you must use the method start(), witch starts a thread and runs the run() method. If you use just the run(), you won't be creating a thread, for it will run on the current thread.
Java Concurrency tutorial from Oracle: http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html.
Java Swing Components from Oracle: http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html.
I hop I could help.
Saclyr.

A: if(name=="crus"){

{//i get an error illegal start of expression//
 public void run()

//i get an error "not a statement","( or[ expected"//
 JImageIcon[] crusimages= new JImageIcon{"crus reading.jpg","crus playing.jpg","crus in class.jpg"};
 }

Every statement in the above code has a problem:
 if(name=="crus"){

Don't use "==" to compare strings. Instead you should be using the equals(...) method:
if ("crus".equals(name));

Next, you can't just define a run() method in the middle of your code.
public void run()

The run() method belongs to a Thread, so you need to create a Thread and override the run() method. Something like:
Thread thread = new Thread()
{
    @override
    public void run()
    {
        System.out.println("I'm a Thread");
    }
};
thread.start();

Finallay you can't create an Array of Image Icons in one step like this:
JImageIcon[] crusimages= new JImageIcon{"crus reading.jpg","crus playing.jpg","crus in class.jpg"};

You need to create an empty Array and then add the Icons one at a time:
ImageIcon[] crusImages = new new ImageIcon[3];
crusImage[0] = new ImageIcon( "crus reading.jpg" );


text:
Q: why is protobuf-net deserialized object not 'lean' We are using the protobuf-net library in order to decode MQTT messages provided from the Inductive Automation - Ignition software, which is based on sparkplug_b.proto payload.
We have generated c# code with the great online protogen tool.
So now we are able to decode the binarires message objects, to human readable JSON for example :-)
But the deserialized Object contains ('useless'?) objects, which overload the object instance.
Why is the object not "filtered" to provide a 'lean' object instance?
For example:
{
  "Body": null,
  "Metrics": [
    {
      "Alias": 0,
      "BooleanValue": false,
      "BytesValue": null,
      "DatasetValue": null,
      "Datatype": 4,
      "DoubleValue": 0,
      "ExtensionValue": null,
      "FloatValue": 0,
      "IntValue": 0,
      "IsHistorical": false,
      "IsNull": false,
      "IsTransient": false,
      "LongValue": 0,
      "Metadata": null,
      "Name": "bdSeq",
      "Properties": null,
      "StringValue": "",
      "TemplateValue": null,
      "Timestamp": 1538568112852
    }
  ],
  "Seq": 18446744073709551615,
  "Timestamp": 1538568112852,
  "Uuid": ""
}

A: That's because the Metric definition has a oneof field:
message Metric {

    // ...

    oneof value {
        uint32   int_value                      = 10;
        uint64   long_value                     = 11;
        float    float_value                    = 12;
        double   double_value                   = 13;
        bool     boolean_value                  = 14;
        string   string_value                   = 15;
        bytes    bytes_value                    = 16;       // Bytes, File
        DataSet  dataset_value                  = 17;
        Template template_value                 = 18;
        MetricValueExtension extension_value    = 19;
    }

    message MetricValueExtension {
        extensions  1 to max;
    }
}

And for each of those members, a property is generated in the C# class. But also, for each property, an accompanying ShouldSerialize property should be generated by protogen:
public bool ShouldSerializeIntValue() => __pbn__itemValue.Is(10);

And JSON.NET (Newtonsoft.Json) should respect this property, so it should only serialize the member that the oneof field referred to, because all other ShouldSerialize properties will return false.


text:
Q: How do i summon custom villagers that sell custom prefilled chests I was making a trading system on my minecraft server (e.x. 64 iron blocks = good armor) and i couldnt figure out how to make the villagers sell custom prefilled chests
if you want to do it for me i would love it!
Prefilled chest give command:
/give @p chest{display:{Name:"\"Iron Rank\""},BlockEntityTag:{Items:[{Slot:0,id:iron_helmet,Count:1,tag:{Enchantments:[{id:protection,lvl:4},{id:respiration,lvl:3},{id:aqua_affinity,lvl:1},{id:thorns,lvl:3},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:1,id:iron_chestplate,Count:1,tag:{Enchantments:[{id:protection,lvl:4},{id:thorns,lvl:3},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:2,id:iron_leggings,Count:1,tag:{Enchantments:[{id:protection,lvl:4},{id:thorns,lvl:3},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:3,id:iron_boots,Count:1,tag:{Enchantments:[{id:protection,lvl:4},{id:feather_falling,lvl:3},{id:thorns,lvl:3},{id:depth_strider,lvl:3},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:4,id:iron_sword,Count:1,tag:{Enchantments:[{id:sharpness,lvl:5},{id:knockback,lvl:2},{id:fire_aspect,lvl:2},{id:looting,lvl:3},{id:sweeping,lvl:3},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:5,id:iron_pickaxe,Count:1,tag:{Enchantments:[{id:efficiency,lvl:5},{id:unbreaking,lvl:3},{id:fortune,lvl:3},{id:mending,lvl:1}]}},{Slot:6,id:iron_pickaxe,Count:1,tag:{Enchantments:[{id:efficiency,lvl:5},{id:silk_touch,lvl:1},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:7,id:iron_axe,Count:1,tag:{Enchantments:[{id:sharpness,lvl:5},{id:efficiency,lvl:5},{id:unbreaking,lvl:3},{id:fortune,lvl:3},{id:mending,lvl:1}]}},{Slot:8,id:iron_shovel,Count:1,tag:{Enchantments:[{id:efficiency,lvl:5},{id:unbreaking,lvl:3},{id:fortune,lvl:3},{id:mending,lvl:1}]}},{Slot:9,id:iron_shovel,Count:1,tag:{Enchantments:[{id:efficiency,lvl:5},{id:silk_touch,lvl:1},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:10,id:iron_hoe,Count:1,tag:{Enchantments:[{id:unbreaking,lvl:3},{id:mending,lvl:1}]}}]}} 1
sorry if its long but this is the command so if you could please put this into a villager trade i would love it!

A: You have to put the command in a command block because it's too long:
summon villager ~ ~1 ~ {VillagerData:{level:5,profession:farmer,type:plains},Offers:{Recipes:[{maxUses:10,buy:{id:emerald,Count:10b},sell:{id:chest,Count:1b,tag:{display:{Name:'"Iron Rank"'},BlockEntityTag:{Items:[{Slot:0,id:iron_helmet,Count:1b,tag:{Enchantments:[{id:protection,lvl:4},{id:respiration,lvl:3},{id:aqua_affinity,lvl:1},{id:thorns,lvl:3},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:1,id:iron_chestplate,Count:1b,tag:{Enchantments:[{id:protection,lvl:4},{id:thorns,lvl:3},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:2,id:iron_leggings,Count:1b,tag:{Enchantments:[{id:protection,lvl:4},{id:thorns,lvl:3},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:3,id:iron_boots,Count:1b,tag:{Enchantments:[{id:protection,lvl:4},{id:feather_falling,lvl:3},{id:thorns,lvl:3},{id:depth_strider,lvl:3},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:4,id:iron_sword,Count:1b,tag:{Enchantments:[{id:sharpness,lvl:5},{id:knockback,lvl:2},{id:fire_aspect,lvl:2},{id:looting,lvl:3},{id:sweeping,lvl:3},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:5,id:iron_pickaxe,Count:1b,tag:{Enchantments:[{id:efficiency,lvl:5},{id:unbreaking,lvl:3},{id:fortune,lvl:3},{id:mending,lvl:1}]}},{Slot:6,id:iron_pickaxe,Count:1b,tag:{Enchantments:[{id:efficiency,lvl:5},{id:silk_touch,lvl:1},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:7,id:iron_axe,Count:1b,tag:{Enchantments:[{id:sharpness,lvl:5},{id:efficiency,lvl:5},{id:unbreaking,lvl:3},{id:fortune,lvl:3},{id:mending,lvl:1}]}},{Slot:8,id:iron_shovel,Count:1b,tag:{Enchantments:[{id:efficiency,lvl:5},{id:unbreaking,lvl:3},{id:fortune,lvl:3},{id:mending,lvl:1}]}},{Slot:9,id:iron_shovel,Count:1b,tag:{Enchantments:[{id:efficiency,lvl:5},{id:silk_touch,lvl:1},{id:unbreaking,lvl:3},{id:mending,lvl:1}]}},{Slot:10,id:iron_hoe,Count:1b,tag:{Enchantments:[{id:unbreaking,lvl:3},{id:mending,lvl:1}]}}]}}}}]}}

I set the price to 10 emeralds and the max uses to 10, which you can change. This command will summon a plains farmer level 5 villager but you can change the VillagerData to whatever you want (see the wiki for more information).
Formatted NBT:
{
  VillagerData: {
    level: 5,
    profession: farmer,
    type: plains
  },
  Offers: {
    Recipes: [{
      maxUses: 10,
      buy: {id: emerald, Count: 10b},
      sell: {
        id: chest,
        Count: 1b,
        tag: {
          display: {Name: '"Iron Rank"'},
          BlockEntityTag: {
            Items: [
              {
                Slot: 0,
                id: iron_helmet,
                Count: 1b,
                tag: {
                  Enchantments: [
                    {id: protection, lvl: 4},
                    {id: respiration, lvl: 3},
                    {id: aqua_affinity,lvl: 1},
                    {id: thorns,lvl: 3},
                    {id: unbreaking,lvl: 3},
                    {id: mending,lvl: 1}
                  ]
                }
              },
              {
                Slot: 1,
                id: iron_chestplate,
                Count: 1b,
                tag: {
                  Enchantments: [
                    {id: protection, lvl: 4},
                    {id: thorns, lvl: 3},
                    {id: unbreaking, lvl: 3},
                    {id: mending, lvl: 1}
                  ]
                }
              },
              {
                Slot: 2,
                id: iron_leggings,
                Count: 1b,
                tag: {
                  Enchantments: [
                    {id: protection, lvl: 4},
                    {id: thorns, lvl: 3},
                    {id: unbreaking, lvl: 3},
                    {id: mending, lvl: 1}
                  ]
                }
              },
              {
                Slot: 3,
                id: iron_boots,
                Count: 1b,
                tag: {
                  Enchantments: [
                    {id: protection, lvl: 4},
                    {id: feather_falling, lvl: 3},
                    {id: thorns, lvl: 3},
                    {id: depth_strider, lvl: 3},
                    {id: unbreaking, lvl: 3},
                    {id: mending, lvl: 1}
                  ]
                }
              },
              {
                Slot: 4,
                id: iron_sword,
                Count: 1b,
                tag: {
                  Enchantments: [
                    {id: sharpness, lvl: 5},
                    {id: knockback, lvl: 2},
                    {id: fire_aspect, lvl: 2},
                    {id: looting, lvl: 3},
                    {id: sweeping, lvl: 3},
                    {id: unbreaking, lvl: 3},
                    {id: mending, lvl: 1}
                  ]
                }
              },
              {
                Slot: 5,
                id: iron_pickaxe,
                Count: 1b,
                tag: {
                  Enchantments: [
                    {id: efficiency, lvl: 5},
                    {id: unbreaking, lvl: 3},
                    {id: fortune, lvl: 3},
                    {id: mending, lvl: 1}
                  ]
                }
              },
              {
                Slot: 6,
                id: iron_pickaxe,
                Count: 1b,
                tag: {
                  Enchantments: [
                    {id: efficiency, lvl: 5},
                    {id: silk_touch, lvl: 1},
                    {id: unbreaking, lvl: 3},
                    {id: mending, lvl: 1}
                  ]
                }
              },
              {
                Slot: 7,
                id: iron_axe,
                Count: 1b,
                tag: {
                  Enchantments: [
                    {id: sharpness, lvl: 5},
                    {id: efficiency, lvl: 5},
                    {id: unbreaking, lvl: 3},
                    {id: fortune, lvl: 3},
                    {id: mending, lvl: 1}
                  ]
                }
              },
              {
                Slot: 8,
                id: iron_shovel,
                Count: 1b,
                tag: {
                  Enchantments: [
                    {id: efficiency, lvl: 5},
                    {id: unbreaking, lvl: 3},
                    {id: fortune, lvl: 3},
                    {id: mending, lvl: 1}
                  ]
                }
              },
              {
                Slot: 9,
                id: iron_shovel,
                Count: 1b,
                tag: {
                  Enchantments: [
                    {id: efficiency, lvl: 5},
                    {id: silk_touch, lvl: 1},
                    {id: unbreaking, lvl: 3},
                    {id: mending, lvl: 1}
                  ]
                }
              },
              {
                Slot: 10,
                id: iron_hoe,
                Count: 1b,
                tag: {
                  Enchantments: [
                    {id: unbreaking, lvl: 3},
                    {id: mending, lvl: 1}
                  ]
                }
              }
            ]
          }
        }
      }
    }]
  }
}


text:
Q: Deny all IPs but one I'm trying to block all IP'sbut my own but it doesn't work for me.
I use the following code as answered in Deny all, allow only one IP through htaccess
order deny,allow
deny from all
allow from MyIP

But it lets other IP's access too.
My IP is static and my site is hosted by a thirth party hosting service

A: I am not sure if your ip is static or not, Please try it like this,
<Files ~ ".*">
    order deny,allow
    deny from all
    allow from 127.0.0.1
</Files>

127.0.0.0 denotes your localhost.
Edit
Remove access rule and try it with mod_rewrite,
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REMOTE_ADDR} !^111\.111\.111\.111$ #your IP
    RewriteRule .* - [F]
</IfModule>

A: If you did the following code:
order deny,allow
deny from all
allow from MyIP
and it also allowed other peoples ips then it has something to do with your host. Cause I ran the code on my site and it worked fine.


text:
Q: Convert Datetime, Sunrise and Sunset from miliseconds to real time format My weather App displays Datetime(last updated), Sunrise, and Sunset data from OpenWeatherMap in the form of milliseconds(i.e 1620792785).
I'm trying to convert it to a real-time format (i.e hh:mm a).
I tried using this code for dt in my example class:
public String getPrettyDate() {
        SimpleDateFormat HMM = new SimpleDateFormat("hh:mm a", Locale.US);
        final Date date = new Date(dt*1000);
        return HMM.format(date);
    }

It converted the time well, but it didn't display the data accurately(i.e when it was 3pm here, it showed 9pm).
I as well checked this site for a similar issue but found none.
So I want to:

*

*Convert the dt accurately

*Convert Sunrise and Sunset time accurately
using the right codes and classes.

Edit:
My app can search for any city, so I'm not getting for a particular timezone but for all cities
My JSON Response:
{
   "coord":{
      "lon":-0.1257,
      "lat":51.5085
   },
   "weather":[
      {
         "id":804,
         "main":"Clouds",
         "description":"overcast clouds",
         "icon":"04d"
      }
   ],
   "base":"stations",
   "main":{
      "temp":289.16,
      "feels_like":288.07,
      "temp_min":286.87,
      "temp_max":290.76,
      "pressure":1009,
      "humidity":48
   },
   "visibility":10000,
   "wind":{
      "speed":0.45,
      "deg":109,
      "gust":2.68
   },
   "clouds":{
      "all":100
   },
   "dt":1620830862,
   "sys":{
      "type":2,
      "id":2019646,
      "country":"GB",
      "sunrise":1620792785,
      "sunset":1620848444
   },
   "timezone":3600,
   "id":2643743,
   "name":"London",
   "cod":200
}

My Example class:
public class Example {
    @SerializedName("coord")
    private Coord coord;
    @SerializedName("weather")
    private List<Weather> weather = null;
    @SerializedName("base")
    private String base;
    @SerializedName("main")
    private Main main;
    @SerializedName("visibility")
    private Integer visibility;
    @SerializedName("wind")
    private Wind wind;
    @SerializedName("clouds")
    private Clouds clouds;
    @SerializedName("dt")
    private Integer dt;
    @SerializedName("sys")
    private Sys sys;
    @SerializedName("timezone")
    private Integer timezone;
    @SerializedName("id")
    private Integer id;
    @SerializedName("name")
    private String name;
    @SerializedName("cod")
    private Integer cod;

    public Coord getCoord() {
        return coord;
    }

    public void setCoord(Coord coord) {
        this.coord = coord;
    }

    public List<Weather> getWeather() {
        return weather;
    }

    public void setWeather(List<Weather> weather) {
        this.weather = weather;
    }

    public String getBase() {
        return base;
    }

    public void setBase(String base) {
        this.base = base;
    }

    public Main getMain() {
        return main;
    }

    public void setMain(Main main) {
        this.main = main;
    }

    public Integer getVisibility() {
        return visibility;
    }

    public void setVisibility(Integer visibility) {
        this.visibility = visibility;
    }

    public Wind getWind() {
        return wind;
    }

    public void setWind(Wind wind) {
        this.wind = wind;
    }

    public Clouds getClouds() {
        return clouds;
    }

    public void setClouds(Clouds clouds) {
        this.clouds = clouds;
    }

    public Integer getDt() {
        return dt;
    }

    public void setDt(Integer dt) {
        this.dt = dt;
    }

    public Sys getSys() {
        return sys;
    }

    public void setSys(Sys sys) {
        this.sys = sys;
    }

    public Integer getTimezone() {
        return timezone;
    }

    public void setTimezone(Integer timezone) {
        this.timezone = timezone;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getCod() {
        return cod;
    }

    public void setCod(Integer cod) {
        this.cod = cod;
    }

    public class Clouds {

        @SerializedName("all")
        private Integer all;

        public Integer getAll() {
            return all;
        }

        public void setAll(Integer all) {
            this.all = all;
        }

    }

    public class Coord {

        @SerializedName("lon")
        private Double lon;
        @SerializedName("lat")
        private Double lat;

        public Double getLon() {
            return lon;
        }

        public void setLon(Double lon) {
            this.lon = lon;
        }

        public Double getLat() {
            return lat;
        }

        public void setLat(Double lat) {
            this.lat = lat;
        }

    }

    public class Main {

        @SerializedName("temp")
        private Double temp;
        @SerializedName("feels_like")
        private Double feelsLike;
        @SerializedName("temp_min")
        private Double tempMin;
        @SerializedName("temp_max")
        private Double tempMax;
        @SerializedName("pressure")
        private Integer pressure;
        @SerializedName("humidity")
        private Integer humidity;

        public Double getTemp() {
            return temp;
        }

        public void setTemp(Double temp) {
            this.temp = temp;
        }

        public Double getFeelsLike() {
            return feelsLike;
        }

        public void setFeelsLike(Double feelsLike) {
            this.feelsLike = feelsLike;
        }

        public Double getTempMin() {
            return tempMin;
        }

        public void setTempMin(Double tempMin) {
            this.tempMin = tempMin;
        }

        public Double getTempMax() {
            return tempMax;
        }

        public void setTempMax(Double tempMax) {
            this.tempMax = tempMax;
        }

        public Integer getPressure() {
            return pressure;
        }

        public void setPressure(Integer pressure) {
            this.pressure = pressure;
        }

        public Integer getHumidity() {
            return humidity;
        }

        public void setHumidity(Integer humidity) {
            this.humidity = humidity;
        }

    }

    public class Sys {

        @SerializedName("type")
        private Integer type;
        @SerializedName("id")
        private Integer id;
        @SerializedName("country")
        private String country;
        @SerializedName("sunrise")
        private Integer sunrise;
        @SerializedName("sunset")
        private Integer sunset;

        public Integer getType() {
            return type;
        }

        public void setType(Integer type) {
            this.type = type;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getCountry() {
            return country;
        }

        public void setCountry(String country) {
            this.country = country;
        }

        public Integer getSunrise() {
            return sunrise;

        }

        public void setSunrise(Integer sunrise) {
            this.sunrise = sunrise;
        }

        public Integer getSunset() {
            return sunset;

        }

        public void setSunset(Integer sunset) {
            this.sunset = sunset;
        }

    }

    public class Weather {

        @SerializedName("id")
        private Integer id;
        @SerializedName("main")
        private String main;
        @SerializedName("description")
        private String description;
        @SerializedName("icon")
        private String icon;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getMain() {
            return main;
        }

        public void setMain(String main) {
            this.main = main;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getIcon() {
            return icon;
        }

        public void setIcon(String icon) {
            this.icon = icon;
        }

    }

    public class Wind {

        @SerializedName("speed")
        private Double speed;
        @SerializedName("deg")
        private Integer deg;
        @SerializedName("gust")
        private Double gust;

        public Double getSpeed() {
            return speed;
        }

        public void setSpeed(Double speed) {
            this.speed = speed;
        }

        public Integer getDeg() {
            return deg;
        }

        public void setDeg(Integer deg) {
            this.deg = deg;
        }

        public Double getGust() {
            return gust;
        }

        public void setGust(Double gust) {
            this.gust = gust;
        }
    }

    public String getPrettyDate() {
        SimpleDateFormat HMM = new SimpleDateFormat("hh:mm a", Locale.US);
        final Date date = new Date(dt*1000);
        return HMM.format(date);
    }
}

My Activity class(Where i called dt):
public class HomeActivity extends AppCompatActivity {
    // User current time
    TextView time_field;
    ImageView Search;
    EditText textfield;
    ConstraintLayout constraintLayout;
    // For scheduling background image change
    public static int count=0;
    int[] drawable =new int[]{R.drawable.dubai,R.drawable.central_bank_of_nigeria,R.drawable.eiffel_tower,R.drawable.hong_kong,R.drawable.statue_of_liberty};
    Timer _t;

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

        time_field = findViewById(R.id.textView9);
        Search = findViewById(R.id.imageView4);
        textfield = findViewById(R.id.textfield);

        BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
        final NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
        assert navHostFragment != null;
        final NavController navController = navHostFragment.getNavController();
        NavigationUI.setupWithNavController(bottomNavigationView, navController);

        Search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getWeatherData(textfield.getText().toString().trim());
                FirstFragment firstFragment = (FirstFragment) navHostFragment.getChildFragmentManager().getFragments().get(0);
                firstFragment.getWeatherData(textfield.getText().toString().trim());

                            constraintLayout = findViewById(R.id.layout);
                            constraintLayout.setBackgroundResource(R.drawable.dubai);
                            _t = new Timer();
                            _t.scheduleAtFixedRate(new TimerTask() {
                                @Override
                                public void run() {
                                    // run on ui thread
                                    runOnUiThread(() -> {
                                        if (count < drawable.length) {

                                            constraintLayout.setBackgroundResource(drawable[count]);
                                            count = (count + 1) % drawable.length;
                                        }
                                    });
                                }
                            }, 5000, 5000);
                        }

            private void getWeatherData(String name) {

                ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);

                Call<Example> call = apiInterface.getWeatherData(name);

                call.enqueue(new Callback<Example>() {
                    @Override
                    public void onResponse(@NotNull Call<Example> call, @NotNull Response<Example> response) {

                        assert response.body() != null;
                        time_field.setText("Last Updated:" + " " + response.body().getPrettyDate());

                    }

                    @Override
                    public void onFailure(@NotNull Call<Example> call, @NotNull Throwable t) {
                        t.printStackTrace();
                    }

                });
            }

        });
    }
}

My FirstFragment class(Where i called sunrise and sunset):
public class FirstFragment extends Fragment {
    // User current time, current temperature, current condition, sunrise, sunset, temperature, pressure, humidity, wind_speed, visibility, clouds
    TextView current_temp, current_output, rise_time, set_time, temp_out, Press_out, Humid_out, Ws_out, Visi_out, Cloud_out;
    // TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public FirstFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SecondFragment.
     */
// TODO: Rename and change types and number of parameters
    public static FirstFragment newInstance(String param1, String param2) {
        FirstFragment fragment = new FirstFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_first, container, false);
        // For displaying weather data
        current_temp = rootView.findViewById(R.id.textView10);
        current_output = rootView.findViewById(R.id.textView11);
        rise_time = rootView.findViewById(R.id.textView25);
        set_time = rootView.findViewById(R.id.textView26);
        temp_out = rootView.findViewById(R.id.textView28);
        Press_out = rootView.findViewById(R.id.textView29);
        Humid_out = rootView.findViewById(R.id.textView30);
        Ws_out = rootView.findViewById(R.id.textView33);
        Visi_out = rootView.findViewById(R.id.textView34);
        Cloud_out = rootView.findViewById(R.id.textView35);

        return rootView;
    }

    public void getWeatherData(String name) {

        ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);

        Call<Example> call = apiInterface.getWeatherData(name);

        call.enqueue(new Callback<Example>() {
            @Override
            public void onResponse(@NotNull Call<Example> call, @NotNull Response<Example> response) {

                assert response.body() !=null;
                current_temp.setText(response.body().getMain().getTemp() + " ℃");
                current_output.setText(response.body().getWeather().get(0).getDescription());
                rise_time.setText(response.body().getSys().getSunrise() + " ");
                set_time.setText(response.body().getSys().getSunset() + " ");
                temp_out.setText(response.body().getMain().getTemp() + " ℃");
                Press_out.setText(response.body().getMain().getPressure() + " hpa");
                Humid_out.setText(response.body().getMain().getHumidity() + " %");
                Ws_out.setText(response.body().getWind().getSpeed() + " Km/h");
                Visi_out.setText(response.body().getVisibility() + " m");
                Cloud_out.setText(response.body().getClouds().getAll()+ " %");
            }

            @Override
            public void onFailure(@NotNull Call<Example> call, @NotNull Throwable t) {
                t.printStackTrace();
            }
        });
    }
}

A: tl;dr
Instant                                      // Represents a moment, a point on the timeline, as seen in UTC (an offset of zero), with resolution of nanoseconds.
.ofEpochSecond( 1_620_792_785L )             // Returns a `Instant`.
.atZone(
    ZoneId.of( "Africa/Tunis" )              // Returns a `ZoneId`.

)                                            // Returns a `ZonedDateTime`.
.format(
    DateTimeFormatter
    .ofLocalizedTime( FormatStyle.MEDIUM )   // Returns a `DateTimeFormatter`.
    .withLocale( Locale.US ) ;               // Returns another `DateTimeFormatter` rather than altering the original, per immutable objects pattern.
)                                            // Returns a `String`.

Details
This has been covered many times on Stack Overflow. So I'll be brief. Search to learn more.

in the form of milliseconds(i.e 1620792785)

No, that looks like a count of whole seconds, not milliseconds, since 1970-01-01T00:00Z.
Never use the terrible legacy date-time classes. Use only java.time classes.
Parse your count of whole seconds since first moment of 1970 UTC as a Instant.
Instant instant = Instant.ofEpochSecond( 1_620_792_785L ) ;

To see that same moment using the wall-clock time kept by the people of a particular region, apply a time zone (ZoneId) to get a ZonedDateTime.
Specify a real time zone name in format of Continent/Region. Apparently your zone is six hours behind UTC. Several time zones currently share that offset-from-UTC. I arbitrarily chose one of them, America/Managua. So replace with your particular time zone.
ZoneId z = ZoneId.of( "America/Managua" ) ;
ZonedDateTime z = instant.atZone( z ) ;

To generate text representing that value, use a DateTimeFormatter object. Such an object can automatically localize by calling DateTimeFormatter.ofLocalizedTime.
Android 26 and later has java.time built-in. For earlier Android, most of the java.time functionality is available through "API desugaring" in the latest tooling.
Any city
After editing, you changed the nature of your Question to ask about how to change time zones according to any arbitrary city name the user may enter.
No magic solution there. You must translate from the user's entered city to a particular time zone name. I know of no library to do that. Mapping from a city name is tricky, as city names are far from unique For example, Paris France, Paris Texas. And many Springfield towns in the United States.
Usually an app asks the user to select their desired time zone. You can prompt for continent to narrow down the list.
To get a list of all time zones currently known at runtime by calling:
Set< String > timeZoneNames = ZoneId.getAvailableZoneIds() ;

See the excellent Answer by Ole V.V. to the original of your now-duplicate Question.


text:
Q: Jest failing to find nested test I have the following project setup:
.
|- package.json
|- library
  |- button
    |- button.test.tsx

When I run jest, it finds the test library/button/button.test.tsx, but gives the error message
ENOENT: no such file or directory, open '<root-dir>/library/button.test.tsx'

when running the test.
As you can see it is not looking in /library/button, but just /library.
How do I solve this?
package.json:
"jest": {
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "transform": {
      "\\.(ts|tsx)$": "./node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "./library/.*.test\\.(ts|tsx|js)$",
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
      "./__mocks__/fileMock.js",
      "\\.(css|less)$": "identity-obj-proxy"
    }
  }

A: Recommend setting the roots option:
{
  "roots": [
    "<rootDir>/library"
  ],
  "transform": {
    "^.+\\.tsx?$": "ts-jest"
  },
  "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "js",
    "jsx",
    "json",
    "node"
  ]
}

I personally use src folder only.


text:
Q: Add button to close panel I would like to add a close button to close a panel that appears in the browser. For that I have a javascript file that launches the prompt.html file that is my panel.
var panel = require('sdk/panel').Panel({
    width  : 400,
    height : 400,
    contentURL : self.data.url('prompt.html')
});

Then in my prompt.html I have the following :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>MyPanel</title>


text:
Q: Criação de diretórios em Python Eu tenho uma lista de diretórios a serem criados que tem essa estrutura :
Bla / Bla / Bla1.md

Bla / Bla / Bla2.md

Blu / Blue.md

Ble.md

Porém os arquivos .md não devem ser criados, mas as pastas que contém os mesmo devem, e para tal eu fiz o seguinte script :
# -*- coding: utf-8 -*-

import os

def build ( address ) :

    address = '/home/bezerk/Imagens/' + address

    if not os.path.exists ( address ) :

        os.makedirs ( address )

with open ( 'Arquivo.txt', 'r' ) as file :

    for line in file.readlines () :

        if line.endswith ( '.md' ) :

            # Tratamento aqui

            build ( line [:-3] )

        else :

            build ( line )

Porém não sei o motivo de o python não reconhecer isso Bla / Bla / Bla1.md mas um item separado como esse aqui Ble.md ele reconhece, se alguém puder me dar insights para resolver eu fico grato

A: Tente fazer os testes abaixo e se vc obtiver os mesmos resultados, o erro esta na sua lógica de tratamento do arquivo, se os resultados forem diferentes há algo de podre no reino do SO :-) vá na linha de comando:
$ cd ~
~$ python

from os import makedirs as mkdir
d1 = 'teste1/bla/bla/bla.md'
mkdir(d1)

Saia do pyton e execute o comando tree para ver a arvore criada a partir de teste1.
tree teste1

Volte ao python e faça:
d2 = 'test2 / bla /bla /bla.md'
mkdir(d2)

Saia do python e tente rodar o comando tree para obter a árvore do diretório teste2 e vc obterá um erro:
$ tree teste2
teste2 [error opening dir]

Por que isso acontece? pelo motivo de que, na verdade, não existe um diretorio chamado "teste2" e sim "teste2 " (com um espaço depois do 2), então comando tree deve ser executado da seguinte maneira:
$ tree teste2\

Note que após a barra há um espaço, este comando resulta na figura abaixo:

Executei os testes em um ubuntu 16, talvez o seu problema esteja no espaços entre as barras, a não ser que isso seja mandatório, tente retira-los, espaços em nomes de diretorios pode ser fonte de problemas, se tiver que mante-los lembre-se que vc tera que usar scape para referencia-los.


text:
Q: How to apply a linear-gradient background to a table row in IE9? I want to apply a linear-gradient background to a table row.
Here's the .css:

And here's the .html:

 Heading

What I am doing wrong here? Why the gradient isn't shown?

A: well, "Heading" text has to be wrapped with a td like so:

Heading


text:
Q: KnpPaginatorBundle sorting a Doctrine ArrayCollection Let's say I have an entity A with columns ID, foo, and bar which are either strings, integers or DateTime objects. This entity has all of the standard getters like getId(), getFoo(), and getBar().
In my controller, I have an object that is of another entity called B. The relationship between B and A is one to many. The getAllA() function finds all A associated with B which will return a Doctrine ArrayCollection. So with the object in the controller, I invoke
$paginator = $this->get('knp_paginator');
$paginatedObject = $paginator->paginate(
            $object->getAllA(),
            $this->get('request')->query->get('page', 1),
            3

Now pagination works fine, but how do I sort? In the table header row I have
{{ knp_pagination_sortable(paginatedObject, 'ID', '???????????????') }}

but what goes in for the question marks?

A: You could use a DQL query like
'SELECT o FROM AcmeBundle:Object o'

and then the third parameter would be 'o.id'
source


text:
Q: Why image don't hide when I set INVISIBLE? I am trying to use FragmentTransition library of bherbst in github:
FragmentTransitionSample
But I want image in DetailFragment invisible when transition end, so  I listen this event in GridFragment and set image invisible:
@Override
public void onKittenClicked(KittenViewHolder holder, int position) {
    int kittenNumber = (position % 6) + 1;

    kittenDetails = DetailsFragment.newInstance(kittenNumber);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        mDetailsTransition.addListener(new Transition.TransitionListener() {
            @Override
            public void onTransitionStart(Transition transition) {

            }

            @Override
            public void onTransitionEnd(Transition transition) {
                kittenDetails.invisibleView();
                Toast.makeText(getActivity(), "Hello===========>", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onTransitionCancel(Transition transition) {

            }

            @Override
            public void onTransitionPause(Transition transition) {

            }

            @Override
            public void onTransitionResume(Transition transition) {

            }
        });
    }

In DetailFragment:
public void invisibleView() {
    image.setVisibility(View.INVISIBLE);
}

This image only invisible when I click on 1st grid. Any idea, please?


text:
Q: collect and format logs from stdout(php - monolog) in node js with exec my PHP call from node.js is :
const process = exec('php ' + phpScriptPath, (err, phpResponse, stderr) => {

            if (err){
                this.logger.error('failed:' , err);
            }
        });

        process.stdout.on('data', (data) => {
            this.logger.info(data.toString());
        });

I am sending the logs  from the PHP script using monolog like following
the logs look like the following :
{"name":"node","environment":"development","hostname":"local","level":50,"msg":"{\"message\":\"log message\",\"context\":{\"error\":\"error message\"},\"level\":400,\"level_name\":\"ERROR\",\"extra\":[]}\n","time":"2019-05-05T06:38:26.147Z","v":0}

using Bunyan ,
how can I format this message to be more readable
PHP monolog formatter :
 $formatter = new \Monolog\Formatter\JsonFormatter();
        $streamHandler = new \Monolog\Handler\StreamHandler('php://stdout', \Monolog\Logger::DEBUG);
        $streamHandler->setFormatter($formatter);
        $log->pushHandler($streamHandler);

2- Php has a diffrent level of logs, how can I check what is the level of logs in node, hoe can I format the message in stdout and get the log level.
\"level_name\":\"ERROR\" .  for example
so I will find the "ERROR" string
3- How can I fit between the log level in node and php.
 if my node log level is "error", I won't be able to print the stdout logs because my code is. "this.logger.error()" . I need something more dynamic then hardcoded logs

A: ok for my second question I found the solution: if I get PHP log as  a JSON string I just can use the following from stdout:
 var phplog = JSON.parse(data);
 console.log(phplog.level_name)
// will print ERROR