text:
Q: Hi I want to print all the palindromic primes between 2 numbers the user inputs So, I am done with first part and most of 2nd one but can not figure out how to do Palindromic primes, so please help. The code i am attaching is p1b and I have no idea what to do in p1c so please help.
I. Introduction:
The purpose of this project is to help you learn the basic JAVA programming language
elements based upon your C/C++ background that you gained from CSC114.
II. Assignment: Develop a JAVA program according to the following steps:
Part A: Name this step p1a.java and you don't need to write a method other than main
for this.
1) The user is asked to enter an integer and your program is to produce the reverse
of that number.
Example follows:
Please enter an integer number: 2341
The reverse of 2341 is 1432
Part B: Name this step p1b.java.
1) Modify the last step using a method called reverse that returns the reverse value of
a given integer. Then, modify the program so that it will runs as the following:
2) The user is asked to enter two integers, say x and y;
3) So long as x is less than y, your program will do the following:
a) Find and print all prime numbers between x and y. (Need a method called
isPrime that checks whether a given number is a prime or not.)
b) Find and print all prime numbers that are also palindromes;
c) Ask for another pair of x and y.
Example follows:
Please enter two integer numbers: 5 400
Prime:
 5 7 11 13 17 19 23 29 31 37
 41 43 47 53 59 61 67 71 73 79
 83 89 97 101 103 107 109 113 127 131
 137 139 149 151 157 163 167 173 179 181
 191 193 197 199 211 223 227 229 233 239
 241 251 257 263 269 271 277 281 283 293
 307 311 313 317 331 337 347 349 353 359
 367 373 379 383 389 397
Palindromic Prime:
 5 7 11 101 131 151 181 191 313 353
 373 383
Please enter two integer numbers: 9 1
Done
Part C: Name this step p1c.java.
1) Traditionally, in order to produce the above output, the approach that one normally
has is to go through the numbers twice: the first time is to find and print all prime
numbers and then go through the numbers again to find and print all palindromic
primes. However, if we are able to keep the result and then print it when the
process is completed, then it will only need 1 pass.
2) Additionally, please display your output in a formatted way (such as aligned output
in the previous page).
3) Modify p1b.java so that it will only go through one pass to produce the same result
as produced in part B.
import java.util.Scanner;

public class p1b {

    public static void main(String[] args) {
        System.out.println("Program for Finding Primem Numbers: ");
        System.out.println("==================================");
        Scanner input = new Scanner(System.in);

        int num1, num2, i;
        int choice;
        System.out.print("Please enter the first number: ");
        num1 = input.nextInt();
        System.out.print("Please enter the Second number: ");
        num2 = input.nextInt();

        if (num1 > num2) {
            System.out.println("        Thank you.");
            System.exit(1);
        }
        System.out.println( isPrime(num1, num2));
        System.out.println( reverse(num1));

        System.out.print("\nWould you like to enter two more numbers, "
                + "Enter 1 for Yes or 0 for No: ");
        choice = input.nextInt();
        if(choice == 1) {
            System.out.print("Please enter the first number: ");
            num1 = input.nextInt();
            System.out.print("Please enter the Second number: ");
            num2 = input.nextInt();
            System.out.println( isPrime(num1, num2));
        }

        if(choice == 0) {
            System.out.println("Bye!!");
            System.exit(0);
        }
    }

    public static int isPrime(int num1, int num2) {
        final int displayPerLine = 50;
        System.out.print("Prime: ");
        for ( int i = num1; i <= num2; i++ ) {
            int j;
            for ( j = 2; j < i; j++) {
                int number = i % j;
                if (number == 0) {
                    break;
                    //return n;
                }
            }
            if(i == j) {
                System.out.printf("%-5d " + i);
            }
            if (i % displayPerLine == 0) {
                System.out.println();
            }
        }
        System.out.println();
            return num1;
    }

    //public static int reverse(int num1, int num2) {
    public static int reverse(int num1, int num2) {
        System.out.print("Palindrome: ");
        int palindrome = num1; // copied number into variable
        int reverse = palindrome;

        while (palindrome != 0) {
            int remainder = palindrome % 10;
            reverse = reverse * 10 + remainder;
            palindrome = palindrome / 10;
        }
        // if original and reverse of number is equal means
        // number is palindrome in Java
        if (num1 == reverse) {
            return reverse;
        }
        return palindrome;
    }

    public static int reverse(int num) {
        int test = 0;
        while (num != 0) {
            int lastdigit = num % 10;
            test = test * 10 + lastdigit;
            num = num / 10;
        }
        return test;
    }

    public static boolean isPalindrome(int num) {
        return num == reverse(num);
    }
}

A: Let's start by fixing isPrime, first test if the number is even; if so, it isn't prime. Next, test odd numbers from 3 to the square root of the number. If none of those are factors, then the number is prime. Something like,
public static boolean isPrime(int i) {
    if (i % 2 == 0) {
        return false;
    }
    double sqrt = Math.sqrt(i);
    for (int t = 3; t <= sqrt; t += 2) {
        if (i % t == 0) {
            return false;
        }
    }
    return true;
}

Then we can implement isPalindrome with a StringBuilder like
public static boolean isPalindrome(int i) {
    String str = String.valueOf(i);
    return new StringBuilder(str).reverse().toString().equals(str);
}

Finally, we can prompt for input in an infinite (here a while) loop and use an inner for loop for printing primes that are also palindromes. And, you can use Math.max and Math.min for getting the max and min respectively. Like,
public static void main(String[] args) {
    System.out.println("\t\tProgram for Finding Prime Numbers: ");
    System.out.println("\t\t===================================");
    Scanner input = new Scanner(System.in);
    while (true) {
        System.out.print("Please enter the first number: ");
        int num1 = input.nextInt();
        System.out.print("Please enter the second number: ");
        int num2 = input.nextInt();
        int lo = Math.min(num1, num2);
        int hi = Math.max(num1, num2);
        for (int i = lo; i <= hi; i++) {
            if (isPalindrome(i) && isPrime(i)) {
                System.out.println(i);
            }
        }
        System.out.print("Would you like to enter two more numbers, "
                + "Enter 1 for Yes or 0 for No: ");
        int choice = input.nextInt();
        if (choice == 0) {
            break;
        }
    }
}


text:
Q: how to retrieve git build data from jenkins pipeline I'm trying to retrieve the Git Build Data from jenkins pipeline and sent the details by mail
Is there any API or inbuilt variable available?

A: You can use GitLab APIs for this. Also, check Gitlab CLI as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to open modal that is in child component from parent? I have layout form where I have button click. In other component I have layout that inside have modal, so when I click on layout click I want to open modal.
https://plnkr.co/edit/wJjPL9ZYYsOapw8ylD12?p=preview
This is my plunker. Any suggestion how can I do that ? I'm getting error that is child undefined.
  <layout>

      <common-modal  #childModal [title]="'common modal'">

    {{5+7}} {{item}}
    Hi heloo

    </common-modal>

    </layout>

A: Set the attribute on the template variable for <layout>:
<layout [child]="childModal">
...

and in layout component:
   @Input() child;
...
  show(){
   this.child.show();
  }

DEMO


text:
Q: Which polygons have *simple* periodic billiard paths? I know (or, rather, believe) that it remains unknown whether every polygon
has a periodic billiard path.
But Howard Masur proved in the 1980's that every rational polygon
(vertex angles rational multiples of $\pi$) has (many) periodic billiard paths.

(Image from: W. Patrick Hooper, "Some irrational polygons have many periodic
billiard paths."
PDF download link.)

My question concerns simple paths: non-self-intersecting, i.e., embedded paths:

Q. Is it known that certain classes of rational polygons have simple
  periodic billiard paths?
  If so, which?
  That certain classes (of rational polygons) have no such simple periodic paths?
  If so, which?

For example, in an acute triangle, its pedal triangle is a simple periodic path,
and the only such.
To be narrowly specific: Might every regular polygon have a simple periodic path?

A: Consider the simple polygonal billiard path itself. It is a polygon and it is convex,
because all interior angles are less than $\pi$. Now start with an arbitrary convex polygon.
It is a billiard path on some polygonal table. Indeed, the lines from which the reflections
happened are uniquely determined by our billiard path. Continue these lines until they
intersect and form a table. Of course this table is not unique, because you can add
arbitrarily many sides which lie outside of the polygonal path and do not intersect our polygonal path. Neither the resulting table, nor the path itself has to have any symmetry.
EDIT. If the table is a triangle with acute angles, then a simple billiard path exists, is unique, and it is the triangle whose vertices are the bases of the three heights of the
table-triangle. This is due to H. A. Schwarz. (See Courant-Robbins,
What's mathematics, Ch. VII, sect. 4).
On the other hand, a triangle whose one angle is $\geq\pi/2$ violates the inequality noticed in Will Sawin's remark: the angles of the triangular table must satisfy $\alpha+\beta-\gamma\in(0,\pi)$ for a simple billiard part to exist.
Thus we have a complete description of triangular tables with a simple billiard path, and more generally, of those tables which have a triangular billiard path.

A: Here is a rather revised answer. I originally thought that having a line of symmetry (bisecting one or perhaps two edges ) might be a sufficient condition. Joseph showed a convincing counter-example to my reasoning. And Alexandre's observations finished it off.
Here is what I can salvage and add.
I'm not so interested in non-polygonal paths but here are a few
1) On the left below is a variation of the right triangle construction showing that a convex (or simply not too badly reentrant) polygonal table with a right angle has a simple periodic billiard path of the form $abcdcba.$ There are arbitrary further sides not shown.
One might require that a path touch all the sides in order to avoid arbitrary modifications which don't affect the path.
2) The top middle diagram is an isosceles triangle table with a path $bacab$ and another $defgfed.$

I'll now restrict to polygons with a simple periodic polygonal billiards path touching each side.
3) A construction given for (acute) isosceles triangle applies to arbitrary acute triangles. Drop the perpendicular from each vertex to the opposite sides. There is a path touching at just those points.
As Alexandre showed, any convex polygon can be a path and the path determines the polygonal table up to similarity (if we require equal number of sides. Will pointed if the path has angles $\alpha_1,\alpha_2,\cdots,\alpha_n$ then the table has angles $\frac{\alpha_i+\alpha_{i+1}}2.$ This provides a necessary condition for a table to have a path. It is a sufficient condition for a circularly ordered lists of angles to be realized by some tables having a path.
4) For a triangular path the table will have angles $\frac{\pi-\alpha_1}2,\frac{\pi-\alpha_2}2,\frac{\pi-\alpha_3}2.$ Hence an obtuse or even a right triangle has no triangular paths. This tells us everything about triangular tables.
5) For quadrilateral tables we see that opposite angles must add to $\pi.$ That is a strong condition (strong enough to demolish my conjecture.) However I have drawn a quadrilateral below with angles $\frac{\pi}4,\frac{\pi}2,\frac{3\pi}4,\frac{\pi}2.$ It is only slightly modified from a right triangle with no path. Since the angles are rational it should be possible to determine if it has a quadrilateral path. But I doubt it does.
6) Regular polygons have polygonal paths. The final table is pentagonal with all angles $\frac{3\pi}5.$ It even has a central line of symmetry. However I again suspect that it does not have a path of the type we seek.

A: An example that may be difficult for Aaron's line-of-symmetry argument:


text:
Q: how can delete inactive useres automatically after 24 hrs in classic asp I written a registration system in Classic ASP. user signup and will receive an activation email.
I want to delete records ( users ), if user did not active their account by clicking on activation link was sent to after 24Hrs.
how can do it?
my users table have these rows ( I'm using Access):
UserID     text
Username   text
Password   text
Email      text
Hash       text
join_date  date/time
active     Yes/No

P.s: I've no access to IIS configuration beacause my website is stored on a public server and not on a dedicated one

A: If you can't create a scheduled task to run an ASP script, then the next best thing might be to do this in global.asa in the Session_OnStart event. This runs every time a new session is started (a new user visits). If you set the last run time in an "Application" variable you can then choose to only run the routine to delete these users once a set time has elapsed. However, if you don't have frequent visitors to your site then it won't run often.
Sub Session_OnStart
   'Runs on application start or after 15 minutes
   If Application("LastRun") = "" Or DateDiff(n, Application("LastRun"), Now()) > 15 Then
       'Your code to delete users here, a query like this...
       'DELETE FROM [tableName] WHERE [active] = 0 AND DATEDIFF(hh, [join_date], GETDATE()) >= 24
       Application("LastRun") = Now()
   End If
End Sub


text:
Q: Printing specific row from a table I have a .csv table named data that looks like the following:

Age
name
ID

15
Stan
9

4
Danny
2

7
Elle
6

However, I want to print out a list of names from the table but only if their age is under 10. So in this case [Danny, Elle]. Here is what I tried so far
if data['Age'] < 10:
     print(data['name'])

I get an error The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). which I don't understand. It would be helpful to know how to solve this and also understand the error.

A: If you print type(data['Age'] < 10) it will return pandas.core.series.Series, this is not a boolean type as you are expecting, it is an object which looks as follows:
In [7]: data['Age'] < 10
Out[7]:
0    False
1     True
2     True
Name: Age, dtype: bool

You can think of it as a set of boolean elements which are true if the index satisfies the that age < 10 and False otehrwise. You can use these values to retrieve a subset of your table and then print the name column as follows (it will select a subset where the values are True):
sub = data[data['Age'] < 10]
print(sub['name'])

What the error is telling you is that pandas cannot figure out a boolean value for a complex object such as Series. Put it simply, it is a bunch of indexes, for which one of those are you evaluating it to be true? This is why there are suggestions such as a.any() or a.all(), which can be used to convert all the boolean values for each index into a single boolean value (if any of them is true, or if all of them are true, respectively). For example:
In [23]: a = data['Age'] < 10

In [24]: print(a)
0    False
1     True
2     True
Name: Age, dtype: bool

In [25]: a.any()
Out[25]: True

In [26]: a.all()
Out[26]: False

a.any() evaluates to true because there is at least one index which is True (2 and 1). a.all() evaluates to False because not every index is False (0 is False).

A: To get all names where age < 10 you can use boolean-indexing:
mask = df["Age"] < 10
print(df.loc[mask, "name"])

Prints:
1    Danny
2     Elle
Name: name, dtype: object

data['Age'] < 10 evaluates to:
0    False
1     True
2     True
Name: Age, dtype: bool

so when you do if data['Age'] < 10: what should be the result? The error message The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). is telling you that.


text:
Q: Show that $|X|=|X^G|$ (mod p) Let $G$ be a p-group, that is ,$|G|=p^n$ where $p$ is a prime and $n$ is a positive integer. Suppose that $G$ acts on a set $X$. Show that $|X|=|X^G|$ (mod p). $X^G=\{x\in{X}|gx=x \forall{g\in{G}}\}$.
I don't really have idea for this question, please help me.

A: Hint: $X=\mathcal{O}(x_1)\cup \mathcal{O}(x_2)\cup \cdots \cup \mathcal{O}(x_r)$, disjoint union of all orbits, and $X^G$ is union of singleton orbits.
Hence $|X|$ is the totality of all orbit-sizes whereas $|X^G|$ is the totality of the singleton orbit-sizes. Thus, the quantity $|X|-|X^G|$ is the totality of those orbit-sizes where orbits are not singleton.
If an orbit is not singleton, then is its cardinality divisible by $p$?


text:
Q: How to assign and extract table values defined in RECORD type Here is sample code
CREATE TYPE entity AS
(
    record_init boolean,
    b_modified boolean,
    custom_name character varying(8000),
    customer_rec customer,     --- customer is a table
    lang_pref boolean,
)

do
$$
declare
entity_rec entity;
Begin

    entity_rec.record_init := TRUE;
    entity_rec.customer_rec.customer_id := 100;
    raise notice ' Customer Id is %', entity_rec.customer_rec.customer_id;
end;
$$;

getting an error while referring customer_id from entity_rec.customer_rec

A: PLpgSQL doesn't support complex expressions on left side of assign statement. You should to divide this operation to more operations (this issue is fixed in prepared PostgreSQL 14):
DECLARE
  entity_rec entity;
  customer_rec customer;
BEGIN
  entity_rec.record_init := TRUE;
  customer_rec.customer_id := 100;
  entity_rec.customer_rec := customer_rec;
  raise notice ' Customer Id is %', entity_rec.customer_rec.customer_id;
END;

Second issue can be dereference of nested records. Postgres by default uses schema schema.table.name. When you use nested composite values, then the parenthesis should be used:

postgres=# do $$
DECLARE
  entity_rec entity;
  customer_rec customer;
BEGIN
  entity_rec.record_init := TRUE;
  customer_rec.customer_id := 100;
  entity_rec.customer_rec := customer_rec;
  raise notice ' Customer Id is %', entity_rec.customer_rec.customer_id;
END;
$$;
ERROR:  missing FROM-clause entry for table "customer_rec"
LINE 1: SELECT entity_rec.customer_rec.customer_id
               ^
QUERY:  SELECT entity_rec.customer_rec.customer_id
CONTEXT:  PL/pgSQL function inline_code_block line 9 at RAISE

Correct:

postgres=# do $$
DECLARE
  entity_rec entity;
  customer_rec customer;
BEGIN
  entity_rec.record_init := TRUE;
  customer_rec.customer_id := 100;
  entity_rec.customer_rec := customer_rec;
  raise notice ' Customer Id is %', (entity_rec).customer_rec.customer_id;
END;
$$;
NOTICE:   Customer Id is 100
DO


text:
Q: How to implement reliable UDP to transfer files quickly? I want to transfer some files from one point to another. Files are sensitive so transfer has to be reliable, but if I use TCP to transfer files than the speed gets slow.
How do I create a reliable version of UDP that will transfer files quickly?
What I am doing is sending an acknowledgement for every received packet. But it is reducing my transfer speed.
Is there any way that exists without sending an acknowledgment for every received packet? Can I somehow keep track of lost packets efficiently and request those packets only?
Note:: I am sending a sequence number with every packet

A: I guess that you could put a count value in each packet and if you received a packet that skips a value then you know that you've lost one or more and could request a resend.
However, you're starting to implement the functionality of TCP by coding for packet loss. Is there a reason why you couldn't implement that instead?
Certainly if I was transferring sensitive data I wouldn't choose UDP myself.


text:
Q: Add encrypted variables to travis.yml and push to open source project I have been contributing to open source project & in one of the issues, I have to upload a folder to AWS S3. I have created an amazon aws account and everything is working.
But I am not able to find a way to correctly encrypt the credentials in the travis.yml file & make a pull request. I am using travis gem to encrypt the variables but is giving me an error that the repository is not known.
Also I read somewhere that the pull request containing sensitive information are not allowed from the forks of that project.
Please guide me on how to do this task!


text:
Q: How do I fill/shade a cetain section of my graph in python? I have a function that I'd like to plot in python and shade the region of interest. I've tried using pyplot.fill_between() but can not quite get what I want. I've attached an image and shaded in orange the region I want to be filled:

I plot the function (in blue) and then the graph is bounded by y=0, y ≈ 0.05 and x = 0.And I wish to shade the relevant region (in orange).
Any tips as to how to go about this?
Thanks in advance.
import numpy as np
import matplotlib.pyplot as plt

def fn (M, r_min):

    d = (1- 2*M/ r_min)
    x = M/(r_min)**2
    A_0 = d**-0.5

    A_dot = np.arange(-0.6,0.5,0.0001) #X axis
    a = np.zeros(len(A_dot))

    for i in range(1,len(A_dot)):

        a[i] = -3*d*A_dot[i]**2 -2*x*A_dot[i] + A_0**2*x**2   #Y axis

    plt.plot(A_dot, a)
    plt.xlim(-0.55,0.55)

    plt.axhline(y = 0, color='black', linestyle='--')
    plt.axhline(y = 0.049382716, color = 'black', linestyle = '--')
    plt.axvline(x = 0,color ='black', linestyle = '--')
    idx = np.argwhere(np.diff(np.sign(a))).flatten() #Finding intersection on x+axis
    plt.plot(A_dot[idx], a[idx], 'ro')

    plt.xlabel('$\\frac{dA_0}{d\tau}$')
    plt.ylabel('$|a|^2$')

    plt.show()

    return(A_dot,a)

fn(1,3)

A: You need to give the x and y vectors as inputs to fill_between. To do that, you can define a mask selecting between the interception point and 0 (add to your fn function):
x_min = A_dot[idx[1]]
x_max = 0.0
mask_x = np.logical_and(A_dot >= x_min, A_dot <= x_max)
plt.fill_between(x=A_dot[mask_x], y1=a[mask_x], y2=0, color='orange')

Result:


text:
Q: Android Jni : crash in global and local ref variables I have jni c++ code that calls java objects methods, example :
jclass JIOManager = CJavaEnv::getInstance()->env()->FindClass(ioManagerName);

    ..... some code

CJavaEnv::getInstance()->env()->DeleteLocalRef(JIOManager);

this works really fine when executes in main thread, but when I try to execute this in another thread
it crash because it says that it is created in another thread :O !! but after I read in google android developer website, they say accessing Global Ref from any thread is fine, so I changed that code to be like.
jclass JIOManager = (jclass)CJavaEnv::getInstance()->env()->NewGlobalRef( CJavaEnv::getInstance()->env()->FindClass(ioManagerName) );

    ..... some code

CJavaEnv::getInstance()->env()->DeleteGlobalRef(JIOManager);

but I get this crash :
09-21 15:38:13.259: E/dalvikvm(3210): JNI ERROR (app bug): local reference table overflow (max=512)
09-21 15:38:13.259: W/dalvikvm(3210): JNI local reference table (0x76fb50) dump:
09-21 15:38:13.259: W/dalvikvm(3210):   Last 10 entries (of 512):
09-21 15:38:13.259: W/dalvikvm(3210):       511: 0x40a609a8 java.lang.Class<libcore.icu.NativeConverter>
09-21 15:38:13.259: W/dalvikvm(3210):       510: 0x42349610 byte[] (1 elements)
09-21 15:38:13.259: W/dalvikvm(3210):       509: 0x41d866b8 java.lang.Class<com.Cocoa.CocoaAndroidSDK.CocoaUnicodeConverter>
09-21 15:38:13.259: W/dalvikvm(3210):       508: 0x423495f8 byte[] (2 elements)
09-21 15:38:13.259: W/dalvikvm(3210):       507: 0x42349428 byte[] (1 elements)
09-21 15:38:13.259: W/dalvikvm(3210):       506: 0x41d866b8 java.lang.Class<com.Cocoa.CocoaAndroidSDK.CocoaUnicodeConverter>
09-21 15:38:13.259: W/dalvikvm(3210):       505: 0x42349410 byte[] (2 elements)
09-21 15:38:13.259: W/dalvikvm(3210):       504: 0x422b3f08 byte[] (1 elements)
09-21 15:38:13.259: W/dalvikvm(3210):       503: 0x41d866b8 java.lang.Class<com.Cocoa.CocoaAndroidSDK.CocoaUnicodeConverter>
09-21 15:38:13.259: W/dalvikvm(3210):       502: 0x422b3ef0 byte[] (2 elements)
09-21 15:38:13.259: W/dalvikvm(3210):   Summary:
09-21 15:38:13.259: W/dalvikvm(3210):       172 of java.lang.Class (3 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         1 of java.lang.String
09-21 15:38:13.259: W/dalvikvm(3210):         8 of byte[] (8 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):        20 of byte[] (1 elements) (20 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):        27 of byte[] (2 elements) (27 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         2 of byte[] (3 elements) (2 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):        16 of byte[] (4 elements) (16 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):        40 of byte[] (5 elements) (40 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         2 of byte[] (6 elements) (2 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         4 of byte[] (7 elements) (4 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):        22 of byte[] (8 elements) (22 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):        15 of byte[] (9 elements) (15 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):        40 of byte[] (10 elements) (40 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         3 of byte[] (11 elements) (3 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):        17 of byte[] (12 elements) (17 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         7 of byte[] (14 elements) (7 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         8 of byte[] (15 elements) (8 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):        15 of byte[] (16 elements) (15 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         8 of byte[] (17 elements) (8 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):        16 of byte[] (18 elements) (16 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         3 of byte[] (21 elements) (3 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         3 of byte[] (22 elements) (3 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):        17 of byte[] (24 elements) (17 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         4 of byte[] (28 elements) (4 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         8 of byte[] (30 elements) (8 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         1 of byte[] (32 elements)
09-21 15:38:13.259: W/dalvikvm(3210):         4 of byte[] (33 elements) (4 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         8 of byte[] (34 elements) (8 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         5 of byte[] (36 elements) (5 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         2 of byte[] (41 elements) (2 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         3 of byte[] (42 elements) (3 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         1 of byte[] (56 elements)
09-21 15:38:13.259: W/dalvikvm(3210):         4 of byte[] (66 elements) (4 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         4 of byte[] (72 elements) (4 unique instances)
09-21 15:38:13.259: W/dalvikvm(3210):         2 of byte[] (82 elements) (2 unique instances)
09-21 15:38:13.259: E/dalvikvm(3210): Failed adding to JNI local ref table (has 512 entries)
09-21 15:38:13.259: I/dalvikvm(3210): "AsyncTask #2" prio=5 tid=16 RUNNABLE
09-21 15:38:13.259: I/dalvikvm(3210):   | group="main" sCount=0 dsCount=0 obj=0x41decfd8 self=0x776200
09-21 15:38:13.259: I/dalvikvm(3210):   | sysTid=3236 nice=10 sched=0/0 cgrp=bg_non_interactive handle=7541280
09-21 15:38:13.259: I/dalvikvm(3210):   | schedstat=( 0 0 0 ) utm=82 stm=70 core=1
09-21 15:38:13.259: I/dalvikvm(3210):   at libcore.icu.NativeConverter.openConverter(Native Method)
09-21 15:38:13.259: I/dalvikvm(3210):   at java.nio.charset.CharsetEncoderICU.newInstance(CharsetEncoderICU.java:71)
09-21 15:38:13.259: I/dalvikvm(3210):   at java.nio.charset.CharsetICU.newEncoder(CharsetICU.java:27)
09-21 15:38:13.259: I/dalvikvm(3210):   at java.nio.charset.Charset.encode(Charset.java:451)
09-21 15:38:13.259: I/dalvikvm(3210):   at java.lang.String.getBytes(String.java:870)
09-21 15:38:13.259: I/dalvikvm(3210):   at com.Cocoa.CocoaAndroidSDK.CocoaUnicodeConverter.UTF8_TO_UTF16(CocoaUnicodeConverter.java:16)
09-21 15:38:13.259: I/dalvikvm(3210):   at com.Cocoa.CocoaAndroidSDK.CocoaSDKNativeLib.load(Native Method)
09-21 15:38:13.259: I/dalvikvm(3210):   at com.Cocoa.CocoaViewer.MainActivity$LongOperation.doInBackground(MainActivity.java:1498)
09-21 15:38:13.259: I/dalvikvm(3210):   at com.Cocoa.CocoaViewer.MainActivity$LongOperation.doInBackground(MainActivity.java:1)
09-21 15:38:13.259: I/dalvikvm(3210):   at android.os.AsyncTask$2.call(AsyncTask.java:264)
09-21 15:38:13.259: I/dalvikvm(3210):   at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-21 15:38:13.259: I/dalvikvm(3210):   at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-21 15:38:13.259: I/dalvikvm(3210):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-21 15:38:13.259: I/dalvikvm(3210):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-21 15:38:13.259: I/dalvikvm(3210):   at java.lang.Thread.run(Thread.java:856)
09-21 15:38:13.259: E/dalvikvm(3210): VM aborting
09-21 15:38:13.259: A/libc(3210): Fatal signal 11 (SIGSEGV) at 0xdeadd00d (code=1)

Any help is appreciated.

A: The "other" thread must also be attached to use the JIOManager. Why not get a local reference also there? On the other hand, your crash dump suggests that actually you are only looking at 3 classes. So You can create the global references to these once (even in JNI_OnLoad() if you find it easier), and use them from all your native threads.

A: There is a limit on the number of local references per thread, and you're exceeding it.  The most common way to do this is to create local references in a loop and not delete them as you go.
Local references are cleaned up automatically (and near-instantly) when execution returns to the VM, so for simple uses its best to just let the VM do the work.  But if you're creating more than 16 local references, it's a good idea to do the clean up manually.
The call to FindClass creates a local reference.  The call to NewGlobalRef creates a global reference, without destroying the local reference.  You should modify your code to look like this:
jclass temp = CJavaEnv::getInstance()->env()->FindClass(ioManagerName);
jclass JIOManager = (jclass)CJavaEnv::getInstance()->env()->NewGlobalRef(temp);
CJavaEnv::getInstance()->env()->DeleteLocalRef(temp);

Global references are not destroyed unless you explicitly destroy them, so be careful about leaking them.  When CheckJNI is enabled there's a cap of a few thousand; without CheckJNI they're allowed to accumulate without bound.
See also JNI Tips.


text:
Q: Autoit pause Start/stop hotkey I have a script pushing "k" button in loop. I have added pause button on "q".
I also want "w" to pause the script. But I don want "w" to start my script. Is that possible?
Global $UnPaused
HotKeySet("q", "TogglePause")
HotKeySet("{PAUSE}", "TogglePause")
HotKeySet("{.}", "Terminate")

While 1
Sleep(100)
WEnd

Func TogglePause()
$UnPaused = NOT $UnPaused
While $UnPaused
    Send("k")
WEnd
EndFunc

Func Terminate()
Exit 0
EndFunc

A: I suggest rearranging your code & introducing a Pause() function to make things easier:
Global $UnPaused=false;
HotKeySet("q", "Pause")
HotKeySet("{PAUSE}", "TogglePause")
HotKeySet("{.}", "Terminate")

While 1
    if $UnPaused Then
        Send("k");
    Else
        Sleep(100)
    EndIf
WEnd

Func Pause()
$UnPaused = False
EndFunc

Func TogglePause()
$UnPaused = NOT $UnPaused
EndFunc

Func Terminate()
Exit 0
EndFunc

And if you don't want to capture a hotkey whilst paused, here's an example of that:
Global $UnPaused=false;
HotKeySet("q", "Pause")
HotKeySet("{PAUSE}", "TogglePause")
HotKeySet("{.}", "Terminate")
HotKeySet("w", "Pause")
While 1
    if $UnPaused Then
        HotKeySet("w", "Pause")
        Send("k");
    Else
        HotKeySet("w")
        Sleep(100)
    EndIf
WEnd

Func Pause()
$UnPaused = False
EndFunc

Func TogglePause()
$UnPaused = NOT $UnPaused
EndFunc

Func Terminate()
Exit 0
EndFunc


text:
Q: Previous Value not being retrieved I created a default_manufacturer_id field to a table and am trying to show the options under $manufacturer_list in a drop down. The drop down populates fine, but the previous value of default_manufacturer_id is not shown up as selected by default.
If I hard-code a specific value with the "value" key in the addField, then that value is shown up as selected. I was expecting the previous value of the default_manufacturer_id field to show up.
    CRUD::addField([
        'name' => 'default_manufacturer_id',
        'type' => "select_from_array",
        'label' => "Default Manufacturer",
        'options' => $manufacturer_list,
        'allows_null' => false,
    ]);

What is stopping this value from showing up as selected automatically? I have checked the database, and the value being saved is correct.
Version numbers are as follows:
root@f9c300ad6814:/var/www/html# php artisan backpack:version
PHP VERSION:
PHP 8.1.13 (cli) (built: Nov 26 2022 14:07:55) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.13, Copyright (c) Zend Technologies
with Zend OPcache v8.1.13, Copyright (c), by Zend Technologies
with Xdebug v3.2.0, Copyright (c) 2002-2022, by Derick Rethans
LARAVEL VERSION:
v9.49.0@e02d9453442ad0a6a2f5dc9df96ea0319d218026
BACKPACK PACKAGE VERSIONS:
backpack/crud: 5.4.11
backpack/pro: 1.1.2
backpack/generators: v3.3.7
With Regards,
Sharat


text:
Q: How do I convert a JSON DateTime format to a C# DateTime format from an API call I'm currently building a project that retrieves API data and saves it into a database. Everything is working fine except for the DateTime values in the API. I have a class that uses RestSharp to obtain the API data then it uses NewtonSoft.Json to derserialize the API data into a JSON format which is then stored into a temporary DTO class file. Here is the API method.
public static void getAllRequestData()
{
    var client = new RestClient("[My API URL]");
    var request = new RestRequest();
    var response = client.Execute(request);

    if (response.StatusCode == System.Net.HttpStatusCode.OK)
    {
        string rawResponse = response.Content;
        AllRequests.Rootobject result = JsonConvert.DeserializeObject<AllRequests.Rootobject>(rawResponse);
    }
}

Now here is the DTO file (AllRequests) that will temporarily store the Converted JSON data.
public class AllRequests
    {
        public class Rootobject
        {
            public Operation Operation { get; set; }
        }

        public class Operation
        {
            public Result Result { get; set; }
            public Detail[] Details { get; set; }
        }

        public class Result
        {
            public string Message { get; set; }
            public string Status { get; set; }
        }

        public class Detail
        {
            [Key]
            public int Id { get; set; }
            public string Requester { get; set; }
            public string WorkOrderId { get; set; }
            public string AccountName { get; set; }
            public string CreatedBy { get; set; }
            public string Subject { get; set; }
            public string Technician { get; set; }
            public string IsOverDue { get; set; }
            public string DueByTime { get; set; }
            public string Priority { get; set; }
            public string CreatedTime { get; set; }
            public string IgnoreRequest { get; set; }
            public string Status { get; set; }
        }
    }

The lines of code in Details that I want to be DateTime formats are "DueByTime" and "CreatedTime" instead of being String values. Currently they're only holding JSON format DateTime values in a String such as "1477394860065".
I've tried making "public string CreatedTime { get; set; }" to "public DateTime CreatedTime { get; set; }" However that only returned an error since it's JSON format. How could I rectify this issue so that it's stored in the DTO correctly in a DateTime format? Because ideally I want to scaffold this class file into a table so it can hold data in a database.
For more context to this, here's what I want rectified in my Database.

I want there to be a DateTime shown instead of a long list of numbers like there is here under Createby and DueBy.
Any help would be appreciated.

A: [EDIT] added the unix time format compliance[/EDIT]
Just putting in code what @Fildor said
public long CreatedTime { get; set; }

[JsonIgnore] // will ignore the property below when serializing/deserializing
public DateTimeOffset CreatedTimeDate {
    // Don't need a setter as the value is directly get from CreatedTime property
    get {
        return DateTimeOffset.FromUnixTimeMilliseconds(CreatedTime);
    }
}

Used also this answer to convert to DateTime as asked, using the local time.
Here is how you convert to DateTime if you don't need the offset : https://learn.microsoft.com/fr-fr/dotnet/standard/datetime/converting-between-datetime-and-offset


text:
Q: How to convert Timestamp - Datetime to dd-MM-yyy without time I'm running a powershell script and exporting the output for a rapport.
Tried different format possibilities to change dd-MM-YYYY HH-MM-SS to just showing dd-MM-YYYY but can't figure it out
@{Name="Date"; Expression={[DateTime]::FromFileTime($_.LastLogonTimestamp)}}

I'm getting 30-10-2017 10:07:10 and only want to get the output 30-10-2017

A: Just convert them to the required format using the below statement.
@{Name="Date"; Expression={[DateTime]::FromFileTime($_.LastLogonTimestamp).ToString('dd-MM-yyyy')}}

Check this documentation for more reference!

https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings

A: If you already have the value as a DateTime, e.g.
$date = [DateTime]::FromFileTime($_.LastLogonTimestamp)

You can use one of the ToString overloads provided by the object type, e.g.
$formattedDate = $date.ToString("dd-MM-yyyy")

You can get further information about formatting options on this link.


text:
Q: Question about the use of DISTINCT when using subqueries So the problem given: Obtain the cast list for the film 'Alien'.
My initial code was:
select name
from actor
join casting
on actor.id=actorid where actorid in (
select actorid from casting join movie on movieid=id where title='alien')

I got an error because each actor was listed multiple times, I resolved it by selecting DISTINCT name, but I kind of don't understand why there was a multiple listing of actors? The subquery gives only actorids' that where listed in casting table with movieid corresponding to title 'Alien'. So there is only one distinct actorid from this query.

A: You are getting multiple rows for each actor because each actor is in multiple movies (presumably).  You are filtering by the actor, but there are already multiple rows.
So, you don't need the outer join:
select a.name
from actor a
where a.id in (select c.actorid
               from casting c join
                    movie m
                    on c.movieid = m.id
               where m.title = 'alien'
              );

Voila!  No duplicates and no select distinct.
More importantly:

*

*Qualify all column references, particularly in a query that references multiple tables.

*Use table aliases so the query is simpler to write and to read.


text:
Q: c# - Binary Search Algorithm for Custom Class String List Basically I need help adapting my Binary Search Algorithm to work with my string list as seen below. Note, I have to use a written Binary Search algorithm, no use of built-in c# functions like .BinarySearch .
I will now show you how the list is formatted and the list itself:
// This class formats the list, might be useful to know

public class Demo
{
    public string Col;
    public string S1;
    public string S2;
    public string S3;

    public override string ToString()
    {
        return string.Format("Col: {0}, S1: {1}, S2: {2}, S3: {3}", Col, S1, S2, S3);
    }
}

// The list itself

var list = new List<Demo>
        {
            new Demo {Col = "Blue", S1 ="88", S2 ="Yes"},
            new Demo {Col = "Green", S1 ="43", S2 ="Yes"},
            new Demo {Col = "Red", S1 ="216", S2 ="No"},
            new Demo {Col = "Yellow", S1 ="100", S2 ="No"}
        };

The list is already sorted into alphabetical order of the 'Col' string values, hence why Blue is first and Yellow is last. The 'Col' is the part of the list that needs to be searched. Below I have inserted my current Binary Search that can search int arrays.
public static int BinarySearch_R(int key, int[] array, int low, int high)
    {
        if (low > high) return -1;
        int mid = (low + high) / 2;
        if (key == array[mid])
        {

            return mid;
        }
        if (key < array[mid]) {
            return BinarySearch_R(key, array, low, mid - 1);
        } else {
            return BinarySearch_R(key, array, mid + 1, high);
        }
    }

I need help adapting my BinarySearch Algorith to work for the list above. If you guys have any questions, or need to see more of my code, just ask.

A: Concrete answer: Adapting your method for the specific case is quite easy.
Let first update your existing method to use a more general method (IComparable<T>.CompareTo for comparing rather than the int operators:
public static int BinarySearch_R(int key, int[] array, int low, int high)
{
    if (low > high) return -1;
    int mid = (low + high) / 2;
    int compare = key.CompareTo(array[mid]);
    if (compare == 0)
    {
        return mid;
    }
    if (compare < 0)
    {
        return BinarySearch_R(key, array, low, mid - 1);
    }
    else {
        return BinarySearch_R(key, array, mid + 1, high);
    }
}

Then all you need is to copy/paste the above method, replace int key with string key, int[] array with List<Demo> array and array[mid] with array[mid].Col:
public static int BinarySearch_R(string key, List<Demo> array, int low, int high)
{
    if (low > high) return -1;
    int mid = (low + high) / 2;
    int compare = key.CompareTo(array[mid].Col);
    if (compare == 0)
    {
        return mid;
    }
    if (compare < 0)
    {
        return BinarySearch_R(key, array, low, mid - 1);
    }
    else {
        return BinarySearch_R(key, array, mid + 1, high);
    }
}

Extended answer: While you can do the above, it will require you to do the same for any other property/class you need such capability.
A much better approach would be to generalize the code. For instance, int[] and List<Demo> can be generalized as IReadOnlyList<T>, int/string key as TKey key, Demo.Col as Func<T, TKey>, CompareTo as IComparer<TKey>.Compare, so the final generic method could be like this:
public static class MyAlgorithms
{
    public static int BinarySearch<T, TKey>(this IReadOnlyList<T> source, Func<T, TKey> keySelector, TKey key, IComparer<TKey> keyComparer = null)
    {
        return source.BinarySearch(0, source.Count, keySelector, key, keyComparer);
    }

    public static int BinarySearch<T, TKey>(this IReadOnlyList<T> source, int start, int count, Func<T, TKey> keySelector, TKey key, IComparer<TKey> keyComparer = null)
    {
        // Argument validations skipped
        if (keyComparer == null) keyComparer = Comparer<TKey>.Default;
        int lo = start, hi = start + count - 1;
        while (lo <= hi)
        {
            int mid = lo + (hi - lo) / 2;
            int compare = keyComparer.Compare(key, keySelector(source[mid]));
            if (compare < 0)
                hi = mid - 1;
            else if (compare > 0)
                lo = mid + 1;
            else
                return mid;
        }
        return -1;
    }
}

Now you can use that single method for any data structure. For instance, searching your List<Demo> by Col would be like this:
int index = list.BinarySearch(e => e.Col, "Red");

A: Ive only done the most basic things in C# so this might just be completely useless. I had an assignment for CS 2 class where at least it sounds somewhat similar to what you want but we use java. So im going to assume you want your list of items sorted by some keyword ("Blue","Green" etc...). I used a LinkedList but it doesnt matter.
    class Node {
    String keyword;
    LinkedList<String> records = new LinkedList<>();
    Node left;
    Node right;

    public Node(String keyword, LinkedList<String> records) {
        this.keyword = keyword;
        this.records = records;
    }
}

Now, the only real difference at least i can tell between having a BST sorted by a string and one sorted by numbers is that you need some type of comparison method to see whether one word is > or < in alphabet. So here's how i did the insert function:
   /**
 * insert node
 * @param keyword compare it to other strings
 */
public void insert(String keyword, LinkedList<String> records) {
    //create a new Node
    Node n = new Node(keyword, records);
    int result;
    Node current = root;
    Node parent = null;

    //cont. until NULL
    while (current != null) {
        result = current.keyword.compareTo(n.keyword);
        if (result == 0) return;
        else if (result > 0) {
            parent = current;
            current = current.left;
        }
        else if (result < 0) {
            parent = current;
            current = current.right;
        }
    }

    if (parent == null) root = n;
    else {
        result = parent.keyword.compareTo(n.keyword);
        if (result > 0) parent.left = n;

        else if (result < 0) parent.right = n;

    }
}

So the method "compareTo(...)" returns 1 if string is higher in alphabet 0 if same and -1 if lower. So i would, if im at all close to getting what youre asking, get the C# version of this method and implement BST as you normally would.

A: Just create make class IComparable and create a custom CompareTo() method. The standard methods like sort will automatically work once the class inherits IComparable.
   public class Demo : IComparable
    {
        public string Color;
        public int value;
        public Boolean truth;

        public int CompareTo(Demo other)
        {
            int results = 0;
            if (this.Color == other.Color)
            {
                if (this.value == other.value)
                {
                    results = this.truth.CompareTo(other.truth);
                }
                else
                {
                    results = this.value.CompareTo(other.value);
                }
            }
            else
            {
                results = this.Color.CompareTo(other.Color);
            }

            return results;
        }


text:
Q: how to import/export jars with included old version external jars? I have project "A" which includes log4j.jar (log4j version 1.2).
I export this project "A" as A.jar.
When someone have log4J updated version (1.2.17) and he imports my A project (import A.jar) , he gets class not found error (because  log4j is not the same version)
Is there a way to solve this, without creating new version of A.jar (with the updated log4j jar) ?

A: Sounds like you're running into a classic dependency management problem.
The long-term solution is to use a build tool designed for this - in Java probably the best place to start for this is Maven, but also consider Ivy as a more single-purpose tool.
With either you can specify what version of libraries you depend upon (and when, in your build / runtime lifecycle), and  get them from a global repository where necessary.


text:
Q: Cannot access NodePort service outside Kubernetes cluster I am on Windows and used Docker Desktop to deploy a local Kubernetes cluster using WSL 2. I tried to deploy a pod and expose it through a NodePort service so I could access it outside the cluster, but it is not working.
Here are the commands to reproduce the scenario:
kubectl create deployment echoserver --image=k8s.gcr.io/echoserver:1.4
kubectl expose deployment echoserver --type=NodePort --port=8080

Trying to open NODE_IP:EXPOSED_PORT in the browser or running the netcat command nc NODE_IP EXPOSED_PORT and trying to send a message (from either WSL or Windows) does not work.

*

*NODE_IP is the internal IP of the Docker Desktop K8S node (obtained by seeing the INTERNAL-IP column on the command kubectl get nodes -o wide)

*EXPOSED_PORT is the node port exposed by the service (obtained by seeing the field NodePort on command kubectl describe service echoserver)

Opening the URL on the browser should be met with this page. However, you will get a generic error response saying the browser couldn't reach the URL.
Sending a message with the netcat command should be met with a 400 Bad Request response, as it will not be a properly formatted HTTP request. However, you will not get any response at all or the TCP connection may not even be made in the 1st place.
Trying to communicate with the service and/or the pod from inside the cluster, for example, through another pod, works perfectly.
Using the command kubectl port-forward deployment/echoserver 2311:8080 to port forward the deployment locally and then either accessing localhost:2311 in the browser or through netcat also work perfectly (in both WSL and Windows).

A: If you want to access it not using localhost you should use your <windows_hosts's_IP:NodePort>.
So having your deployment and service deployed:
$kubectl get svc,deploy
NAME                 TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
service/echoserver   NodePort    10.105.169.2   <none>        8080:31570/TCP   4m12s
service/kubernetes   ClusterIP   10.96.0.1      <none>        443/TCP          5m3s

NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/echoserver   1/1     1            1           4m19s

You can either access it by using localhost:31570 or <windows_hosts's_IP:NodePort>.
In my case 192.168.0.29 is my Windows host's IP:
curl.exe 192.168.0.29:31570
CLIENT VALUES:
client_address=192.168.65.3
command=GET
real path=/
query=nil
request_version=1.1
request_uri=http://192.168.0.29:8080/


text:
Q: Sentry.io API get issues filtering on environment tag I would like to retrieve the issues from sentry.io
The following code returns me the first page of the issues
import json
import requests

url = "https://sentry.io/api/0/projects/my-account/my-project/issues/"
res = requests.get(url, headers={"Authorization": "Bearer <token here>")
issues = json.loads(res.text)

I'm struggling to use the "query" mentioned in their (brief) documenation:
https://docs.sentry.io/api/events/list-a-projects-issues/

query (string)
An optional Sentry structured search query. If not provided an implied "is:unresolved" is assumed.

Question: How would I use query to filter for instance "environment" being equal "production"?

A: I got mislead by the documentation. It's actually rather straight forward:
import json
import requests

url = "https://sentry.io/api/0/projects/my-account/my-project/issues/"
query_str = "environment=production"
res = requests.get(f"{url}?{query_str}", headers={"Authorization": "Bearer <token here>")
issues = json.loads(res.text)


text:
Q: Spark - Replace column value - regex pattern value is having slash value- how to handle it? Data Frame:
+-------------------+-------------------+
|               Desc|   replaced_columns|
+-------------------+-------------------+
|India is my Country|India is my Country|
| Delhi is my Nation| Delhi is my Nation|
| I Love India\Delhi| I Love India\Delhi|
|         I Love USA|         I Love USA|
|I am stay in USA\SA|I am stay in USA\SA|
+-------------------+-------------------+

"Desc" column is the original column name from DataFrame. replace_columns is after we are doing some transformation. In desc column , i need to replace "India\Delhi" value to "-". I tried below code.
dataDF.withColumn("replaced_columns", regexp_replace(dataDF("Desc"), "India\\Delhi", "-")).show()

it is NOT replacing with "-" string. How can i do that one ?

A: I found 3 approaches for the above question:
val approach1 = dataDF.withColumn("replaced_columns", regexp_replace(col("Desc"), "\\\\","-")).show() // (it should be 4 backslash in actual while running in IDE)

val approach2 = dataDF.select($"Desc",translate($"Desc","\\","-").as("replaced_columns")).show()

The below one is for specific record which you asked above -- ( In desc column , I need to replace "India\Delhi" value to "-". I tried below code.)
val approach3 = dataDF
   .withColumn("replaced_columns",when(col("Desc").like("%Delhi")
     , regexp_replace(col("Desc"), "\\\\", "-")).otherwise(col("Desc")))
    .show()


text:
Q: Jetty upgrade 8 to 9 When I am trying to migrate to Jetty 9.4.18 from Jetty 8.1.12, I am getting errors because of following issues.

*

*we are using  org.eclipse.jetty.server.AsyncContinuation. Which is not present in Jetty 9.4.18

*We are using AbstractHttpConnection.   specifically AbstractHttpConnection.getCurrentConnection() method. Which is not present in Jetty 9.4.18.

*We are using org.eclipse.jetty.security.MappedLoginService which is not present in Jetty 9.4.18.

*we are using connector.getConnection() method. which is not present in Connector class in Jetty 9.4.18.

I did not find any documentation in Jetty upgrade page for these issues.

A: Welcome to Stackoverflow!
It is not a great idea to ask multiple unrelated questions on a single question.

1) we are using org.eclipse.jetty.server.AsyncContinuation. Which is not present in Jetty 9.4.18

AsyncContinuation is an Jetty 7 and older concept.
It was kept in Jetty 8 as a transition to the Servlet spec specific behaviors regarding async that were introduced in Servlet 3.0 (supported in Jetty 8.x).
Switch to using javax.servlet.AsyncContext instead.  (You'll find many of the methods names to be similar, so the transition shouldn't be that problematic).

2) We are using AbstractHttpConnection. specifically AbstractHttpConnection.getCurrentConnection() method. Which is not present in Jetty 9.4.18

If you are accessing the raw Connection you will have an endless stream of issues ahead of you.   The Connection object no longer represents the physical connection, it often represents a virtual connection and can mutate or be swapped out through the lifespan of a physical connection.  You have failed to explain why you need this, and under what kind of situations and environments you need this.
Create a new question on stackoverflow explaining why you need this, and what goal you are attempting to solve. (not the techniques you were using before, the goal, the end result)

3) We are using org.eclipse.jetty.security.MappedLoginService which is not present in Jetty 9.4.18

The entire Security layer was refactored, without details on what you are attempting, it would be impossible to point you to the correct place to look.
Create (another) question on stackoverflow for this one too.  Explain what you are attempting to solve, show some code.  When detailing your question focus on the goal first, then the techniques you have attempted.

4) we are using connector.getConnection() method. which is not present in Connector class in Jetty 9.4.18.

This seems to overlap with question 3, perhaps.
But there's nothing to work with on this kind of question.


text:
Q: Overriding iPhone shutter sound through SDK In my iPhone app, I am using the UIImagePickerController with source type UIImagePickerControllerSourceTypeCamera. When the user takes a picture, the phone plays the familiar camera shutter sound. How can I replace this with my own custom sound? I know it's possible because I've seen other apps from the App Store do it (e.g. Red Laser).

A: I am quite certain it's not possible. AFAIK, Red Laser doesn't actually take a "normal" picture but uses UIGetScreenImage() (undocumented but nevertheless allowed for App Store apps) to make a screenshot of the live video feed. Since the OS does not play sound on this occasion, they are free to play their own sound.
Edit for clarification: As of OS 3.1, you are free to substitute the standard camera interface with your own controls. So you could place your own shutter button on the screen and play your own sound when the user taps it, but AFAIK there is now way to get rid of the OS's standard shutter sound.

A: AFAIK the standard camera shutter sound cannot be changed via SDK.
This answer supports that. You can replace your own sound by switching sound files, but not in an app.
Some answers such as this one suggest using AVCapture, but this method takes video screenshots, which reduces the image quality. I
t appears that you can't change the shutter sound because you could make it a silent sound, and capturing images covertly is against the App Store policy. See this answer.
TLDR:
The only way to change the shutter sound is to use a video screen grab.


text:
Q: Dynamic Rendering of tiles as per custom selected options Cartida is one of the best Customize map providers.
https://www.cartida.com/global/map/

On Cartida, you can choose, whatever color of roads you want, whatever building color you want and so many other features. So, on each change of option, they call to a service, something like
https://maps.cartida.com/cartida/map?style=cartida&width=1205&height=850&bbox=8262171.608849932,3689647.5481946995,8292984.162073471,3711382.544244499&webmerclevel=12&boost=1&scalefactor=1.8179293857353394&colors=water:0x9BBCD9|land:0xffffff|objects:0x7a1f1f|buildings:0xffffff|background:0xFFFFFF&show=roads,road_details,water,landuse

How can I make a customizable map like this for my own area of interest? Let's say I have osm data for a city, and want to create a webapp that can provide such customization for layer on/off or color change etc.


text:
Q: reasonable expectations for CALayer number of property animations concurrently? I'm using UIView animation blocks to animate CALayer properties (backgroundColor in this case) on multiple layers on the display at once.
All layers are opaque, and I'm animating everything in one block, essentially like this
[UIView beginAnimations:@"outer" context:nil];
float duration = .25;
float offset = 0.0;
for( NSArray *viewsInPass in viewQueue ) {
   for( UIView *innerView in viewInPass ) {
       [UIView beginAnimations:@"inner" context:nil];
       [UIView setAnimationDelay:offset];
       [UIView setAnimationDuration:duration];
       [innerView.layer setBackgroundColor:[newColor CGColog]];
       [UIView commitAnimations];
   }
   offset += duration;
}
[UIView commitAnimations];

Once this has 4-5 concurrent layers animating their background color it get very choppy and the device essentially starts missing its render rate entirely and just freezes to the end of the remaining animations.  All views do not overlap and they are all opaque, and are generally about 20x20 pixels.
I was a little shocked at how non-performant this is, especially after reading so many gratifying things about Quartz 2D etc.  I feel like I must be missing something fundamental  here!
Help!

A: Opaqueness in the views is the single biggest performance impact - if you can keep them from overlapping and entirely opaque through the whole rendering process (i.e. no transparency anywhere in that view sequence, including the background), you'll get slightly better perf.
I managed to get a single large animation up at ~30 fps (i.e. whole screen), but ran into memory limitations (original iPhone/iPod) that ultimately killed me beyond that. If you want more than about what you're getting there, you'll need go into OpenGL land - either through a gaming framework or directly. The overhead of the objective-C calls in that loop to enable changing the offset at the same time that you're cycling through images will ultimately kill you.

A: Edit: [removed]
Since you have each animation start as the previous one ends, you could start each in an NSTimer or the delegate didFinish callback instead of queueing all the animations at once.  That would put less demand on the animation system.
You should try to make sure that no views are queued with different colors at the same time.

A: It turns out the issue is that all you need to add some sort of epsilon between the offsets you start with.  You end up with n*2 animating at the tail of each pass and the start of the next just for an instant.  For some reason this makes the animation system barf even if it's just a processing slice they share.
Making it be
offset += duration * 1.05;
resolved the jerkiness between passes that clogged up the animations.


text:
Q: Find smallest set of rows whose column sums at least reach a target I'm trying to write an algorithm that prints the solution for the following problem:

Given a target array T = [t1, t2, ...
tn], and a set of lists S = { A = [a1,
a2, ... an], B = [b1, b2,
... bn], ... X = [x1, x2, ...
xn] }, what is the subset of S with the lowest cardinality
that satisfies the condition where the sum of the ith terms
of each array in the subset are at least ti?

Example:
T = [2, 3, 1]

S = {[0, 1, 2], [1, 0, 1], [2, 2, 0]}

The subset with the lowest cardinality that satisfies the above conditions is the set {[0, 1, 2], [2, 2, 0]}. Expressing the sums of each array's ith terms as [2, 3, 2], you can see that each ith sum is greater than or equal to the ith term of T.
I've looked at other subset-sum problems but can't come up with an efficient algorithm to solve this one.


text:
Q: MVVM+Kotlin+Databinding best practice I am building an app on MVVM+Kotlin+Databinding, and i have this situation i am stuck at.
I have LoginFragment which has a phone number edittext and a button,
Now i need to check if the phone number is empty or not when user clicks the button.
Normally i would do that by using this code in my fragment.
if(!binding!!.phone.text.isEmpty()) {
    //do something
}

But according to experts my view should not know anything about the business logic, Hence i need to have this check inside my viewModel.
so what should be the best way to achieve this?

A: Here is the bet practice to achieve that (from my point of view):
In your layout add text watcher and text to your EditText
android:text="@{view_model.phone}"
app:addTextChangedListener="@{view_model.phoneWatcher}"

and on click method to your button
android:onClick="@{() -> view_model.save()}"

Inside the ViewModel you will have text observable and a watcher
val phone = ObservableField<String?>()

val phoneWatcher = object : TextWatcherAdapter() {
    override fun afterTextChanged(s: Editable?) {
        phone.set(s?.toString())
    }
}

Now you can make your check inside ViewModel
fun save() {
    if (phone.get()?.isNotEmpty == true) {
        // TODO: do something
    }
}

Also please note that it is a best practice to avoid doing something like that binding!!.phone in Kotlin. If you're using !! to make a possible nullable object look like it is not-nullable (even if you're 100% sure it is) - you're doing something wrong.


text:
Q: Using UIWebView to call the Upload method I want to upload some data to Amazon S3. I must use the UIWebView call from the Amazon SDK (multipartUpload:) to achieve that.
The main problem is that my ViewController freezes execution until the upload finishes.
Is there a way to solve this? I tried starting a new thread from WebView for just the upload Upload method, but the application crashes.
And the second question: Does anyone know of any functions that would allow pausing/resuming uploads in Amazon S3?

A: You can set the upload on a background thread.
    // perform edit asynchronously to avoid blocking ui
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
             //UPLOAD CODE GOES HERE AND RUNS OUTSIDE OF THE MAINTHREAD SO NO UI IS BLOCKED
    });

Here is a link that goes into using grand central dispatch to perform async processes.
http://blog.slaunchaman.com/2011/02/28/cocoa-touch-tutorial-using-grand-central-dispatch-for-asynchronous-table-view-cells/


text:
Q: Introduction to De Moivre's theorem
If $a=\cos\frac{2π}7+i\sin\frac{2π}7$, $b=a+a^2+a^4$, $c=a^3+a^5+a^6$, show that $b$ and $c$ are the roots of the equation $x^2+x+2=0$.

A: HINT
Note that
$$a=\cos\frac{2π}7+i\sin\frac{2π}7=e^{\frac{2πi}7}$$
thus
$$1+a+a^2+a^3+a^4+a^5+a^6=0$$
Proof that sum of complex unit roots is zero

A: $$b+c=\cos\frac{2\pi}{7}+\cos\frac{4\pi}{7}+\cos\frac{8\pi}{7}+\left(\sin\frac{2\pi}{7}+\sin\frac{4\pi}{7}+\sin\frac{8\pi}{7}\right)i+$$
$$+\cos\frac{6\pi}{7}+\cos\frac{10\pi}{7}+\cos\frac{12\pi}{7}+\left(\sin\frac{6\pi}{7}+\sin\frac{10\pi}{7}+\sin\frac{12\pi}{7}\right)i=$$
$$=\cos\frac{2\pi}{7}+\cos\frac{4\pi}{7}+\cos\frac{6\pi}{7}+\cos\frac{6\pi}{7}+\cos\frac{4\pi}{7}+\cos\frac{2\pi}{7}+$$
$$+\left(\sin\frac{2\pi}{7}+\sin\frac{4\pi}{7}-\sin\frac{6\pi}{7}+\sin\frac{6\pi}{7}-\sin\frac{4\pi}{7}-\sin\frac{2\pi}{7}\right)i=$$
$$=\frac{2\sin\frac{\pi}{7}\cos\frac{2\pi}{7}+2\sin\frac{\pi}{7}\cos\frac{4\pi}{7}+2\sin\frac{\pi}{7}\cos\frac{6\pi}{7}}{2\sin\frac{\pi}{7}}=$$
$$=\frac{\sin\frac{3\pi}{7}-\sin\frac{\pi}{7}+\sin\frac{5\pi}{7}-\sin\frac{3\pi}{7}+\sin\frac{7\pi}{7}-\sin\frac{5\pi}{7}}{2\sin\frac{\pi}{7}}=-1.$$
You can calculate the value of $ab$ by the same way.
Indeed, since we proved that $$\cos\frac{2\pi}{7}+\cos\frac{4\pi}{7}+\cos\frac{6\pi}{7}=-\frac{1}{2},$$ we obtain:
$$bc=\left(-\frac{1}{2}+\left(\sin\frac{2\pi}{7}+\sin\frac{4\pi}{7}+\sin\frac{8\pi}{7}\right)i\right)\left(-\frac{1}{2}-\left(\sin\frac{2\pi}{7}+\sin\frac{4\pi}{7}+\sin\frac{8\pi}{7}\right)i\right)=$$
$$=\frac{1}{4}+\left(\sin\frac{2\pi}{7}+\sin\frac{4\pi}{7}-\sin\frac{6\pi}{7}\right)^2=$$
$$=\tfrac{1}{4}+\sin^2\frac{2\pi}{7}+\sin^2\frac{4\pi}{7}+\sin^2\frac{6\pi}{7}+2\sin\frac{2\pi}{7}\sin\frac{4\pi}{7}-2\sin\frac{2\pi}{7}\sin\frac{6\pi}{7}-2\sin\frac{4\pi}{7}\sin\frac{6\pi}{7}=$$
$$=\frac{1}{4}+\frac{1}{2}\left(1-\cos\frac{4\pi}{7}+1-\cos\frac{6\pi}{7}+1-\cos\frac{2\pi}{7}\right)+$$
$$+\cos\frac{2\pi}{7}-\cos\frac{6\pi}{7}+\cos\frac{6\pi}{7}-\cos\frac{4\pi}{7}+\cos\frac{4\pi}{7}-\cos\frac{2\pi}{7}=\frac{1}{4}+\frac{7}{4}=2$$
and use the Vieta's theorem.
Also, we can use De Moivre here.
$a^7=\cos2\pi+i\sin2\pi=1$ and since $a\neq1$, we obtain:
$$a^6+a^5+a^4+a^3+a^2+a+1=0,$$ which gives $b+c=-1.$
Now, $$bc=a^4(1+a+a^3)(1+a^2+a^3)=a^4(a^6+a^5+a^4+3a^3+a^2+a+1)=2a^7=2$$ and we are done again.


text:
Q: Google App Engine Enterprise and SQL/Django Admin? I'm having a difficult time finding definitive information on this. If I have a paid, enterprise account with Google, can I host SQL databases and thus the Django Admin feature? I have a MySQL database I would like to port to GAE and make viewable via the Django Admin section, and an Enterprise Google account is an option, but I need to know for sure if I can even do this with an Enterprise account.

A: The App Engine For Business Roadmap list the status of hosted SQL as Preview, with an ETA in Q2 2011. So I guess the answer is:
Not yet.


text:
Q: Dependency of buoyancy on volume and mass of submerged object When we fully submerge a volume of 1 litre, whether that mass is 1 kg or 100 kg, isn't the volume of the displaced liquid always the same and equal to the actual 1 litre, i.e. to the volume of the fully submerged object?
So in other words the buoyant force acting on a fully submerged object is only dependent to the volume of the object?
Of course for different fluids, the density of the fluid will play a role, but we are talking about the same fluid.

A: Yes.
Buoyancy force is dependent on:

*

*density of fluid

*gravitational acceleration

*submerged volume of a body

It does not matter if you are putting 2.7 kg block of aluminium or 7.4 kg block of tin. The buoyant force is the same.

A: Archimedes' principle of buoyant forces states that:
$$ {\vec F_B} = -\rho V \hspace{1pt}{\vec g}, $$
where $\rho$ = Density of the fluid, $V$ = Volume of body submerged in liquid, ${\vec g}$ = Acceleration due to gravity.
The physical interpretation is essentially that the water exerts a force opposite to the gravitational pull on the submerged part of the body.
Here's a nice image you can analyse with a force diagram to figure out the "effective weight" of a body when submerged as an exercise:


text:
Q: How to configure power managment with tlp? I have a similar issue like this user, that is my hard drive overheats.
I'm running Ubuntu MATE 15.10, which has tlp, and I've read that they should not be installed together.
So is there a way to configure the things in the linked post with tlp?

A: You can't install TLP and laptop-mode-tools at the same time (the tlp package conflicts with the laptop-mode-tools package to prevent parallel install).
I understand you want to have the equivalent of
NOLM_HD_IDLE_TIMEOUT_SECONDS=7200 # 2 hours
LM_AC_HD_POWERMGMT=1
NOLM_AC_HD_POWERMGMT=1

This translates to
DISK_APM_LEVEL_ON_AC="1"
DISK_SPINDOWN_TIMEOUT_ON_AC="244"

in the TLP configuration.
But i recommend against APM = 1. This could mean excessive wear caused by frequent start/stop cycles of the spindle motor and/or load cycles for the heads.
My recommendation for TLP is to try APM = 128 on AC (same as on battery):
DISK_APM_LEVEL_ON_AC="128"
DISK_APM_LEVEL_ON_BAT="128"

and not to change DISK_SPINDOWN_TIMEOUT_ON_AC because a spindown timeout of 2h doesn't make sense.
Then install the package smartmontools and monitor the HDD temp with
sudo tlp-stat -d

Output shows:
...
SMART info:
  ...
  190 Airflow_Temperature_Cel   =       28 [°C]

Refer to the TLP configuration docs for more info.


text:
Q: grouping multiple columns and bringing values into character string This is an example we can work with:
df <- tibble(y = c("a", "a", "a", "a", "a", "a"), z = c("b", "b", "b", "b", "b", "b"), a = c("aaa", "aaa", "aaa", "bbb", "bbb", "bbb"),
             b = c(1,2,3,1,2,3), c = c(5,10,15,100,95,90))
df
# A tibble: 6 x 5
  y     z     a         b     c
  <chr> <chr> <chr> <dbl> <dbl>
1 a     b     aaa       1     5
2 a     b     aaa       2    10
3 a     b     aaa       3    15
4 a     b     bbb       1   100
5 a     b     bbb       2    95
6 a     b     bbb       3    90

I want to group the values in column y, z and a and combine column b and c to a single string. The final result should look exactly like this:
# A tibble: 2 x 4
  y      z       a        result
  <chr>  <chr>   <chr>    <chr>
1 a      b       aaa      {"1":5,"2":10,"3":15}
2 a      b       bbb      {"1":100,"2":95,"3":90}

Which i can almost achieve with:
b <- by(df[-1:-3], df$a, function(x)
  sprintf("{%s}", toString(Reduce(paste0, c(x, "\"", "\":")[c(3, 1, 4, 2)]))))
data.frame(a=unique(df$a), result=do.call(rbind, as.list(b)), row.names=NULL)

    a                    result
1 aaa   {"1":5, "2":10, "3":15}
2 bbb {"1":100, "2":95, "3":90}

This only groups by column a, though and not by all three (y, z and a) columns. I got the hint that i can do fix it with the aggregate function but have a hard time appying it.

A: Using dplyr you can make use sprintf/paste0 :
library(dplyr)

df %>%
  group_by(y, z, a) %>%
  summarise(result = paste0('{', toString(sprintf('"%d":"%d"', b, c)), '}')) %>%
  ungroup %>% data.frame()

#  y z   a                          result
#1 a b aaa   {"1":"5", "2":"10", "3":"15"}
#2 a b bbb {"1":"100", "2":"95", "3":"90"}

Using by this can be written as :
do.call(rbind, by(df, list(df$y, df$z, df$a), function(x)
  cbind(unique(x[1:3]),
        result = paste0('{', toString(sprintf('"%d":"%d"', x$b, x$c)), '}'))))


text:
Q: Java Swing Layout Problems & Code Optimisation In order to train Java I wrote my own program.
I like to play CSGO and we never can decide what map to play.
So I want to write a program where you can select the maps you want and then it gives out each map from the selection randomly and only once.
There's a bit more to it, but the code for that is working already.
I tried this once already with the Swing Form builder from IntelliJ (my IDE),
but as I didn't really understand what it did there, I wanted to redo it by hand. So I rewrote the program, but I can't get it to look properly.
My first Try with IntelliJ Swing Builder:

Without the help of the GUIBuilder it looks like this right now:

So I Googled hours to get the right Layout. Currently I'm using GridBagLayout (seems to fit my needs the most). But I can't get it right. It should look like the first picture.
So, Question 1:
What am I doing wrong with GridBag as there is a lot of unused space and stuff
and Question 2: I know there's a lot to improve codewise, what are your tips?
I still have problems knowing when to private and access methods & stuff,
so are there any mistakes that are crucial?
Here is my code:
Its 3 Classes:
First
First
Main Class (just for starting)
import javax.swing.*;

public class App {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new MainFrame("Map Chooser v0.1");
                frame.setSize(500, 250);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

** The Swing MainFrame: **
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class MainFrame extends JFrame {

    ImageIcon dust2;

    public MainFrame(String title) {
        super(title);

        GridLayout gridMain = new GridLayout(10, 10, 5, 5);
        GridLayout gridCB = new GridLayout(3, 5, 5, 5);
        GridLayout gridButton = new GridLayout(1, 1, 10, 10);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(gridMain);
        mainPanel.setBackground(Color.DARK_GRAY);

        JPanel checkboxPanel = new JPanel();
        checkboxPanel.setLayout(gridCB);
        checkboxPanel.setBackground(Color.DARK_GRAY);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(gridButton);
        buttonPanel.setBackground(Color.DARK_GRAY);

        JPanel labelPanel = new JPanel();
        labelPanel.setBackground(Color.DARK_GRAY);

        mainPanel.add(checkboxPanel);
        mainPanel.add(buttonPanel);
        mainPanel.add(labelPanel);

        MapRound map = new MapRound();
        //GridBagConstraints gbc = new GridBagConstraints();
        GridBagConstraints gbc2 = new GridBagConstraints();
        GridBagConstraints gbc3 = new GridBagConstraints();
        gbc2.weighty = 0.5;
        gbc2.weightx = 0.5;

        gbc3.weightx = 1;
        gbc3.weighty = 1;
        gbc3.fill = GridBagConstraints.ABOVE_BASELINE;

        //Checkboxes
        JCheckBox dust2CB = new JCheckBox("Dust II");
        dust2CB.setBackground(Color.DARK_GRAY);
        dust2CB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 0;
        gbc2.gridy = 0;
        checkboxPanel.add(dust2CB, gbc2);
        dust2CB.setSelected(false);

        JCheckBox trainCB = new JCheckBox("Train");
        trainCB.setBackground(Color.DARK_GRAY);
        trainCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 0;
        gbc2.gridy = 1;
        checkboxPanel.add(trainCB, gbc2);
        trainCB.setSelected(false);

        JCheckBox mirageCB = new JCheckBox("Mirage");
        mirageCB.setBackground(Color.DARK_GRAY);
        mirageCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 0;
        gbc2.gridy = 2;
        checkboxPanel.add(mirageCB, gbc2);
        mirageCB.setSelected(false);

        JCheckBox infernoCB = new JCheckBox("Inferno");
        infernoCB.setBackground(Color.DARK_GRAY);
        infernoCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 1;
        gbc2.gridy = 0;
        checkboxPanel.add(infernoCB, gbc2);
        infernoCB.setSelected(false);

        JCheckBox cobblestoneCB = new JCheckBox("Cobblestone");
        cobblestoneCB.setBackground(Color.DARK_GRAY);
        cobblestoneCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 1;
        gbc2.gridy = 1;
        checkboxPanel.add(cobblestoneCB, gbc2);
        cobblestoneCB.setSelected(false);

        JCheckBox overpassCB = new JCheckBox("Overpass");
        overpassCB.setBackground(Color.DARK_GRAY);
        overpassCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 1;
        gbc2.gridy = 2;
        checkboxPanel.add(overpassCB, gbc2);
        overpassCB.setSelected(false);

        JCheckBox cacheCB = new JCheckBox("Cache");
        cacheCB.setBackground(Color.DARK_GRAY);
        cacheCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 2;
        gbc2.gridy = 0;
        checkboxPanel.add(cacheCB, gbc2);
        cacheCB.setSelected(false);

        JCheckBox aztecCB = new JCheckBox("Aztec");
        aztecCB.setBackground(Color.DARK_GRAY);
        aztecCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 2;
        gbc2.gridy = 1;
        checkboxPanel.add(aztecCB, gbc2);
        aztecCB.setSelected(false);

        JCheckBox dustCB = new JCheckBox("Dust");
        dustCB.setBackground(Color.DARK_GRAY);
        dustCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 2;
        gbc2.gridy = 2;
        checkboxPanel.add(dustCB, gbc2);
        dustCB.setSelected(false);

        JCheckBox vertigoCB = new JCheckBox("Vertigo");
        vertigoCB.setBackground(Color.DARK_GRAY);
        vertigoCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 3;
        gbc2.gridy = 0;
        checkboxPanel.add(vertigoCB, gbc2);
        vertigoCB.setSelected(false);

        JCheckBox nukeCB = new JCheckBox("Nuke");
        nukeCB.setBackground(Color.DARK_GRAY);
        nukeCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 3;
        gbc2.gridy = 1;
        checkboxPanel.add(nukeCB, gbc2);
        nukeCB.setSelected(false);

        JCheckBox officeCB = new JCheckBox("Office");
        officeCB.setBackground(Color.DARK_GRAY);
        officeCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 3;
        gbc2.gridy = 2;
        checkboxPanel.add(officeCB, gbc2);
        officeCB.setSelected(false);

        JCheckBox italyCB = new JCheckBox("Italy");
        italyCB.setBackground(Color.DARK_GRAY);
        italyCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 9;
        gbc2.gridy = 0;
        checkboxPanel.add(italyCB, gbc2);
        italyCB.setSelected(false);

        JCheckBox assaultCB = new JCheckBox("Assault");
        assaultCB.setBackground(Color.DARK_GRAY);
        assaultCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 9;
        gbc2.gridy = 1;
        checkboxPanel.add(assaultCB, gbc2);
        assaultCB.setSelected(false);

        JCheckBox militiaCB = new JCheckBox("Militia");
        militiaCB.setBackground(Color.DARK_GRAY);
        militiaCB.setForeground(Color.LIGHT_GRAY);
        gbc2.gridx = 9;
        gbc2.gridy = 2;
        checkboxPanel.add(militiaCB, gbc2);
        militiaCB.setSelected(false);

        //Buttons
        JButton startButton = new JButton("Start");
        startButton.setBackground(Color.DARK_GRAY);
        startButton.setForeground(Color.LIGHT_GRAY);
        gbc3.gridx = 0;
        gbc3.gridy = 0;
        gbc3.insets = new Insets(10, 10, 10, 10);
        startButton.setPreferredSize(new Dimension(400, 400));
        buttonPanel.add(startButton, gbc3);

        JButton newmapButton = new JButton("New Map");
        newmapButton.setBackground(Color.DARK_GRAY);
        newmapButton.setForeground(Color.LIGHT_GRAY);
        gbc3.gridx = 0;
        gbc3.gridy = 1;
        gbc3.weightx = 1.0;
        gbc3.weighty = 1.0;
        gbc3.insets = new Insets(0, 0, 10, 10);
        buttonPanel.add(newmapButton, gbc3);
        newmapButton.setEnabled(false);

        JButton resetButton = new JButton("Reset");
        resetButton.setBackground(Color.DARK_GRAY);
        resetButton.setForeground(Color.LIGHT_GRAY);
        gbc3.gridx = 0;
        gbc3.gridy = 3;
        gbc3.insets = new Insets(0, 0, 10, 10);
        buttonPanel.add(resetButton, gbc3);
        resetButton.setEnabled(false);

        //Labels
        JLabel result = new JLabel("Press START to begin");
        gbc3.gridx = 0;
        gbc3.gridy = 4;
        gbc3.insets = new Insets(0, 0, 10, 10);
        labelPanel.add(result, gbc3);

        //Verhalten
        dust2CB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {

                if (dust2CB.isSelected()) {
                    map.mList.add("DustII");
                } else {
                    map.removeMap("DustII");
                }
            }
        });

        trainCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (trainCB.isSelected()) {
                    map.mList.add("Train");
                } else {
                    map.removeMap("Train");
                }
            }
        });

        mirageCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (mirageCB.isSelected()) {
                    map.mList.add("Mirage");
                } else {
                    map.removeMap("Mirage");
                }
            }
        });

        infernoCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (infernoCB.isSelected()) {
                    map.mList.add("Inferno");
                } else {
                    map.removeMap("Inferno");
                }
            }
        });

        cobblestoneCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (cobblestoneCB.isSelected()) {
                    map.mList.add("Cobblestone");
                } else {
                    map.removeMap("Cobblestone");
                }
            }
        });

        overpassCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (overpassCB.isSelected()) {
                    map.mList.add("Overpass");
                } else {
                    map.removeMap("Overpass");
                }
            }
        });

        cacheCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (cacheCB.isSelected()) {
                    map.mList.add("Cache");
                } else {
                    map.removeMap("Cache");
                }
            }
        });

        aztecCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (aztecCB.isSelected()) {
                    map.mList.add("Aztec");
                } else {
                    map.removeMap("Aztec");
                }
            }
        });

        dustCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (dustCB.isSelected()) {
                    map.mList.add("Dust");
                } else {
                    map.removeMap("Dust");
                }
            }
        });

        vertigoCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (vertigoCB.isSelected()) {
                    map.mList.add("Vertigo");
                } else {
                    map.removeMap("Vertigo");
                }
            }
        });

        nukeCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (nukeCB.isSelected()) {
                    map.mList.add("Nuke");
                } else {
                    map.removeMap("Nuke");
                }
            }
        });

        officeCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (officeCB.isSelected()) {
                    map.mList.add("Office");
                } else {
                    map.removeMap("Office");
                }
            }
        });

        italyCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (italyCB.isSelected()) {
                    map.mList.add("Italy");
                } else {
                    map.removeMap("Italy");
                }
            }
        });

        assaultCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (assaultCB.isSelected()) {
                    map.mList.add("Assault");
                } else {
                    map.removeMap("Assault");
                }
            }
        });

        militiaCB.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (militiaCB.isSelected()) {
                    map.mList.add("Militia");
                } else {
                    map.removeMap("Militia");
                }
            }
        });

        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e2) {

                if (map.mList.size() == 0) {
                    JOptionPane.showMessageDialog
                            (null, "Please add one or more    maps to the selection pool!");
                } else {

                    map.scambleMap();
                    startButton.setEnabled(false);
                    newmapButton.setEnabled(true);
                    resetButton.setEnabled(true);

                    dust2CB.setEnabled(false);
                    trainCB.setEnabled(false);
                    mirageCB.setEnabled(false);
                    infernoCB.setEnabled(false);
                    cobblestoneCB.setEnabled(false);
                    overpassCB.setEnabled(false);
                    cacheCB.setEnabled(false);
                    aztecCB.setEnabled(false);
                    dustCB.setEnabled(false);
                    vertigoCB.setEnabled(false);
                    nukeCB.setEnabled(false);
                    officeCB.setEnabled(false);
                    italyCB.setEnabled(false);
                    assaultCB.setEnabled(false);
                    militiaCB.setEnabled(false);
                }
            }
        });

        newmapButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e2) {
                boolean preventloop = true;

                try {
                    while (preventloop) {
                        String xyz = map.nextMap();
                        result.setText("
                                "+ xyz + ");
                        preventloop = false;
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null,
                            "You played all maps!\nThe game has been reset");
                    map.resetStatus();
                    result.setText("Press START to begin");
                    newmapButton.setEnabled(false);
                    startButton.setEnabled(true);
                    dust2CB.setEnabled(true);
                    trainCB.setEnabled(true);
                    mirageCB.setEnabled(true);
                    infernoCB.setEnabled(true);
                    cobblestoneCB.setEnabled(true);
                    overpassCB.setEnabled(true);
                    cacheCB.setEnabled(true);
                    aztecCB.setEnabled(true);
                    dustCB.setEnabled(true);
                    vertigoCB.setEnabled(true);
                    nukeCB.setEnabled(true);
                    officeCB.setEnabled(true);
                    italyCB.setEnabled(true);
                    assaultCB.setEnabled(true);
                    militiaCB.setEnabled(true);
                }
            }
        });

        resetButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                map.resetStatus();
                result.setText("Press START to begin");
                newmapButton.setEnabled(false);
                startButton.setEnabled(true);

                dust2CB.setEnabled(true);
                trainCB.setEnabled(true);
                mirageCB.setEnabled(true);
                infernoCB.setEnabled(true);
                cobblestoneCB.setEnabled(true);
                overpassCB.setEnabled(true);
                cacheCB.setEnabled(true);
                aztecCB.setEnabled(true);
                dustCB.setEnabled(true);
                vertigoCB.setEnabled(true);
                nukeCB.setEnabled(true);
                officeCB.setEnabled(true);
                italyCB.setEnabled(true);
                assaultCB.setEnabled(true);
                militiaCB.setEnabled(true);
            }
        });

        this.add(mainPanel);
        this.setVisible(true);
    }
}

And the last:
(Blueprint for Map Object which containes the Arraylist
import java.util.ArrayList;
import java.util.Collections;
public class MapRound {
    ArrayList mList = new ArrayList<>();
    int counter = 0;
//Constructor
public MapRound() {
}

public String nextMap() {
    String result = mList.get(counter);
    counter = counter + 1;
    return result;
}

public void resetStatus() {
    counter = 0;
    Collections.shuffle(mList);
}

public String removeMap(String index) {
    mList.remove(index);
    return index;
}

public void scambleMap() {
    Collections.shuffle(mList);
}

}
If you have any ideas or advices, I would be happy to hear them!

A: Looking at your code, I see the GridLayout layout manager being used (instead of GridBagLayout). Although the names are very similar, their behavior is very different. This also means that the GridBagConstraints objects you pass along when adding a component to one of the panels will not be understood properly. (It would be nice if the layout manager would give an error message when a constraints object is passed that it cannot handle.)
See for example this nice Visual Guide to Layout Managers for more information on these two (and other) layout managers.
I think the BoxLayout layout manager and empty borders around some panels would be useful for your program too. You can use labels to show the images at the top and bottom of your GUI. I think that all GridBagConstraints related code can be removed. An example screenshot:

Your MainFrame class could be modified like this:
public class MainFrame extends JFrame {

    //ImageIcon dust2;
    public MainFrame(String title) {
        super(title);

        //GridLayout gridMain = new GridLayout(5, 0, 5, 5);
        GridLayout gridCB = new GridLayout(3, 5, 5, 5);
        //GridLayout gridButton = new GridLayout(4, 1, 10, 10);

        JPanel mainPanel = new JPanel();
        BoxLayout mainLayout = new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS);
        mainPanel.setLayout(mainLayout);
        mainPanel.setBackground(Color.DARK_GRAY);

        JPanel checkboxPanel = new JPanel();
        checkboxPanel.setLayout(gridCB);
        checkboxPanel.setBackground(Color.DARK_GRAY);

        JPanel buttonPanel = new JPanel();
        BoxLayout buttonLayout = new BoxLayout(buttonPanel, BoxLayout.PAGE_AXIS);
        buttonPanel.setLayout(buttonLayout);
        buttonPanel.setBorder(new EmptyBorder(6, 6, 6, 6));
        buttonPanel.setBackground(Color.DARK_GRAY);

        JPanel labelPanel = new JPanel();
        labelPanel.setBackground(Color.DARK_GRAY);

        String directory = "directory/to/images/";

        JPanel topImagePanel = new JPanel();
        topImagePanel.setBackground(Color.DARK_GRAY);
        topImagePanel.setBorder(new EmptyBorder(6, 6, 6, 6));
        String topImagePath = directory + "map selector - top.png";
        topImagePanel.add(new JLabel(new ImageIcon(topImagePath)));

        JPanel bottomImagePanel = new JPanel();
        bottomImagePanel.setBackground(Color.DARK_GRAY);
        bottomImagePanel.setBorder(new EmptyBorder(6, 6, 6, 6));
        String bottomImagePath = directory + "map selector - bottom.png";
        bottomImagePanel.add(new JLabel(new ImageIcon(bottomImagePath)));

        mainPanel.add(topImagePanel);
        mainPanel.add(checkboxPanel);
        mainPanel.add(buttonPanel);
        mainPanel.add(labelPanel);
        mainPanel.add(bottomImagePanel);

        // [...]

        //Buttons
        JButton startButton = new JButton("Start");
        startButton.setBackground(Color.DARK_GRAY);
        startButton.setForeground(Color.LIGHT_GRAY);
        gbc3.gridx = 0;
        gbc3.gridy = 0;
        gbc3.insets = new Insets(10, 10, 10, 10);
        startButton.setPreferredSize(new Dimension(400, 400));
        buttonPanel.add(startButton, gbc3);
        startButton.setAlignmentX(Component.CENTER_ALIGNMENT);

        buttonPanel.add(Box.createRigidArea(new Dimension(0, 6)));

        JButton newmapButton = new JButton("New Map");
        newmapButton.setBackground(Color.DARK_GRAY);
        newmapButton.setForeground(Color.LIGHT_GRAY);
        gbc3.gridx = 0;
        gbc3.gridy = 1;
        gbc3.weightx = 1.0;
        gbc3.weighty = 1.0;
        gbc3.insets = new Insets(0,0,10,10);
        buttonPanel.add(newmapButton, gbc3);
        newmapButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        newmapButton.setEnabled(false);

        buttonPanel.add(Box.createRigidArea(new Dimension(0, 6)));

        JButton resetButton = new JButton("Reset");
        resetButton.setBackground(Color.DARK_GRAY);
        resetButton.setForeground(Color.LIGHT_GRAY);
        gbc3.gridx = 0;
        gbc3.gridy = 3;
        gbc3.insets = new Insets(0,0,10,10);
        buttonPanel.add(resetButton, gbc3);
        resetButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        resetButton.setEnabled(false);

        // [...]
    }
}

Edit: some general advice for your code

*

*The MainFrame constructor is very large. I would split it up in smaller methods to create the different panels and to add the listeners.

*Search for similar pieces of code to see if you can make a reusable method. For example: there are three blocks of code that set all check boxes to disabled or enabled. You could make a method with a boolean parameter to call setEnabled for all check boxes.

*Creating the check boxes currently takes a lot of code. If you have a list of game maps, you could create the check boxes in a loop. (This is a nice advantage of creating your GUI in code.) If you use the name property of each check box, they could all share the same ItemListener. And finally, if you store all the check boxes in a list, you can easily disable or enable all of them.

Some code to illustrate this:
java.util.List<String> gameMaps = Arrays.asList(
        "Dust II", "Train", "Mirage", "Inferno", "Cobblestone", "Overpass",
        "Cache", "Aztec", "Dust", "Vertigo", "Nuke", "Office", "Italy",
        "Assault", "Militia"
);

ItemListener mapCheckBoxListener = new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent itemEvent) {
        JCheckBox checkBox = (JCheckBox) itemEvent.getSource();
        if (checkBox.isSelected()) {
            map.mList.add(checkBox.getName());
        } else {
            map.removeMap(checkBox.getName());
        }
    }
};

java.util.List<JCheckBox> mapCheckBoxes = new ArrayList<>();
for (String gameMap : gameMaps) {
    JCheckBox mapCheckBox = new JCheckBox(gameMap);
    mapCheckBox.setName(gameMap);
    mapCheckBox.setBackground(Color.DARK_GRAY);
    mapCheckBox.setForeground(Color.LIGHT_GRAY);
    checkboxPanel.add(mapCheckBox);
    mapCheckBox.setSelected(false);
    mapCheckBox.addItemListener(mapCheckBoxListener);
    mapCheckBoxes.add(mapCheckBox);
}

// [....]

private void setMapsEnabled(java.util.List<JCheckBox> mapCheckBoxes, boolean enabled) {
    for (JCheckBox mapCheckBox : mapCheckBoxes) {
        mapCheckBox.setEnabled(enabled);
    }
}