text:
Q: zxing ean13 barcode encoding with 'lead', 'separator' and 'trailer' I'm using zxing to generate an EAN13 barcode. Everything works fine when I use this code:
new EAN13Writer().encode(eanValue, BarcodeFormat.EAN_13, requestedWidth, requestedHeight);

Result:

Now, the customer wants to have a lead, separater and a trailer like this one:

(Image source)
As far as I understand the code of zxing (see here) I'm using above can't make those lines longer than others. But I've found out that there are two encode-methods in the EAN13Writer and it seems like, the second encode-function does exactly what I want to do. But the problem is that this function doesn't return a bitmatrix but a boolean array.  (Edit: Nope the function does not achieve what I want to do)
Can anybody tell me how I can achieve the second barcode style?

A: As I couldn't find a solution in the zxing code I wrote my own EAN13Writer. I had to copy paste some methods and constants as they were package-private in the zxing package.
Basically it just stores the position of the lines which shall be longer in a member variable. When the BitMatrix is rendered every line which should not be longer will be shortened by 5%. If anybody has the same problem this code might help a little bit.
/**
 * This is a custom implementation as the customer wants a modified barcode with longer and shorter lines for start, middle and end.
 * Most code is based on Code from the OneDimensionalCodeWriter, EAN13Writer and UPCEANReader but
 * had to be copied as the methods were package private
 *
 */
public class CustomEAN13Writer extends OneDimensionalCodeWriter {

// For an EAN-13 barcode, the first digit is represented by the parities used
// to encode the next six digits, according to the table below. For example,
// if the barcode is 5 123456 789012 then the value of the first digit is
// signified by using odd for '1', even for '2', even for '3', odd for '4',
// odd for '5', and even for '6'. See http://en.wikipedia.org/wiki/EAN-13
//
//                Parity of next 6 digits
//    Digit   0     1     2     3     4     5
//       0    Odd   Odd   Odd   Odd   Odd   Odd
//       1    Odd   Odd   Even  Odd   Even  Even
//       2    Odd   Odd   Even  Even  Odd   Even
//       3    Odd   Odd   Even  Even  Even  Odd
//       4    Odd   Even  Odd   Odd   Even  Even
//       5    Odd   Even  Even  Odd   Odd   Even
//       6    Odd   Even  Even  Even  Odd   Odd
//       7    Odd   Even  Odd   Even  Odd   Even
//       8    Odd   Even  Odd   Even  Even  Odd
//       9    Odd   Even  Even  Odd   Even  Odd
//
// Note that the encoding for '0' uses the same parity as a UPC barcode. Hence
// a UPC barcode can be converted to an EAN-13 barcode by prepending a 0.
//
// The encoding is represented by the following array, which is a bit pattern
// using Odd = 0 and Even = 1. For example, 5 is represented by:
//
//              Odd Even Even Odd Odd Even
// in binary:
//                0    1    1   0   0    1   == 0x19
//
static final int[] FIRST_DIGIT_ENCODINGS = {
        0x00, 0x0B, 0x0D, 0xE, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A
};

/**
 * Start/end guard pattern.
 */
static final int[] START_END_PATTERN = {1, 1, 1,};

/**
 * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
 */
static final int[][] L_AND_G_PATTERNS;

/**
 * "Odd", or "L" patterns used to encode UPC/EAN digits.
 */
static final int[][] L_PATTERNS = {
        {3, 2, 1, 1}, // 0
        {2, 2, 2, 1}, // 1
        {2, 1, 2, 2}, // 2
        {1, 4, 1, 1}, // 3
        {1, 1, 3, 2}, // 4
        {1, 2, 3, 1}, // 5
        {1, 1, 1, 4}, // 6
        {1, 3, 1, 2}, // 7
        {1, 2, 1, 3}, // 8
        {3, 1, 1, 2}  // 9
};

/**
 * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
 */
static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};

static {
    L_AND_G_PATTERNS = new int[20][];
    System.arraycopy(L_PATTERNS, 0, L_AND_G_PATTERNS, 0, 10);
    for (int i = 10; i < 20; i++) {
        int[] widths = L_PATTERNS[i - 10];
        int[] reversedWidths = new int[widths.length];
        for (int j = 0; j < widths.length; j++) {
            reversedWidths[j] = widths[widths.length - j - 1];
        }
        L_AND_G_PATTERNS[i] = reversedWidths;
    }
}

private static final int CODE_WIDTH = 3 + // start guard
        (7 * 6) + // left bars
        5 + // middle guard
        (7 * 6) + // right bars
        3; // end guard

private static final int DEFAULT_MARGIN = 10;

//This list should contain all positions of lines which should be longer than the other lines
private List<Integer> mLongLinePositions;

public CustomEAN13Writer() {
    mLongLinePositions = new ArrayList<>();
}

/**
 * @param target     encode black/white pattern into this array
 * @param pos        position to start encoding at in {@code target}
 * @param pattern    lengths of black/white runs to encode
 * @param startColor starting color - false for white, true for black
 * @return the number of elements added to target.
 */
public int appendPatternAndConsiderLongLinePosition(boolean[] target, int pos, int[] pattern,
        boolean startColor) {
    boolean color = startColor;
    int numAdded = 0;
    for (int len : pattern) {
        for (int j = 0; j < len; j++) {
            //If the pattern is the start-, middle- or end-pattern save the position for rendering later
            if (pattern.equals(START_END_PATTERN) || pattern.equals(MIDDLE_PATTERN) || pattern
                    .equals(START_END_PATTERN)) {
                mLongLinePositions.add(pos);
            }
            target[pos++] = color;
        }
        numAdded += len;
        color = !color; // flip color after each segment
    }
    return numAdded;
}

@Override
public boolean[] encode(final String contents) {
    if (contents.length() != 13) {
        throw new IllegalArgumentException(
                "Requested contents should be 13 digits long, but got " + contents.length());
    }
    try {
        if (!checkStandardUPCEANChecksum(contents)) {
            throw new IllegalArgumentException("Contents do not pass checksum");
        }
    } catch (FormatException ignored) {
        throw new IllegalArgumentException("Illegal contents");
    }

    int firstDigit = Integer.parseInt(contents.substring(0, 1));
    int parities = FIRST_DIGIT_ENCODINGS[firstDigit];
    boolean[] result = new boolean[CODE_WIDTH];
    int pos = 0;

    pos += appendPatternAndConsiderLongLinePosition(result, pos, START_END_PATTERN, true);

    // See {@link #EAN13Reader} for a description of how the first digit & left bars are encoded
    for (int i = 1; i <= 6; i++) {
        int digit = Integer.parseInt(contents.substring(i, i + 1));
        if ((parities >> (6 - i) & 1) == 1) {
            digit += 10;
        }
        pos += appendPatternAndConsiderLongLinePosition(result, pos, L_AND_G_PATTERNS[digit],
                false);
    }

    pos += appendPatternAndConsiderLongLinePosition(result, pos, MIDDLE_PATTERN, false);

    for (int i = 7; i <= 12; i++) {
        int digit = Integer.parseInt(contents.substring(i, i + 1));
        pos += appendPatternAndConsiderLongLinePosition(result, pos, L_PATTERNS[digit], true);
    }
    appendPatternAndConsiderLongLinePosition(result, pos, START_END_PATTERN, true);

    return result;
}

public BitMatrix encodeAndRender(String contents, int width, int height) {
    boolean[] code = encode(contents);

    int inputWidth = code.length;
    // Add quiet zone on both sides.
    int fullWidth = inputWidth + DEFAULT_MARGIN;
    int outputWidth = Math.max(width, fullWidth);
    int outputHeight = Math.max(1, height);

    int multiple = outputWidth / fullWidth;
    int leftPadding = (outputWidth - (inputWidth * multiple)) / 2;

    BitMatrix output = new BitMatrix(outputWidth, outputHeight);
    for (int inputX = 0, outputX = leftPadding; inputX < inputWidth;
            inputX++, outputX += multiple) {
        if (code[inputX]) {
            int barcodeHeight = outputHeight;
            //if the position isn't in the list for long lines we have to shorten the line by 5%
            if (!mLongLinePositions.contains(inputX)) {
                barcodeHeight = (int) ((float) outputHeight * 0.95f);
            }
            output.setRegion(outputX, 0, multiple, barcodeHeight);

        }
    }
    return output;
}

/**
 * Computes the UPC/EAN checksum on a string of digits, and reports whether the checksum is
 * correct or not.
 *
 * @param s string of digits to check
 * @return true iff string of digits passes the UPC/EAN checksum algorithm
 * @throws FormatException if the string does not contain only digits
 */
static boolean checkStandardUPCEANChecksum(CharSequence s) throws FormatException {
    int length = s.length();
    if (length == 0) {
        return false;
    }

    int sum = 0;
    for (int i = length - 2; i >= 0; i -= 2) {
        int digit = (int) s.charAt(i) - (int) '0';
        if (digit < 0 || digit > 9) {
            throw FormatException.getFormatInstance();
        }
        sum += digit;
    }
    sum *= 3;
    for (int i = length - 1; i >= 0; i -= 2) {
        int digit = (int) s.charAt(i) - (int) '0';
        if (digit < 0 || digit > 9) {
            throw FormatException.getFormatInstance();
        }
        sum += digit;
    }
    return sum % 10 == 0;
}
}

A: The second encode method returns an array of boolean that is a row of pixels. A true value is black, a false value is white. That array is extrapolated into your first image by: OneDimensionalCodeWriter::renderResult().
That method makes no provision for the human readable image. The separators are there in your first image, but they are not extended nor, obviously, is the human readable rendering of the number that is encoded.
My best advice is to fork the github repo and modify the renderResult method to do what you want. Obviously you need to provide something to your client, so I'd just do something quick in it's own branch. Ultimately the best thing is to do it correctly and offer the changes back to the zxing team.
I would assume that there should be a hint (EncodeHintType) added to allow a choice to make the barcode human readable. To save yourself time, I would post a message to their dev mailing list and see what they feel would be the best way to add this feature.


text:
Q: Reduccion en haskell Estoy tratando de reducir esta función, muchas gracias
 funcionPractica x f = \g -> h ( g x )

A: Por un lado, hay una equivalencia entre una función y una expresión lambda. Estas dos sentencias son equivalentes:
f = \x -> h

f x = h

Lo que nos daría la primera reducción:
func x f g = h ( g x )
       where h = \z -> f z

Por otro lado, la expresión lambda de la cláusula where no es otra cosa que la aplicación de la función f. Por tanto, podemos sustituir h por f:
func x f g = f ( g x )

O sea, se trata de la composición de dos funciones, f y g. Para que quede claro, mejor usar el operador composición:
func x f g = (f . g)  x

Ésta sería la solución más sencilla y que dejaría como final. Pero dependiendo de lo que consideres por simple, aún se podría simplificar más transformando esta función en una expresión pointfree, bastante más difícil de entender:
func = flip (.) . flip id

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where to store user data? I'm developing an Android application, and I want to restore user settings, when my application will be installed on another phone by the same user.
I don't want to use Dropbox or Google drive, because not all the users have account in these clouds. Id like to use something, that all Android users have.
Some cloud linked to google account? But I can't found any.
There should be pretty common solution but I haven't found any information about it.

A: For Android 6.0 and newer you can use auto backup. It backups the SharedPreferences and other data stored in your applicationsdirectory up to 25mb. Apps targeting Android 6.0 are automatically using auto backup. You can change this behaviour.
For older versions you can use key-value backup. This is perfect for preferences.


text:
Q: pl sql oracle subquery I have a procedure:
CREATE OR REPLACE PROCEDURE recommend_book(
  in_ID_user IN number
)
IS
  --zmienne
  zmienna1 number(9,0);
BEGIN
  SELECT COUNT(GENRE)
    INTO zmienna1
    FROM BOOKS
   WHERE ID_BOOK IN(SELECT ID_BOOK
                      FROM SIGNATURES
                     WHERE SIGNATURE IN (SELECT SIGNATURE
                                           FROM ORDERS
                                          WHERE ID_READER=in_ID_user)
                    );
END;
/

I'm getting the error

PL-00428: An INTO clause is expected in this SELECT statement

Could you please help me identify what's missing/what's wrong here?

A: For other developers when see this question, it should be an answer:
As Frank says:

Are you 100% sure that the error you're seeing isn't from a previous compilation attempt? Your procedure looks perfectly fine.

Just restart your compiler.


text:
Q: Unable to install Hyper-V-Hypervisor Update: I can't check any suggestions anymore as I dosn't have this installation anymore

I'm trying to install Hyper-V on my PC.
But I have a problem.
Every time I tried to install it I have the problem that on reboot Windows perfoms an update (looks like the normal Windows Update) but is unable to complete it and then it removes the changes.
I followed this guide step by step (except the fresh start) and ended on installing the components individually.
So my result:
I installed the services, the GUI and the PowerShell module. But when I install the Hypervisor it always happens the same (like I described above).
I already removed VMWare and never had anything else.
But in the past I alreaday had Hyper V once and it worked then.
Any idea why this doesn't work this time?
Thank you!
I have Windows 10 Pro x64.
And virtualization is enabled (and worked in the past).
Edit 1:
Here is the winver result:


text:
Q: Adding Dropout Layers to Segmentation_Models Resnet34 with Keras I want to use the Segmentation_Models UNet (with ResNet34 Backbone) for uncertainty estimation, so i want to add some Dropout Layers into the upsampling part. The Model is not Sequential, so i think i have to reconnect some outputs to the new Dropout Layers and the following layer inputs to the output of Dropout.
I'm not sure, whats the right way to do this. I'm currently trying this:
# create model
model = sm.Unet('resnet34', classes=1, activation='sigmoid', encoder_weights='imagenet')

# define optimizer, loss and metrics
optim = tf.keras.optimizers.Adam(0.001)
total_loss = sm.losses.binary_focal_dice_loss # or sm.losses.categorical_focal_dice_loss
metrics = ['accuracy', sm.metrics.IOUScore(threshold=0.5), sm.metrics.FScore(threshold=0.5)]

# get input layer
updated_model_layers = model.layers[0]

# iterate over old model and add Dropout after given Convolutions
for layer in model.layers[1:]:
    # take old layer and add to new Model
    updated_model_layers = layer(updated_model_layers.output)

    # after some convolutions, add Dropout
    if layer.name in ['decoder_stage0b_conv', 'decoder_stage0a_conv', 'decoder_stage1a_conv', 'decoder_stage1b_conv', 'decoder_stage2a_conv',
                          'decoder_stage2b_conv', 'decoder_stage3a_conv', 'decoder_stage3b_conv', 'decoder_stage4a_conv']:

        if (uncertain):
            # activate dropout in predictions
            next_layer = Dropout(0.1) (updated_model_layers, training=True)
        else:
            # add dropout layer
            next_layer = Dropout(0.1) (updated_model_layers)

        # add reconnected Droput Layer
        updated_model_layers = next_layer
model = Model(model.layers[0], updated_model_layers)

This throws the following Error: AttributeError: 'KerasTensor' object has no attribute 'output'
But I think I'm doing something wrong. Does anybody have a Solution for this?

A: There is a problem with the Resnet model you are using. It is complex and has Add and Concatenate layers (residual layers, I guess), which take as input a list of tensors from several "subnetworks". In other words, the network is not linear, so you can't walk through the model with a simple loop.
Regarding your error, in the loop of your code: layer is a layer and updated_model_layers is a tensor (functional API). Therefore, updated_model_layers.output does not exist. You confuse the two a bit


text:
Q: How to use pandas.DataFrame.mask for NaN I want to ignore NaN values in my selected dataframe columns when I want to normalize with sklearn.preprocessing.normalize. Column example:
0     12.0
1     12.0
2      3.0
3      NaN
4      3.0
5      3.0
6      NaN
7      NaN
8      3.0
9      3.0
10     3.0
11     4.0
12    10.0

A: You can make use of function dropna(). It will return the same dataframe with rows containing NaN deleted.
>>> a.dropna()
     0  12.0
0    1    12
1    2     3
3    4     3
4    5     3
7    8     3
8    9     3
9   10     3
10  11     4
11  12    10


text:
Q: Agrupar cadenas por fecha utilizando Pandas Python estoy trabajando en un programa, y necesito agrupar cadenas de texto que están generadas en una fecha determinada.
La forma de agrupación que quiero es agrupar una misma cadena todas las veces que se repita, siempre y cuando una próxima repetición ocurra en menos de 30 días. En el caso que después de 30 días vuelva a repetirse volver a contar (es un contéo móvil).
Hasta hora estoy leyendo desde un CSV y tengo las cadenas separadas y las fechas convertidas en date, de la siguiente forma:
    import pandas as pd
    import numpy as np
    import numpy
    import csv
    from numpy import genfromtxt
    import numpy as np
    from datetime import datetime, timedelta
    from time import time

    df = pd.read_csv('Export.csv', header=0, sep=';')

    FDE=[]

    FDE=df["#"] +"-"+df["Text"]                          #Crear lista
    df[" Date"] = pd.to_datetime(df[" Date"])            #Convertir fechas a date

    print(FDE)

FDE es la cadena que debo buscar, cada vez que FDE se repite y la fecha asociada al FDE repetido es menor a 30 días, se debe contar. En los casos que FDE sea mayor a 30 días se debe reiniciar el conteo. De esta forma quedan distintas historias para un tipo de FDE.
El archivo del cual estoy leyendo es el siguiente:
https://drive.google.com/file/d/0B11sJdX_AaJBVVpZZnNDT3o4XzQ/view?usp=sharing
Cualquier idea o ayuda se agradece.
Ejemplo de salida:
    CCB-HYD PUPRI R = 2
    CBH-G AIR = 2
    CBD-FD AIL = 2
    CBD-FFAIL = 2

Saludos!

A: Lo siguiente creo que hace lo que quieres. No he encontrado una funcionalidad mágica de pandas que permita hacerlo de forma más directa. Igual existe pero la desconozco:
import datetime as dt

import pandas as pd

# funciones de ayuda
dateparser = lambda d: dt.datetime.strptime(d, "%d-%m-%Y %H:%M")

def agrupa(data):
    groups = [1]
    delta = pd.Timedelta(days=30)
    for i in range(1,len(data)):
        d1 = data['FDE Date'].iloc[i]
        d0 = data['FDE Date'].iloc[i-1]
        print(i, d1, d0)
        if d1 - d0 > delta:
            groups.append(groups[-1] + 1)
        else:
            groups.append(groups[-1])
    return groups

# Leemos los datos y los organizamos como queremos
df = pd.read_csv("kk.csv",
                 header=0,
                 sep=';',
                 parse_dates=[6, 8, 21],
                 date_parser=dateparser)

df['FDE'] = df["Tail #"] +"-"+df["FDE Text"]

# Agrupamos por 'FDE'
groups = df.groupby('FDE')

# Bucle sobre los grupos y extraemos grupos de fechas con la fn agrupa
for group in groups:
    df_tmp = group[1].sort_values('FDE Date')
    group = group[0]
    df_tmp['grupos'] = agrupa(df_tmp)

    # Esto lo tendrás que retocar para extraer la info como consideres
    print("Grupos para ", group)
    print(df_tmp.groupby('grupos')['FDE Date'].count().values)

Por partes, dateparser es una función que permite leer el csv y transformar las columnas de fechas en fechas. agrupa se usa para crear grupos por fechas dentro de cada grupo (ver código). Leemos el fichero y creamos grupos usando groupby. Dentro de cada grupo iteramos sobre la columna FDE Date para crear una columna de grupos que determina si un evento se debe asociar a un grupo o a otro.


text:
Q: Check if a cookie exists on another domain I have actually set the following cookie for the following domain:
setcookie("thing", $data, time()+3600, "/", "example1.com", 1);

The cookie was set from this domain: example2.com
When I try to search for the cookie 'thing' I can't seem to find it. How is it possible to set a cookie on a domain, which will remain on another domain if I search for it?
UPDATE:
I basically want to pass a value from Domain A to Domain B. When a visitor arrives to Domain A he/she gets redirected AND pass a value to Domain B which I'd like to capture there.
How is it possible?

A: Every browser prevents it.
Cookies can not be shared between domains.
https://wikipedia.org/wiki/Same-Origin-Policy

A: I'm pretty sure it is impossible to create a cookie for another domain - this would be a pretty significant security hole.
See @scones' link.


text:
Q: Height of the list item should automatically increase with size of div inside it I have the following mark up:

 20

 name

css is:
.nearby{width: 85px;
   height: auto;
   float: left;
   margin-right: 10px;
   font-size: 26px;
   text-align: center;
   padding: 15px 0;
   border: 2px #c1c1c1 solid;
   background: #fafafa;
}
li{padding: .7em 15px;
   display: block;
}

Unfortunately, the div doesn't sit nicely in the middle as it is too tall. Anyway, the li item could also increase in height so that its padding is dependent on the div rather than the h1?

A: You will have to add the following for it to work:
li{overflow:hidden;}

When setting the parent of a floated element to overflow:hidden; you force it to wrap the entire floated content. This is a very useful technique and it is used alot.

A: set float:left  for ul and li both i always have this problem try it


text:
Q: Laravel eloquent orderByRaw error with two withCount() value -Likes table migration:
public function up()
  {
      Schema::create('likes', function (Blueprint $table) {
          $table->id();
          $table->bigInteger('user_id')->unsigned();
          $table->boolean('direction');
          $table->morphs('likeable');
          $table->timestamps();
      });
      Schema::table('likes', function ($table) {
          $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
      });
  }

Like model:
    public function likeable()
    {
        return $this->morphTo();
    }

In Entry model:
    public function likes(): morphMany
    {
        return $this->morphMany(Like::class, 'likeable')->where('direction', true);
    }

    public function dislikes(): morphMany
    {
        return $this->morphMany(Like::class, 'likeable')->where('direction', false);
    }

    public function likesAndDislikes(): morphMany
    {
        return $this->morphMany(Like::class, 'likeable');
    }

I run this query:
Entry::withCount(['likes', 'dislikes'])
        ->orderByRaw('(likes_count + (dislikes_count * -1)) desc')
        ->paginate();

I got error:

quote
Illuminate\Database\ QueryException
PHP 8.1.3
9.45.1
SQLSTATE[42703]: Undefined column: 7 ERROR: column "likes_count" does not exist LINE 1: ... $4) as "dislikes_count" from "entries" order by (likes_coun... ^
SELECT
"entries".,
(
SELECT
count()
FROM
"likes"
WHERE
"entries"."id" = "likes"."likeable_id"
AND "likes"."likeable_type" = entries
AND "direction" = 1
) AS "likes_count",
(
SELECT
count(*)
FROM
"likes"
WHERE
"entries"."id" = "likes"."likeable_id"
AND "likes"."likeable_type" = entries
AND "direction" = 0
) AS "dislikes_count"
FROM
"entries"
ORDER BY
(likes_count + (dislikes_count * -1)) DESC
limit
15 OFFSET 0


text:
Q: How Background task access Main app JSON file I have created background task in similar fashion as mentioned in below link:
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj991805.aspx
Live tile is working fine with above code.
Problem :
In above link. we are extracting feed from MSDN Blog but in my application, I want to access JSON file defined in my app. So overall, I want my background task to access my main app JSON file.
Can you please guide me how background task can access main app JSON file?


text:
Q: Working regex fails when using Scala pattern matching In a following code the same pattern matches when Java API is used, but not when using Scala pattern matching.
import java.util.regex.Pattern

object Main extends App {
  val text = "/oAuth.html?state=abcde&code=hfjksdhfrufhjjfkdjfkds"

  val statePatternString = """\/.*\?.*state=([^&\?]*)"""
  val statePattern = statePatternString.r
  val statePatternJ = Pattern.compile(statePatternString)

  val sj = statePatternJ.matcher(text)
  val sjMatch = if (sj.find()) sj.group(1) else ""
  println(s"Java match $sjMatch")

  val ss = statePattern.unapplySeq(text)
  println(s"Scala unapplySeq $ss")
  val sm = statePattern.findFirstIn(text)
  println(s"Scala findFirstIn $sm")

  text match {
    case statePattern(s) =>
      println(s"Scala matching $s")
    case _ =>
      println("Scala not matching")
  }

}

The app output is:

Java match abcde
Scala unapplySeq None
Scala findFirstIn Some(/oAuth.html?state=abcde)
Scala not matching

When using the extractor syntax val statePattern(se) = text the error is scala.MatchError.
What is causing the Scala regex unapplySeq to fail?

A: When you define a Scala pattern, it is anchored by default (=requires a full string match), while your Java sj.find() is looking for a match anywhere inside the string. Add .unanchored for the Scala regex to also allow partial matches:
val statePattern = statePatternString.r.unanchored
                                       ^^^^^^^^^^^

See IDEONE demo
Some UnanchoredRegex reference:

def unanchored: UnanchoredRegex
Create a new Regex with the same pattern, but no requirement that the entire String matches in extractor patterns.
Normally, matching on date behaves as though the pattern were enclosed in anchors, ^pattern$.
The unanchored Regex behaves as though those anchors were removed.
Note that this method does not actually strip any matchers from the pattern.

AN ALTERNATIVE SOLUTION would mean adding the .* at the pattern end, but remember that a dot does not match a newline by default.  If a solution should be generic, the (?s) DOTALL modifier should be specified at the beginning of the pattern to make sure the whole string with potential newline sequences is matched.


text:
Q: Resize photos as thumbnail squares like Flickr and Facebook photostreams? What is the best way to resize photos and create square, same-sized thumbnail pictures for photostreams?  Flickr and Facebook do this, and we would like to emulate this functionality.
Here's an example: http://www.flickr.com/photos/alphageek/233472093/
If you view the photostream on the right hand side (mid page), all the thumbnails are the same size even though the original images vary in size, and most importantly, the thumbnails appear intelligently cropped.
Flickr is able to automatically crop and resize image around the main focus, as opposed to simply resizing the image to thumbnail size (e.g., by setting the image width and height), which would cause the image to look squished and lose the focus of the image.

A: they are doing a resized crop.
if you are using imagemagick to convert it would be the # option like "40x40#" or "90x90#" where the photo will be resized then cropped to maintain aspect ratio while getting as much as possible in the thumbnail.
programmatically it probably goes like this:
1) resize image so that the short side is as specified.
2) crop for the middle so the long side is now also as specified.

A: Yes.  First you need to get a new size keeping aspect ratio intact:
CGFloat horizontalRatio = newSize.width/oldSize.width;
CGFloat verticalRatio = newSize.height/oldSize.height;
CGFloat ratio = MAX(horizontalRatio, verticalRatio);
CGSize newSize = CGSizeMake(oldSize.width *ratio, newSize.height*ratio)

Then you need to redraw your image in the new size (self is your image):
UIGraphicsBeginImageContextWithOptions(newSize, YES, 0);
    [self drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

Then crop to desired size :
        CGRect cropRect = CGRectMake ((newImage.size.width - width) / 2, (newImage.size.height - height) / 2, width, height)
        UIGraphicsBeginImageContextWithOptions(cropRect.size, YES, 0);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGRect drawRect = CGRectMake(-cropRect.origin.x, -cropRect.origin.y, self.size.width, self.size.height);
        CGContextClipToRect(context, CGRectMake(0, 0, cropRect.size.width, cropRect.size.height));
        [self drawInRect:drawRect];
        UIImage* croppedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
return croppedImage;

A: For such problems, i always use: http://www.imagemagick.org/script/convert.php.
Imagemagick provides a lot of functions for manipulations images.
I take images in a loop and create a large version and a thumbnail-version.


text:
Q: Haskell: converting a list of (a, b) key-value pairs (with possibly repeated keys) to a list of (a, [b]) grouped by key I'm a Haskell beginner.  Let's suppose I want to write a function convertKVList that takes a flat list of key-value pairs, where some of the keys might be repeated, and turns it into a mapping from keys to lists of values where all of the keys are unique.  For instance, on a list of pairs of Ints, I want this behavior:
> convertKVList [(1, 2), (1, 4), (1, 3), (2, 3)]
[(1,[3,4,2]),(2,[3])]

This seems like a common enough task that there ought to be a library function available to do what I want, but I couldn't find anything when I looked.  Finally, someone suggested that I compose Map.toList with Map.fromListWith (++), and I ended up with this:
import Data.Map as Map (toList, fromListWith)

convertKVList :: (Ord a) => [(a, b)] -> [(a, [b])]
convertKVList ls =
  (Map.toList . Map.fromListWith (++) . map (\(x,y) -> (x,[y]))) ls

My question is for more experienced Haskellers and is in two parts: First, is this how you would  go about it, or is there a "better" (easier to read, or more efficient, or both) way?
Second, how could I have come up with this on my own?  I knew that I wanted the type to be [(a, b)] -> [(a, [b])], but putting that into Hoogle didn't turn up anything useful.  And I had looked at the Data.Map docs, but neither fromListWith nor toList had jumped out as particularly helpful.  So: how would you go about thinking about this problem?  (I realize that both of these questions are subjective, especially the second one.)
Thanks!

A: One of the most important points when writing a function, is trying to split what it should do into separate sub-tasks (which are often put together by function composition in the end). E.g., in the definition you came up with, there are three tasks (in order of application, i.e., from right to left in the definition):

*

*map the 2nd component of each pair to a singleton list (thereby enabling the use of Map.fromListWith)

*create a map (which takes care of merging entries with equal keys)

*turn it into a list

I wanted to post a different solution (which was an exact copy of the code Mark posted in the meanwhile ;)). Just to make clear that most of the time there are different routes to the same goal. In his definition you have the separate tasks:

*

*sort the list by keys

*group the result by keys

*turn it into a list of the desired type

Once again, separation of concerns (modularity) is an important principle. Just try to apply it to small problems and once you gained some experience you will be able to come up with surprisingly simple solutions to seemingly difficult problems.

A: while this is by no means canonical:
import Data.List
import Data.Ord
import Data.Function (on)

convertKVList :: Ord a => [(a,b)] -> [(a,[b])]
convertKVList = map (\x -> (fst $ head x,  map snd x)) . groupBy ((==) `on` fst) . sortBy (comparing fst)

it does have the advantage of not pulling in Data.Map. should be asymptotically the same, haven't benchmarked. I think you could clean up the first chunk with Control.Arrow (something like (fst . head &&& map snd)) but it's not obviously cleaner.
Not sure how you'd come to it except by either knowing it or asking in #haskell, though.

A: Hoogle is not the only search engine able to search Haskell libraries by type signatures and it definitely and unfortunately covers only a small part of Hackage. Searching with Hayoo for a type signature [(a,b)]->[(a,[b])] brought up these two implementations:

*

*aggregateAL

*alistCollect
Concerning your take on the problem, since in your function you already bring up a higher level datastructure (Map), it doesn't make sense to downgrade to a more primitive associative list in the output, because:

*

*Most of the algorithms you can possibly utilize such data in will only benefit from getting a Map input, because it's much more effective for dealing with key-value stores, and if you ever find yourself still needing a list you can always utilize the toList in place.

*Map implies the absence of duplicate keys on type level, which is not any less important, since in Haskell you should always do the maximum proofs using the type-system. This principle is essentially what makes the statement "If it compiles, it works" closest to truth.

In other words this is the correct definition of your function:
convertKVList :: (Ord a) => [(a, b)] -> Map a [b]
convertKVList ls =
  Map.fromListWith (++) . map (\(x,y) -> (x,[y])) $ ls

Hayooing for that type signature brings a couple of already implemented results too.
Concerning the approaching the problem, it's classic: "Divide and conquer!". Chris has some good points too in his answer.

A: That looks like an understandable solution and you can clean it up slightly more:

import Data.Map (toList, fromListWith)
import Control.Arrow (second)

convertKVList :: Ord a => [(a, b)] -> [(a, [b])]
convertKVList = toList . fromListWith (++) . map (second (:[]))

Regarding how you might come up with this on your own: assuming you started with Data.Map, then you want to use the map to combine values with equal keys. The documentation for Data.Map on Hackage says a is the type for values and k for keys.
Knowing this, you can search for a -> a -> a to find functions that might combine two values in a Map k a to produce a new a value. This narrows the API down to a handful of functions like insertWith, fromListWith, and fromAscListWith.
Similarly, to convert your Map k a to [(k, a)], you can search the documentation for Map k a -> [(k, a)] and find only a few functions like assocs, toList, toAscList, and toDescList. Note that in your case, [(k, a)] is instantiated to [(Int, [Int])].
One thing I've found helpful in understanding the standard Haskell libraries is to view the source on Hackage. Seeing which functions are implemented in terms of others helps make the API feel smaller, and I can see which functions are the basic building blocks.

A: I suspect that without dipping into mutation and the ST monad, you are unlikely to improve on the Map.fromListWith solution (or substantially equivalent alternatives like using HashMap.fromListWith).  I'd just go with that.
Basically, with mutation you can do this grouping in near-linear time by using a mutable hash table with a as the keys and mutable lists of b as the values.  Without mutation, however, it's going to be worse, because each insert into a balanced search tree is O(log n); this is because "inserting" means constructing a new copy of each tree node that leads to the one your inserted element goes in.  And you need to do n inserts—which gives you exactly the O(n * log n) bounds that the Map.fromListWith function has.  Sorting the association list ahead of time doesn't fundamentally improve this, because sorting is also O(n * log n).
So to improve on O(n * log n), you need data structures with mutation.  I just did a quick Google and the best bet would be to implement the standard imperative algorithm using something like the hashtables library (which I've never tried, so I can't vouch for it).  To use this you're going to need to understand Control.Monad.ST and Data.STRef.  The ST monad is a technique that GHC provides for using mutation "internally" in a pure function—it uses some type system extensions to guarantee that the side effects cannot be observed outside of the functions in question.  HaskellWiki has some examples, but it might take some studying and practice to feel comfortable with this one.
The other thing I would recommend, if you feel like you want to understand Data.Map or similar libraries better, is to look at Chris Okasaki's Purely Functional Data Structures book (or his dissertation (PDF) that the book is based on).  It's based on Standard ML instead of Haskell, the data structures are not the same, and it can be a bit of a difficult read, but it's a foundational book.

A: So, my solution overuses pattern-matching because I don't actually know what functions are in the standard library.
The idea was that if the list is sorted by the keys, then you can collect your key-values as you go. To do the logic of checking whether to add to the first key-value list or create a new entry, I used patterns and guards to define the conditionals. And liberal use of cons to prepend values to a list.
And in case the original list isn't sorted, there's a sortBy.
import Data.List
import Data.Ord

ls = [(2, 1), (1, 2), (1, 4), (1, 3), (2, 3)]

addval [] (k, v)= [(k, [v])]
addval ((k1, vals) : xs) (k2, v) | k1 == k2
  = ((k1, (v : vals)) : xs)
addval ls (k, v) = ((k, [v]) : ls)

convert ls = foldl addval [] (sortBy (comparing fst) ls)

Ugly code, but it avoids using Map.


text:
Q: Make gestureState return values in steps (grid-like behavior) I'm using 'react-native-draggable' to create a floorplan builder and I'm in the process of modifying the package to suite our needs as this package does not support grid-stepped behavior.
By default,
const {dx, dy} = gestureState;

dx / dy will always have 0 as starting point regardless of any object's position on the screen — It measures the distance your finger has moved on the x and y from the moment you started draggin an object.
To make the object move in steps, I had the idea of trying to reset the gestureState to 0 if dx or dy is above 20px / below -20px to simulate a grid of 20x20 grid slots. But it seems the values returned by gestureState are constant (which makes sense) so once you start moving, it keeps on measuring until you release.
Any idea of how I would go about solving this?
  const handleOnDrag = React.useCallback(
    (e, gestureState) => {
      const {dx, dy} = gestureState; // always returns a value from 0
      const {top, right, left, bottom} = startBounds.current;
      const far = 999999999;

      const changeX = clamp(
        dx, // New value it will animate object to (!!)
        Number.isFinite(minX) ? minX - left : -far, // checks if any boundaries are set on X
        Number.isFinite(maxX) ? maxX - right : far, // checks if any boundaries are set on X
      );
      const changeY = clamp(
        dy, // New value it will animate object to (!!)
        Number.isFinite(minY) ? minY - top : -far, // checks if any boundaries are set on Y
        Number.isFinite(maxY) ? maxY - bottom : far, // checks if any boundaries are set on Y
      );

        // Animate object
        pan.current.setValue({x: changeX, y: changeY});

        onDrag(e, gestureState);
    },
    [maxX, maxY, minX, minY, onDrag],
  );

Any help would be much appreciated!

A: I solved it by using Math.round() to round to nearest 50 (or any decimal-number depending on grid size)
Math.round(dx/50) * 50

and
Math.round(dx/50) * 50


text:
Q: Why does the exponent of $\text{Gal}(F_i/F_{i-1})$ divide the exponent of $\text{Gal}(K_i/K_{i-1})$ ? We have the chain of intermediate fields $$F=K_0\leq K_1 \leq \ldots \leq K_r=K$$
Let $\omega$ be the $n$th primitive root of $1$.
We consider the chain $$F\leq F(\omega)\leq F_1\leq \ldots \leq F_r=K(\omega)$$ with $F_i=K_i(\omega)$.
We have that $F_i=F_{i-1}K_i$ and $\text{Gal}(F_i/F_{i-1})\hookrightarrow \text{Gal}(K_i/K_{i-1})$.
Why does it hold that the exponent of $\text{Gal}(F_i/F_{i-1})$ divides the exponent of $\text{Gal}(K_i/K_{i-1})$ ?

A: This has nothing to do with the specific structure of these groups - by the definition of "exponent" (for example, as the least common multiple of the orders of every element in the group), if $ H \subset G $ are finite groups, then the exponent of $ H $ always divides the exponent of $ G $...


text:
Q: jquery nav menu not marking current page when click on sub menu here is my jsfiddle: http://jsfiddle.net/HhBEJ/3/
Despite some of the code not looking good in jsfiddle because i have background images and such - I am having a problem with my nav menu.
What I want it to do is:
When I load the page(index.htm) I want it to have a page marker ( which i have named current) to mark that I'm currently on the home page.  When I click on another page to navigate to - I want it to remove current from prev page and make curPage the new current (you can see I did this in jquery (i think i did it right)) and if i click on a sub menu.  for instance i go to  "web > web215 > JavaScript" when I click on javaScript I want the Web parent Web215 child AND the javaScript grandchild to highlight all with the 'current' id. but it's not doing it to any of them except for a quick second when i click - it's not saving it when the page loads.  I think the culprit is somewhere in here:
function youAreHere() {
var pathName = $(location).attr('pathname');
var curPage = pathName.substring(pathName.lastIndexOf('/') + 1);
$('a').each(function () {
    if ($(this).attr('href') == curPage) {
        $(this).attr('id', 'current');
    } else if (curPage == '') {
        $('a:first').attr('id', 'current');
    }
}); //END function

I know when i put an alert it's calling the page correctly and it's working as intended but the current class isn't either A: staying after it loads or B: loading up at all.

A: your css is wrong, you are setting the id of current to the a tag but in the css you are setting the id of current to the li tag. This is what you need:
div#menu li a#current {
 font-weight: bold;
 font-size: 16px;
 z-index: 6;
 background: transparent url('../images/menu_level1_item.png') repeat-x scroll 0pt 100%;
}
div#menu li a#current ul {
 font-weight: normal;
 font-size: 12px;
}


text:
Q: Homeomorphism between N-disk and N-Projective Plane I've just showed that:
$D^n$, quotiented with this equivalence relation:
$x\sim y \iff x=-y \text{ and } x,y\in\partial D^n$
(i.e. the antipodal points on the boundary of $D^n$ are identified)
is homeomorphic to $RP^n$.
for $n=3$
Just for curiosity, could be that extended for every $n$ ?
thank you so much in Advance for any hints !!

A: yes.
First of all, it is easy to see that $\mathbb{R}P^n$ is homeomorphic to $S^n/\langle x\sim -x\rangle$ (pretty standard exercise you can find anywhere).
Now it remains to be proved that $$S^n/\langle x\sim -x\rangle \cong D^n/\sim' $$ (The quotient you mention.
Take the map which sends $[x] \in S^n$ to $x$ where $x$ is the representative of the class $[x]$ which lies in the upper hemisphere. You possibly have only problem if $[x]$ is such that $x$ (and so $-x$) lies on the equator. You don't have a canonical choice for them, but in the target space you claim that both choice are the same point, therefore any choice works fine and therefore you are done. Continuity is clear and bicontinuity as well.


text:
Q: Find word in string php and create an action within PHP script causes syntax error I found an old PHP whois script which I am going to use on my personal page. The script is working, however I want it to show a link to an external WHOIS (for more details). I did a search on Google and on Stackoverflow and found the following information:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
   echo 'true';
}

I modified and corrected it (thanks joshua miller) to
if((strpos($url, 'com') !== false) || (strpos($url, 'net') !== false)) {
    echo '
Whois in detail
';
}

So if the result of $url containes a .com or .net domain it will show the link, right? Sidenote: $url is already defined elsewhere, so it's an example here to get the ide.
Anyways, now for the issue. I pasted the above text into the current code, but it gives me a syntax error. I am doing something wrong here, but I have no clue what I am doing wrong here.
            if(isset($updation_date) && $updation_date != "" || isset($creation_date) && $creation_date != "" || isset($expiration_date) && $expiration_date != "")
            {
                $important_dates = '

'.$_SESSION['IMPORTANT DATES'].'

';
                    if(isset($updation_date) && $updation_date != "")
                    {
                    $important_dates .= '

                            '.$_SESSION['Updated'].':

                                '.$updation_date.'
                                ('.domainAge($updation_date).')

';
                    }
                    if(isset($creation_date) && $creation_date != "")
                    {
                    $important_dates .= '

                            '.$_SESSION['Created'].':

                                '.$creation_date.'
                                ('.domainAge($creation_date).')

';
                    }
                    if(isset($expiration_date) && $expiration_date != "")
                    {
                    $important_dates .= ''.$_SESSION['Expires'].':

                                '.$expiration_date.'
                                ('.domainAge($expiration_date).')

';
                    }
                    $important_dates .= '

';
            }
            $array[0] = '

 '.$url.'

                'if((strpos($url, 'com') !== false) || (strpos($url, 'net') !== false)) {
                     echo '
Whois in detail
';
       }'

                '.$list_server.''.$registrar_info.''.$important_dates;
                $array[1] = $raw_registrar_data;
        }

The line I added is located near the end (line #54) as you can see.
Now can someone be so kind to tell me what I am doing wrong here? The error I am getting is a Syntax error at the line with:
'if((strpos($url, 'com') !== false) || (strpos($url, 'net') !== false)) {

...but probably the rest of it is also wrong.
Thank you in advance for your help and advice with this. Probably it's something small, but if you do not know PHP or coding in general, than it can be really hard to figure something out.
Updated with the code joshua miller kindly provided as I used strpos incorrectly in this example. However I am still getting the same syntax error.
Update #2
Apparently the syntax error is because I used an "if"-stament in there, it gives me the following error, when I look it up with a syntax validator: PHP Syntax Check: Parse error: syntax error, unexpected 'if' (T_IF) in your code on line 222 (in the code I paste here it's #54).

A: UPDATE: Based on the full code provided, I think the following might help:
    $array[0] = '

 '.$url.'

';

    if((strpos($url, 'com') !== false) || (strpos($url, 'net') !== false)) {
        $array[0] .= '
Whois in detail
';
    }

    $array[0] .= $list_server.''.$registrar_info.''.$important_dates;

Original Answer
I don't think you can add multiple needles (the term you are searching for) like that in the function. Try this instead:
if((strpos($url, 'com') !== false) || (strpos($url, 'net') !== false)) {
  echo '
Whois in detail
';
}

A: if(strpos($url, 'com', 'net')!== false) {

is wrong because it supposes three parameters
use instead
if((strpos($url,'com')!== false)||(strpos($url,'com')!== false)) {

A: that's not how strpos() works
http://php.net/strpos
you can search for 1 needle in your string, not multiple.
For that you might want to have a look at preg_match
You can also make it search for "ends in .com" rather than "has com in it somewhere"
if(preg_match('#\.(net|com)$#', $url)) {

}

A: When using strpos() the syntax is strpos($haystack, $needle) so having two strings like you do: ('com', 'net') is invalid syntax.
You may want to split it into two function calls like so:

if(strpos($url, 'com') !== false || strpos($url, 'net') !== false) {}

A: strpos only takes 3 parameters:

*

*whatever you want it to look into,

*the string it should look for, and

*the optional offset it should begin at.


text:
Q: How do I choose a linkage method for Hierarchical Agglomerative Clustering? I understand that HAC has several options in terms of linkage functions. You have:

*

*Single linkage which produces "straggly" clusters

*Complete linkage which produces tight, spherical clusters

*Average linkage which is sort of a compromise between the two

*Ward's method, which is based more off the variance than actual distance

What I'm trying to figure out is, how do I know which one of these I want to use? Are there certain datasets where "straggly" clusters are preferable to spherical ones? Or is it more a function of what I intend to do with the clustering data?

A: It depends on your data.
Single-linkage works reasonably well on clean data.
If you have dirty data, the other linkages may be better.
Ward is similar to k-means. It may be a good choice if you want to talk about centroids and data partitioned completely into disjoint subsets.
The other problem is that only SLINK (for single-linkabe) is fast. All the others usually work in O(n^3) so they are not usable on large data sets. Compare this to e.g. DBSCAN which runs in O(n log n) if done well, or kmeans in O(n)...


text:
Q: IPC mechanisms concepts I want to understand these IPC mechanism concepts in OS - Shared Memory, Message System, Sockets, RPC, RMI
How do different operating systems implement these. Specifically Android operating system?

A: IPC is inter-process communication mechanisms in OS is large discussion concept so, I think here we can't cover all this,
Some Low Level stuff:
The IPC mechanism discussed here is at the lowest level—all other inter-CPU IPC mechanisms use it as the base. For example, a TCP/IP connection through the ARM11 processor to another processor ends up going through this IPC mechanism. Diagnostic messages are another example of messages that rely on this low-level IPC.
The IPC mechanism is implemented with two sides—a "client side," which faces the kernel and provides a callback-based style of interface, and a "CPU side," which provides the interface to the other CPUs.

*

*The CPU side is implemented as a shared-memory interface, with
interrupts and a "doorbell" mechanism. At the highest level, to send
messages from the ARM11 to another CPU, the message content is placed
in a buffer in shared memory and a hardware port is tickled to
indicate to the other CPU that data is available.

*In the reverse direction, the data is placed into shared memory by
the other CPU and a hardware interrupt is triggered on the ARM11.
This hardware interrupt causes the ARM11 to examine the shared
memory's buffer, retrieve the message and route it to the client.
But to more specific to Android:
IPC in android, It describes the mechanism how different types of android components are communicated.
Android implements a few key tools used to communicate with or coordinate between programs securely. These mechanisms give Android applications the ability to run processes in the background, offer services consumed by other applications, safely share relational data, start other programs, and reuse components from other applications safely.

*

*Much of the interprocess communication (IPC) that occurs on Android
is done through the passing around of a data structures called
Intents. These are collections of information that have a few
expected properties the system can use to help figure out where to
send an Intent if the developer wasn't explicit. The Action property
expresses what the Intent is for (the Intent.ACTION_VIEW action
indicates that the data is to be displayed to the user, for example).
The data property is an optional URI and could point to a file,
contact, web page, phone number, and so on. Intents also potentially
have a collection of key/value pairs called extras, as well as flags,
components, and other more advanced features.

*Each of these IPC mechanisms uses Intents in some capacity and is
probably somewhat familiar to most Android developers. However,
because using these safely is key to Android security,
1) Intents are messages which components can send and receive. It is a universal mechanism of passing data between processes. With help of the intents one can start services or activities, invoke broadcast receivers and so on.
2) Bundles are entities the data is passed through. It is similar to the serialization of an object, but much faster on android. Bundle can be got from intent via the getExtras() method.
3) Binders are the entity which allows activities and services obtain a reference to another services. It allows not simply send messages to services but directly invoke methods on them.
For more info look at:

*

*Grasping Android's IPC mechanism

*Android's Securable IPC Mechanisms


text:
Q: HTML DOM manipulation in Laravel 4 In my app I'm using Laravel 4.1 and I would like to do a more complex modification of html string that was passed by WYSIWYG texarea in html form. I used to work with Symfony 2, where I can do this efficiently with packages like https://github.com/wasinger/htmlpagedom. Is there something similar in Laravel? How could I make wasinger/htmlpagedom package working in Laravel?

A: No big deal, I've just added package to composer.json and than I used it in \Wa72\HtmlPageDom\HtmlPageCrawler namespace.


text:
Q: Having a problem with Google Maps Flutter on real Android device I created stateful widget that is used throughout the app to display a map with markers. I need to show a map on a screen in order to give users a better experience. I'm only writing this because SO says that I have too much code in this question.
The map displays fine on the iOS emulator. Haven't checked on a real iOS device yet.
I'm using google_maps_flutter: ^2.2.1
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class GoogleMapWidget extends StatefulWidget {
  final double lat;
  final double lng;
  final String name;
  final String id;
  const GoogleMapWidget({
    Key? key,
    required this.lat,
    required this.lng,
    required this.name,
    required this.id,
  }) : super(key: key);
  @override
  State<GoogleMapWidget> createState() => _GoogleMapWidgetState();
}

class _GoogleMapWidgetState extends State<GoogleMapWidget> {
  final Completer<GoogleMapController> mapController = Completer();
  List<Marker> markers = <Marker>[];

  @override
  Widget build(BuildContext context) {
    markers.add(
      Marker(
        markerId: MarkerId(widget.id),
        position: LatLng(widget.lat, widget.lng),
        infoWindow: InfoWindow(title: widget.name),
      ),
    );
    return SizedBox(
      width: 350.0,
      height: 400.0,
      child: GoogleMap(
        initialCameraPosition: CameraPosition(
          target: LatLng(widget.lat, widget.lng),
          zoom: 15.0,
        ),
        mapType: MapType.normal,
        markers: Set<Marker>.of(markers),
        onMapCreated: (GoogleMapController controller) {
          mapController.complete(controller);
        },
      ),
    );
  }
}

The widget is used like this:
   GoogleMapWidget(
     name: name,
     id: 'single_screen',
     lat: lat,
     lng: lng,
   ),

I connected a Samsung S10 to the computer and did flutter run
When entering the screen that uses the map widget I get this:
D/OpenGLRenderer( 4700): eglCreateWindowSurface
E/FrameEvents( 4700): updateAcquireFence: Did not find frame.

And when exiting:
V/GoogleMapController( 4700): Controller was disposed before GoogleMap was ready.
E/PlatformViewsController( 4700): Disposing platform view threw an exception
E/PlatformViewsController( 4700): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.LinkedList.isEmpty()' on a null object reference
E/PlatformViewsController( 4700):       at com.google.android.gms.dynamic.DeferredLifecycleHelper.zae(com.google.android.gms:play-services-base@@18.0.1:1)
E/PlatformViewsController( 4700):       at com.google.android.gms.dynamic.DeferredLifecycleHelper.onDestroy(com.google.android.gms:play-services-base@@18.0.1:2)
E/PlatformViewsController( 4700):       at com.google.android.gms.maps.MapView.onDestroy(com.google.android.gms:play-services-maps@@18.0.0:1)
E/PlatformViewsController( 4700):       at io.flutter.plugins.googlemaps.GoogleMapController.destroyMapViewIfNecessary(GoogleMapController.java:891)
E/PlatformViewsController( 4700):       at io.flutter.plugins.googlemaps.GoogleMapController.dispose(GoogleMapController.java:578)
E/PlatformViewsController( 4700):       at io.flutter.plugin.platform.PlatformViewsController$1.dispose(PlatformViewsController.java:376)
E/PlatformViewsController( 4700):       at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.dispose(PlatformViewsChannel.java:135)
E/PlatformViewsController( 4700):       at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.onMethodCall(PlatformViewsChannel.java:63)
E/PlatformViewsController( 4700):       at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262)
E/PlatformViewsController( 4700):       at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
E/PlatformViewsController( 4700):       at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$io-flutter-embedding-engine-dart-DartMessenger(DartMessenger.java:319)
E/PlatformViewsController( 4700):       at io.flutter.embedding.engine.dart.DartMessenger$$ExternalSyntheticLambda0.run(Unknown Source:12)
E/PlatformViewsController( 4700):       at android.os.Handler.handleCallback(Handler.java:938)
E/PlatformViewsController( 4700):       at android.os.Handler.dispatchMessage(Handler.java:99)
E/PlatformViewsController( 4700):       at android.os.Looper.loopOnce(Looper.java:226)
E/PlatformViewsController( 4700):       at android.os.Looper.loop(Looper.java:313)
E/PlatformViewsController( 4700):       at android.app.ActivityThread.main(ActivityThread.java:8663)
E/PlatformViewsController( 4700):       at java.lang.reflect.Method.invoke(Native Method)
E/PlatformViewsController( 4700):       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
E/PlatformViewsController( 4700):       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
D/OpenGLRenderer( 4700): setSurface called with nullptr
D/OpenGLRenderer( 4700): setSurface() destroyed EGLSurface
D/OpenGLRenderer( 4700): destroyEglSurface

[✓] Flutter (Channel stable, 3.3.4, on macOS 12.6 21G115 darwin-x64, locale en-EN)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
[✓] Chrome - develop for the web
[!] Android Studio (not installed)
[✓] VS Code (version 1.72.0)
[✓] Connected device (4 available)
[✓] HTTP Host Availability


text:
Q: Is there a difference between arrow functions and regular functions for middleware functions in Express app? I see so often people use regular functions for their middleware functions in the Express servers. Is there a reason for no arrow functions?
Is it because of hoisting reasons, because I've seen other posts on this but they don't break the middleware out to its own function
Tired both of them, and saw no issue really


text:
Q: Can't go on to the next page using post request I've written a script in python to get different links leading to different articles from a webpage. Upon running my script I can get them flawlessly. However, the problem I'm facing is that the article links traverse multiple pages as they are of big numbers to fit within a single page. if I click on the next page button, the attached information i can see in the developer tools which in reality produce an ajax call through post request. As there are no links attached to that next page button, I can't find any way to go on to the next page and parse links from there. I've tried with a post request with that formdata but it doesn't seem to work. Where am I going wrong?
Link to the landing page containing articles
This is the information I get using chrome dev tools when I click on the next page button:
GENERAL
=======================================================
Request URL: https://www.ncbi.nlm.nih.gov/pubmed/
Request Method: POST
Status Code: 200 OK
Remote Address: 130.14.29.110:443
Referrer Policy: origin-when-cross-origin

RESPONSE HEADERS
=======================================================
Cache-Control: private
Connection: Keep-Alive
Content-Encoding: gzip
Content-Security-Policy: upgrade-insecure-requests
Content-Type: text/html; charset=UTF-8
Date: Fri, 29 Jun 2018 10:27:42 GMT
Keep-Alive: timeout=1, max=9
NCBI-PHID: 396E3400B36089610000000000C6005E.m_12.03.m_8
NCBI-SID: CE8C479DB3510951_0083SID
Referrer-Policy: origin-when-cross-origin
Server: Apache
Set-Cookie: ncbi_sid=CE8C479DB3510951_0083SID; domain=.nih.gov; path=/; expires=Sat, 29 Jun 2019 10:27:42 GMT
Set-Cookie: WebEnv=1Jqk9ZOlyZSMGjHikFxNDsJ_ObuK0OxHkidgMrx8vWy2g9zqu8wopb8_D9qXGsLJQ9mdylAaDMA_T-tvHJ40Sq_FODOo33__T-tAH%40CE8C479DB3510951_0083SID; domain=.nlm.nih.gov; path=/; expires=Fri, 29 Jun 2018 18:27:42 GMT
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
Transfer-Encoding: chunked
Vary: Accept-Encoding
X-UA-Compatible: IE=Edge
X-XSS-Protection: 1; mode=block

REQUEST HEADERS
========================================================
Accept: text/html, */*; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 395
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: ncbi_sid=CE8C479DB3510951_0083SID; _ga=GA1.2.1222765292.1530204312; _gid=GA1.2.739858891.1530204312; _gat=1; WebEnv=18Kcapkr72VVldfGaODQIbB2bzuU50uUwU7wrUi-x-bNDgwH73vW0M9dVXA_JOyukBSscTE8Qmd1BmLAi2nDUz7DRBZpKj1wuA_QB%40CE8C479DB3510951_0083SID; starnext=MYGwlsDWB2CmAeAXAXAbgA4CdYDcDOsAhpsABZoCu0IA9oQCZxLJA===
Host: www.ncbi.nlm.nih.gov
NCBI-PHID: 396E3400B36089610000000000C6005E.m_12.03
Origin: https://www.ncbi.nlm.nih.gov
Referer: https://www.ncbi.nlm.nih.gov/pubmed
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
X-Requested-With: XMLHttpRequest

FORM DATA
========================================================
p$l: AjaxServer
portlets: id=relevancesortad:sort=;id=timelinead:blobid=NCID_1_120519284_130.14.22.215_9001_1530267709_1070655576_0MetA0_S_MegaStore_F_1:yr=:term=%222015%22%5BDate%20-%20Publication%5D%20%3A%20%223000%22%5BDate%20-%20Publication%5D;id=reldata:db=pubmed:querykey=1;id=searchdetails;id=recentactivity
load: yes

This is my script so far (the get request is working flawlessly if uncommented, but for the first page):
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

geturl = "https://www.ncbi.nlm.nih.gov/pubmed/?term=%222015%22%5BDate+-+Publication%5D+%3A+%223000%22%5BDate+-+Publication%5D"
posturl = "https://www.ncbi.nlm.nih.gov/pubmed/"

# res = requests.get(geturl,headers={"User-Agent":"Mozilla/5.0"})
# soup = BeautifulSoup(res.text,"lxml")
# for items in soup.select("div.rslt p.title a"):
#     print(items.get("href"))

FormData={
    'p$l': 'AjaxServer',
    'portlets': 'id=relevancesortad:sort=;id=timelinead:blobid=NCID_1_120519284_130.14.22.215_9001_1530267709_1070655576_0MetA0_S_MegaStore_F_1:yr=:term=%222015%22%5BDate%20-%20Publication%5D%20%3A%20%223000%22%5BDate%20-%20Publication%5D;id=reldata:db=pubmed:querykey=1;id=searchdetails;id=recentactivity',
    'load': 'yes'
    }

req = requests.post(posturl,data=FormData,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(req.text,"lxml")
for items in soup.select("div.rslt p.title a"):
    print(items.get("href"))

Btw, the url in the browser becomes "https://www.ncbi.nlm.nih.gov/pubmed" when I click on the next page link.
I don't wish to go for any solution related to any browser simulator. Thanks in advance.

A: The content is heavily dynamic, so it would be best to use selenium or similar clients, but I realize that this wouldn't be practical as the number of results is so large. So, we'll have to analyse the HTTP requests submitted by the browser and simulate them with requests.
The contents of next page are loaded by POST request to /pubmed, and the post data are the input fields of the EntrezForm form. The form submission is controlled by js (triggered when 'next page' button is clicked), and is preformed with the .submit() method.
After some examination I discovered some interesting fields:

*

*EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_Pager.CurrPage and
EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_Pager.cPage indicate the current and next page.

*EntrezSystem2.PEntrez.DbConnector.Cmd seems to preform a database query. If we don't submit this field the results won't change.

*EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_DisplayBar.PageSize and
EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_DisplayBar.PrevPageSize indicate the number of results per page.
With that information I was able to get multiple pages with the script below.
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

geturl = "https://www.ncbi.nlm.nih.gov/pubmed/?term=%222015%22%5BDate+-+Publication%5D+%3A+%223000%22%5BDate+-+Publication%5D"
posturl = "https://www.ncbi.nlm.nih.gov/pubmed/"

s = requests.session()
s.headers["User-Agent"] = "Mozilla/5.0"

soup = BeautifulSoup(s.get(geturl).text,"lxml")
inputs = {i['name']: i.get('value', '') for i in soup.select('form#EntrezForm input[name]')}

results = int(inputs['EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_ResultsController.ResultCount'])
items_per_page = 100
pages = results // items_per_page + int(bool(results % items_per_page))

inputs['EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_DisplayBar.PageSize'] = items_per_page
inputs['EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_DisplayBar.PrevPageSize'] = items_per_page
inputs['EntrezSystem2.PEntrez.DbConnector.Cmd'] = 'PageChanged'

links = []

for page in range(pages):
    inputs['EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_Pager.CurrPage'] = page + 1
    inputs['EntrezSystem2.PEntrez.PubMed.Pubmed_ResultsPanel.Pubmed_Pager.cPage'] = page

    res = s.post(posturl, inputs)
    soup = BeautifulSoup(res.text, "lxml")

    items = [i['href'] for i in soup.select("div.rslt p.title a[href]")]
    links += items

    for i in items:
        print(i)

I'm requesting 100 items per page because higher numbers seem to 'break' the server, but you should be able to adjust that number with some error checking.
Finally, the links are displayed in descending order (/29960282, /29960281, ...), so I thought we could calculate the links without preforming any POST requests:
geturl = "https://www.ncbi.nlm.nih.gov/pubmed/?term=%222015%22%5BDate+-+Publication%5D+%3A+%223000%22%5BDate+-+Publication%5D"
posturl = "https://www.ncbi.nlm.nih.gov/pubmed/"

s = requests.session()
s.headers["User-Agent"] = "Mozilla/5.0"
soup = BeautifulSoup(s.get(geturl).text,"lxml")

results = int(soup.select_one('[name$=ResultCount]')['value'])
first_link = int(soup.select_one("div.rslt p.title a[href]")['href'].split('/')[-1])
last_link = first_link - results

links = [posturl + str(i) for i in range(first_link, last_link, -1)]

But unfortunately the results are not accurate.

A: Not to treat this question as an XY problem, as, if solved, should pose a very interesting solution BUT I have found a solution for this specific issue that is much more efficient: Using the NCBI's Entrez Programming Utilities and a handy, opensource, unofficial Entrez repo.
With the entrez.py script from the Entrez repo in my PATH, I've created this script that prints out the links just as you want them:
from entrez import on_search
import re

db = 'pubmed'
term = '"2015"[Date - Publication] : "3000"[Date - Publication]'
link_base = f'https://www.ncbi.nlm.nih.gov/{db}/'

def links_generator(db, term):
    for line in on_search(db=db, term=term, tool='link'):
        match = re.search(r'<Id>([0-9]+)</Id>', line)
        if match: yield (link_base + match.group(1))

for link in links_generator(db, term):
    print(link)

Output:
https://www.ncbi.nlm.nih.gov/pubmed/29980165
https://www.ncbi.nlm.nih.gov/pubmed/29980164
https://www.ncbi.nlm.nih.gov/pubmed/29980163
https://www.ncbi.nlm.nih.gov/pubmed/29980162
https://www.ncbi.nlm.nih.gov/pubmed/29980161
https://www.ncbi.nlm.nih.gov/pubmed/29980160
https://www.ncbi.nlm.nih.gov/pubmed/29980159
https://www.ncbi.nlm.nih.gov/pubmed/29980158
https://www.ncbi.nlm.nih.gov/pubmed/29980157
https://www.ncbi.nlm.nih.gov/pubmed/29980156
https://www.ncbi.nlm.nih.gov/pubmed/29980155
https://www.ncbi.nlm.nih.gov/pubmed/29980154
https://www.ncbi.nlm.nih.gov/pubmed/29980153
https://www.ncbi.nlm.nih.gov/pubmed/29980152
https://www.ncbi.nlm.nih.gov/pubmed/29980151
https://www.ncbi.nlm.nih.gov/pubmed/29980150
https://www.ncbi.nlm.nih.gov/pubmed/29980149
https://www.ncbi.nlm.nih.gov/pubmed/29980148
...

Which, if compared to the frontend page, are in the same order. :-)


text:
Q: Proper Naming Convention For Parameter of Type List I wrote a method in c# which takes the input parameter of type List and i kept the parameter variable name as cardIDList.
And from code review feedback, they asked me to change the parameter variable name from cardIDList to cardIDs saying that appending list is not a right naming convention from Microsoft standard.
I tried to find the truthiness of that feedback in google, but I couldn't find like that anywhere. I need the help on this.
From :
public void DoSomething(List<long> cardIDList)

To :
public void DoSomething(List<long> cardIDs)

A: Common naming conventions can be found here https://github.com/ktaranov/naming-convention/blob/master/C%23%20Coding%20Standards%20and%20Naming%20Conventions.md
and here:
https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines
https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-parameters says:

CONSIDER using names based on a parameter's meaning rather than the
  parameter's type.

First of all - why do you take List as a parameter? You should allow the parameter to be as generic as possible - if you only need collection of elements and their count, use ICollection. Even better IEnumerable if you want to only iterate through the list or IReadOnlyCollection if you want to avoid accidental item change. It will be much easier to write unit tests for this method or override it in the future.
As you can see, type of parameter can be changed in the future and it shouldn't affect the naming. Putting "list" in the parameter name is redundant because we already know the type of that parameter. Now what should you do if you want for example to change the type to IEnumerable? Change it to cardIDEnumerable?


text:
Q: Full screen caller for Android I would like to developed full screen caller application in android.
How can i add my activity on top of the call screen of my phone? Any example?

A: i dont really understand your question, but a fullscreen view can be created by the following code:
 requestWindowFeature(Window.FEATURE_NO_TITLE);
 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)

note: its important to call this before setContentView();


text:
Q: Java project runs in ecipse but fails when exported Hey everyone thanks for all the help so far !. I have finally finished this project and it runs fine in eclipse but when I export it I get this error from stack trace also any help on how this could be improved in terms of architecture is much appreciated.
Exception is Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeExcepti
on: com.badlogic.gdx.utils.GdxRuntimeException: File not found: assets\font.fnt
It runs fine in eclipe but fails when exported

public class ConnectFourApplication extends Game implements ApplicationListener {

 private Screen screen;
 private Game game;

 public static void main(String[] args) {

  new LwjglApplication(new ConnectFourApplication(), "PennyPop", 1280, 720,
    true);
 }

 public ConnectFourApplication(){
  game = this;
 }

 @Override
 public void create() {
  screen = new MainScreen(game);
  setScreen(screen);
  screen.show();

 }

 @Override
 public void dispose() {
  screen.hide();
  screen.dispose();

 }

 /** Clears the screen with a white color */
 private void clearWhite() {
  Gdx.gl.glClearColor(1, 1, 1, 1);
  Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
 }

 @Override
 public void pause() {
  screen.pause();
 }

 @Override
 public void render() {
  clearWhite();
  super.render();
 }

 @Override
 public void resize(int width, int height) {
  screen.resize(width, height);

 }

 @Override
 public void resume() {
  screen.resume();
 }

public class MainScreen implements Screen {

 private final Stage stage;
 private final SpriteBatch spriteBatch;

 //Parameter for drawing the buttons
 private final BitmapFont font;
 private final TextureAtlas buttons;
 private final Button SFXButton;
 private final Button APIButton;
 private final Button GameButton;
 private final Skin images;

 //Parameter for Sound
 private final com.badlogic.gdx.audio.Sound SFXClick;

 //Parameter for the api call
 private final String WeatherUrl;
 private final HttpRequest request;
 private final City SanFrancisco;

 //The screen to load after the game button is hit
 private Screen gamescreen;

 private Game game;

 public MainScreen(Game game) {

   this.game = game;

  //Set up our assets
  spriteBatch = new SpriteBatch();
  stage = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false, spriteBatch);

  font = new BitmapFont(Gdx.files.internal("assets/font.fnt"),
           Gdx.files.internal("assets/font.png"), false);

  buttons = new TextureAtlas("assets/GameButtons.pack");
  images = new Skin(buttons);
  images.addRegions(buttons);
  SFXButton = new Button(images.getDrawable("sfxButton"));
  SFXButton.setPosition(295, 310);
  APIButton = new Button(images.getDrawable("apiButton"));
  APIButton.setPosition(405, 310);
  GameButton = new Button(images.getDrawable("gameButton"));
  GameButton.setPosition(515, 310);
  SFXClick = Gdx.audio.newSound(Gdx.files.internal("assets/button_click.wav"));

  //Add our actors to the stage
  stage.addActor(SFXButton);
  stage.addActor(APIButton);
  stage.addActor(GameButton);

  //Set up our Url request to be used when clicking the button
  WeatherUrl = "http://api.openweathermap.org/data/2.5/weather?q=San%20Francisco,US";
  request = new HttpRequest(HttpMethods.GET);
  request.setUrl(WeatherUrl);
  SanFrancisco = new City("Unavailable","Unavailable","0","0"); //init san fran to be displayed before they have clicked the button

 }

 @Override
 public void dispose() {
  spriteBatch.dispose();
  stage.dispose();
 }

 @Override
 public void render(float delta) {
  stage.act(delta);
  stage.draw();

  //Begin sprite batch
  spriteBatch.begin();

  //Set our on click listeners for our buttons
  if (SFXButton.isPressed())
   SFXClick.play();

  if(APIButton.isPressed())
  {
   CallApi();
  }

  if(GameButton.isPressed())
   LoadGame();

  //Set font color and render the screen
  font.setColor(Color.RED);
  font.draw(spriteBatch, "PennyPop", 455 - font.getBounds("PennpyPop").width/2,
    460 + font.getBounds("PennyPop").height/2);

  font.setColor(Color.BLACK);
  font.draw(spriteBatch, "Current Weather", 900 - font.getBounds("PennpyPop").width/2,
    460 + font.getBounds("PennyPop").height/2);

  font.setColor(Color.LIGHT_GRAY);
  font.draw(spriteBatch, SanFrancisco.Name, 940 - font.getBounds("PennpyPop").width/2,
    420 + font.getBounds("PennyPop").height/2);

  font.setColor(Color.RED);
  font.draw(spriteBatch, SanFrancisco.CurrentCondition, 950 - font.getBounds("PennpyPop").width/2,
    300 + font.getBounds("PennyPop").height/2);

  font.draw(spriteBatch, SanFrancisco.Temperature + " Degrees,", 920 - font.getBounds("PennpyPop").width/2,
    270 + font.getBounds("PennyPop").height/2);

  font.draw(spriteBatch, SanFrancisco.WindSpeed, 1200 - font.getBounds("PennpyPop").width/2,
    270 + font.getBounds("PennyPop").height/2);

  //End or sprite batch
  spriteBatch.end();

 }

 //Handles calling our API
 public void CallApi(){

  //Sends our stored HTTPRequest object
   Gdx.net.sendHttpRequest(request, new HttpResponseListener() {
   @Override
   public void handleHttpResponse(HttpResponse httpResponse) {

    //Uses our private response reader object to give us a the JSON from the api call
    JSONObject json =  HttpResponseReader(httpResponse);

    //Gets the name of the city
    SanFrancisco.Name = (String) json.get("name");

    //Parsed through our returned JSON for the weather key
    JSONArray WeatherArray = (JSONArray) json.get("weather");
    //Gets the actual weather dictionary
    JSONObject Weather = (JSONObject) WeatherArray.get(0);
    //Finally get the value with the key of description and assign it
    //To the San Fran current conditions field
    SanFrancisco.CurrentCondition = (String) Weather.get("description");

    //Gets the actual main dictionary
    JSONObject main = (JSONObject) json.get("main");
    //Finally get the values based on the keys
    SanFrancisco.Temperature = (String) Double.toString((double) main.get("temp"));

    //Finally get the wind speed
    JSONObject wind = (JSONObject) json.get("wind");
    SanFrancisco.WindSpeed = (String) Double.toString((double) wind.get("speed"));

   }

            @Override
            public void failed(Throwable t) {
                Gdx.app.log("Failed ", t.getMessage());

            }
   });
 }

 //When the button game button is clicked should load the connect four game
 public void LoadGame(){

  game.setScreen(new GameScreen(game));

 }

 //Converts our HttpResponse into a JSON OBject
 private static JSONObject HttpResponseReader(HttpResponse httpResponse){

     BufferedReader read = new BufferedReader(new InputStreamReader(httpResponse.getResultAsStream()));
        StringBuffer result = new StringBuffer();
        String line = "";

        try {
         while ((line = read.readLine()) != null) {
         result.append(line);
     }

            JSONObject json;
   try {
    json = (JSONObject)new JSONParser().parse(result.toString());
    return json;
   } catch (ParseException e) {
    e.printStackTrace();
   }

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

        return null;

 }

 @Override
 public void resize(int width, int height) {
  stage.setViewport(width, height, false);
 }

 @Override
 public void hide() {
  Gdx.input.setInputProcessor(null);
 }

 @Override
 public void show() {
  Gdx.input.setInputProcessor(stage);
  render(0);
 }

 @Override
 public void pause() {
  // Irrelevant on desktop, ignore this
 }

 @Override
 public void resume() {
  // Irrelevant on desktop, ignore this
 }

 public class GameScreen  implements Screen {

//Our stage and sprites
private final Stage gamestage;
private final SpriteBatch gamesprites;

//Parameter for drawing the pieces
private final BitmapFont gamefont;
private final TextureAtlas pieces;
private final Skin piecesskin;

//this will be the sprite and texture for our red connect four buttons
private Texture redtexture;
private Sprite redsprite;

//this will be the sprite and texture for our red connect four buttons
private Texture yellowtexture;
private Sprite yellowsprite;

//Setup the board
//renders the line
private ShapeRenderer boardlineshape;

//setup the line locations
private int linestartx;
private int linestarty;
private int lineendx;
private int lineendy;
private int linexdistance;
private int lineydistance;

//for this game we will define a board size as the amount of lines the board should contain
private double boardsize;

//Lines required to win
private int linestowin;
private String playersturnstring;
private OrthographicCamera camera;

//Holds all the parameters for our players

//Keeps track of who's turn it is, if 0 player one if 1 player two
private int playersturn;

//Holds the location of all of player ones pieces
//Needs to be two Dimensional to hold x and y values
private int[][] playeronepieces;

private int playeronepieceindex;

//Holds the location of all of player twos pieces
//Needs to be two Dimensional to hold x and y values
private int[][] playertwopieces;

private int playertwopieceindex;

//make the number of pieces per player variable so it can be changed for the future
private int numberofpiecesperplayer;

private Game game;

public boolean gameover;

private boolean isready;

private int[][] RowsAndColumns;

private int columnvalue = 538;

public GameScreen(Game game){

  this.game = game;

 //Set up our assets
 gamesprites = new SpriteBatch();
 gamestage = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false, gamesprites);

 //Sets up our font
 gamefont = new BitmapFont(Gdx.files.internal("assets/font.fnt"),
          Gdx.files.internal("assets/font.png"), false);

 pieces = new TextureAtlas("assets/GameButtons.pack");
 piecesskin = new Skin(pieces);
 piecesskin.addRegions(pieces);

 //set up our camera
    camera= new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    camera.setToOrtho(true, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    camera.update();

    //sets up our red connect four piece
    redtexture = new Texture(Gdx.files.internal("assets/red.png"));
    redsprite = new Sprite(redtexture);

    //sets up our yellow connect four piece
    yellowtexture = new Texture(Gdx.files.internal("assets/yellow.png"));
    yellowsprite = new Sprite(yellowtexture);

 //setup the board
    SetUpGameBoard(8,4,Color.BLACK);

    linestartx = 300;
    linestarty = 100;
    lineendx = 300;
    lineendy = 600;
    linexdistance = 100;
    lineydistance = 100;

 //setup the pieces
    numberofpiecesperplayer = 60;

 //initialize anything else we need for the game
 playersturnstring = "";

 //start with player one's turn
 playersturn = 0;

 //setup or pieces locations as blank
 playeronepieces = new int[2][numberofpiecesperplayer]; //create two arrays one for x values one for y

 playeronepieceindex = 0;

 playertwopieces = new int[2][numberofpiecesperplayer]; //create two arrays one for x values one for y

 playertwopieceindex = 0;

 gameover = false;

 isready = false;

 linestowin = 4;

}

//Should initialize our game board
public void SetUpGameBoard(int boardsize,int linestowin, Color linecolor){

 this.boardsize = boardsize;
 this.linestowin = linestowin;
 boardlineshape = new ShapeRenderer();
 boardlineshape.setProjectionMatrix(camera.combined);
 boardlineshape.setColor(linecolor);

 //holds the board cells
 RowsAndColumns = new int[2][(int) boardsize];

}

@Override
public void dispose() {
 // TODO Auto-generated method stub

}

@Override
public void hide() {
 Gdx.input.setInputProcessor(null);

}

@Override
public void pause() {
 // TODO Auto-generated method stub

}

@Override
public void render(float delta) {

 //set the stage
 gamestage.act(delta);
 gamestage.draw();

 //if the mouse is clicked and the game is not over send us back to the main screen
 if (Gdx.input.justTouched() && gameover == true){

  //if the game is over and the user clicks send us back to the main screen
  game.setScreen(new MainScreen(game));
 }

 if(isready){
  //if the mouse is clicked and the game is not over add a piece to player one
  if (Gdx.input.justTouched() && gameover != true){

   AddPiece(Gdx.input.getX(), Gdx.input.getY());
  }
 }

 //Draw our board
 boardlineshape.begin(ShapeType.Line);

 ///Draw all of the lines for our board
 DrawBoard(linestartx,linestarty,lineendx,lineendy);

 boardlineshape.end();

 //Starts our game sprite batch
 gamesprites.begin();

 //Draw all of player ones pieces
 DrawPlayerOnePieces();

 //Draw all of player twos pieces
 DrawPlayerTwoPieces();

 gamefont.draw(gamesprites, playersturnstring, 515, 650);

 //End our game sprite batch
 gamesprites.end();

 //Lastly check to make sure our the game is not over
 CheckForGameOver();

 isready = true;

}

//draw the board
private void DrawBoard(int linestartx, int linestarty, int lineendx, int lineendy){

 camera.update();
 boardlineshape.setProjectionMatrix(camera.combined);

 //For each line in our board draw a line
 for(int i =0; i < boardsize; i++)
 {
  //first we will draw the vertical lines then we will change to the horizontal lines

  boardlineshape.line(linestartx, linestarty,lineendx, lineendy);

  //if the x value exceeds a certian amount then change to the horizontal lines

  //increment the start x position to draw another line
  linestartx += linexdistance;
  lineendx += lineydistance;

  //if the x start is over 1200 we have drawn the last vertical line so switch to th
  //horizontal lines
  if(linestartx > 1000)
  {

   //set our x values and render our horizontal lines
   lineendx = linestartx - linexdistance;
   linestartx = this.linestartx;

   linestarty = this.linestarty;
   lineendy = this.linestarty;

   for(int index =0; index < boardsize -2; index++){

    //increment the start y position to draw another line
    boardlineshape.line(linestartx, linestarty,lineendx, lineendy);

    linestarty += lineydistance;
    lineendy += lineydistance;

   }
  }

 }
}

//Draws all the current pieces for player one
private void DrawPlayerOnePieces(){

 //For all of player one's pieces
 for(int i = 0; i < playeronepieces[1].length;i++)
 {
  //of its not an empty piece draw it
  if(playeronepieces[0][i] != 0){

   gamesprites.draw(redtexture, playeronepieces[0][i], playeronepieces[1][i]);
  }

 }

}

//Draws all the current pieces for player two
private void DrawPlayerTwoPieces(){

 //For all of player two's pieces
 for(int i = 0; i < playertwopieces[1].length;i++)
 {
  //of its not an empty piece draw it
  if(playertwopieces[0][i] != 0){

   gamesprites.draw(yellowtexture, playertwopieces[0][i], playertwopieces[1][i]);
  }

 }

}

//Adds a piece to whichever players current turn it is
private void AddPiece(int clickx, int clicky){

 RestPlayersTurn(playersturn);

 int computedx = GetComputedX(clickx,linestartx);

 int computedy = GetComputedY(clicky,linestarty);

 if(playeronepieceindex != 60)
 {
  //makes sure they are clicking inside our board and that there is not already a piece on that part of the board
  if(
    (clickx > linestartx && clickx < linestartx + ((boardsize - 1) * linexdistance))&&
    (clicky > linestarty && clicky < lineendy)&&
    (CheckIfPieceExists(computedx,computedy,playeronepieces) == false) &&
    (CheckIfPieceExists(computedx,computedy,playertwopieces) == false)
    )
  {
   if(playersturn == 0)
   {
    playeronepieces[0][playeronepieceindex] = computedx; //set the x value

    playeronepieces[1][playeronepieceindex] = 700 - computedy; //set the y value

    playeronepieceindex++;

    playersturnstring = "Player Two's turn";

    gamefont.setColor(Color.YELLOW);

   }
   else if(playersturn == 1)
   {

    playertwopieces[0][playertwopieceindex] = computedx; //set the x value

    playertwopieces[1][playertwopieceindex] = 700 - computedy; //set the y value

    playertwopieceindex++;

    playersturnstring = "Player One's turn";

    gamefont.setColor(Color.RED);

   }

   //every time we add a piece change the players turn
   playersturn++;

  }
 }

}

//puts our x value in the center of its cell
public int GetComputedX(int touchx, int linestartx){

 //compute our x depending on the nearest line
 int lineendx = linestartx + linexdistance;

 //for the images width
 int imagewidth = redtexture.getWidth();

 for(int i = 0; i < boardsize; i++)
 {
  //if the touched x is in this range than assign the computed x value to
  //half the cell
  if(touchx > linestartx && touchx < lineendx){

   touchx = (lineendx - (linexdistance/2)) - (imagewidth/2);
   break;
  }

  linestartx += linexdistance;
  lineendx += linexdistance;
 }

 return touchx;
}

//puts our y value in the center of the cell
public int GetComputedY(int touchy, int linestarty)
{
 //compute our x depending on the nearest line
 int lineendy = linestarty + lineydistance;

 //for the images width
 int imageheight = redtexture.getHeight();

 //computer our x depending on the nearest line
 for(int i =0; i < boardsize; i++)
 {
  //if the touched x is in this range than assign the computed x value to
  //half the cell
  if(touchy > linestarty && touchy < lineendy){
   touchy = ((lineendy - (lineydistance/2)) + (imageheight/4));
   break;
  }

  linestarty += lineydistance;
  lineendy += lineydistance;
 }

 return touchy;
}

//Sets the next players turn
private void RestPlayersTurn(int playerturn){

 if(playerturn == 2){

  playersturn = 0;

 }

}

//check for game over
private void CheckForGameOver(){

 //check if player one has a connect four
 CheckForConnectFourHorizontal();
 CheckForConnectFourVertical();
 CheckForConnectFourDiagonal();

}

private void CheckForConnectFourHorizontal(){

 int rowvalue = 318;

 int columnvalue = 534;

 //for each column on the board check the row for a horizontal connect four for player one
 for(int i = 0; i < RowsAndColumns[1].length; i++)
 {
  CheckRowForConnectFour(rowvalue,columnvalue,playeronepieces);

  rowvalue = 318;

  columnvalue = columnvalue - 100;
 }

        rowvalue = 318;

     columnvalue = 534;

 //for each column on the board check the row for a horizontal connect four for player two
 for(int i = 0; i < RowsAndColumns[1].length; i++)
 {
  CheckRowForConnectFour(rowvalue,columnvalue,playertwopieces);

  rowvalue = 318;

  columnvalue = columnvalue - 100;
 }

}

private void CheckForConnectFourVertical(){

 int rowvalue = 318;

 int columnvalue = 534;

 //for each column on the board check the row for a horizontal connect four
 for(int i = 0; i < RowsAndColumns[1].length; i++)
 {
  CheckColumnForConnectFour(rowvalue,columnvalue,playeronepieces);

  rowvalue = rowvalue + 100 ;

  columnvalue = 534;
 }

 rowvalue = 318;

 columnvalue = 534;

 //for each column on the board check the row for a horizontal connect four
 for(int i = 0; i < RowsAndColumns[1].length; i++)
 {
  CheckColumnForConnectFour(rowvalue,columnvalue,playertwopieces);

  rowvalue = rowvalue + 100 ;

  columnvalue = 534;
 }

}

private void CheckForConnectFourDiagonal(){

 int rowvalue = 318;

 int columnvalue = 534;

 int originalrowvalue = 318;

 //finally do this for every column
 for(int index = 0; index < RowsAndColumns[0].length; index++ ){

  //for each row on the board check the next four diagonal
  for(int i = 0; i < RowsAndColumns[1].length; i++)
  {
   CheckDiagonalSegment(rowvalue,columnvalue,playeronepieces);

   rowvalue = rowvalue + 100;
  }

  rowvalue = originalrowvalue;
  columnvalue -= 100;

 }

 rowvalue = 318;

 columnvalue = 534;

 originalrowvalue = 318;

 //finally do this for every column
 for(int index = 0; index < RowsAndColumns[0].length; index++ ){

  //for each row on the board check the next four diagonal
  for(int i = 0; i < RowsAndColumns[1].length; i++)
  {
   CheckDiagonalSegment(rowvalue,columnvalue,playertwopieces);

   rowvalue = rowvalue + 100;
  }

  rowvalue = originalrowvalue;
  columnvalue -= 100;

 }

}

private void CheckRowForConnectFour(int rowvalue, int columnvalue, int[][] playerpieces){

 int consecutivepiecesinrow = 0;

 int nonmatchedpieces = 0;

 //for all the rows in this column
 for(int index = 0; index < playerpieces[0].length; index++){ //go through the row

  //for all of the pieces check to see if one matches this spot on the grid
  for(int i = 0; i < playerpieces[0].length;i++)
  {
   //if both of these match this is a cell is occupied by a red peiece
   if(playerpieces[0][i] == rowvalue && playerpieces[1][i] == columnvalue )
   {
    //add to the counter
    consecutivepiecesinrow++;
    nonmatchedpieces = 0;
    break; //we found a piece here so break to the outer loop

   }

   else{ //if we found one add them to our counter otherwise if none of the items
    //match then it doesnt exist in this array

    nonmatchedpieces++;
   }
  }

  //if the red player has no piece on this cell
  if(nonmatchedpieces == playerpieces[0].length)
  {
   consecutivepiecesinrow = 0;
   nonmatchedpieces = 0;
  }

  //if we hit for matched then end the game
  if(consecutivepiecesinrow == 4){
   playersturnstring = "Game Over";
   gamefont.setColor(Color.RED);
   gameover = true;

  }

  //check the next cell
  rowvalue += 100;

 }

}

private void CheckColumnForConnectFour( int rowvalue, int columnvalue, int[][] playerpieces)
{

 int consecutivepiecesinrow = 0;

 int nonmatchedpieces = 0;

 //for all the rows in this column
 for(int index = 0; index < RowsAndColumns[1].length; index++){ //go through the column

  //for all of the pieces check to see if one matches this spot on the grid
  for(int i = 0; i < playerpieces[1].length;i++)
  {
   //if both of these match this is a cell is occupied by a red peiece
   if(playerpieces[0][i] == rowvalue && playerpieces[1][i] == columnvalue )
   {
    //add to the counter
    consecutivepiecesinrow++;
    nonmatchedpieces = 0;
    break; //we found a piece here so break to the outer loop

   }

   else{ //if we found one add them to our counter otherwise if none of the items
    //match then it doesnt exist in this array

    nonmatchedpieces++;
   }
  }

  //if the red player has no piece on this cell
  if(nonmatchedpieces == playerpieces[0].length)
  {
   consecutivepiecesinrow = 0;
   nonmatchedpieces = 0;
  }

  //if we hit for matched then end the game
  if(consecutivepiecesinrow == 4){
   playersturnstring = "Game Over";
   gamefont.setColor(Color.RED);
   gameover = true;

  }

  //check the next cell
  columnvalue -= 100;

 }

}

private void CheckDiagonalSegment(int rowvalue, int columnvalue, int[][] playerpieces){

 CheckForForwardDiagonal(rowvalue,columnvalue,playerpieces);
 CheckForBackwardDiagonal(rowvalue,columnvalue,playerpieces);

}

private void CheckForForwardDiagonal(int rowvalue, int columnvalue,int[][] playerpieces){

 int consecutivepiecesinrow = 0;

 int nonmatchedpieces = 0;

 //check for four to the right
 for(int index = 0; index < RowsAndColumns[0].length; index++){ //for every square in the diagonal

  for(int i = 0; i < playeronepieces[0].length;i++) // for every player peice check for a red
  {

   //if both of these match this is a cell is occupied by a red peiece
   if(playerpieces[0][i] == rowvalue && playerpieces[1][i] == columnvalue )
   {
    //add to the counter
    consecutivepiecesinrow++;
    nonmatchedpieces = 0;
    break; //we found a piece here so break to the outer loop

   }

   else{ //if we found one add them to our counter otherwise if none of the items
    //match then it doesnt exist in this array

    nonmatchedpieces++;
   }
  }

  //if the red player has no piece on this cell
  if(nonmatchedpieces == playerpieces[0].length)
  {
   consecutivepiecesinrow = 0;
   nonmatchedpieces = 0;
  }

  //if we hit for matched then end the game
  if(consecutivepiecesinrow == 4){
   playersturnstring = "Game Over";
   gamefont.setColor(Color.RED);
   gameover = true;

  }

  rowvalue += 100;
  columnvalue -= 100;

 }

}

public void CheckForBackwardDiagonal(int rowvalue, int columnvalue,int[][] playerpieces){

 int consecutivepiecesinrow = 0;

 int nonmatchedpieces = 0;

 //checks the diagonal to the left
 for(int index = 0; index < RowsAndColumns[0].length; index++){ //for every square in the diagonal

  for(int i = 0; i < playerpieces[0].length;i++) // for every player peice check for a red
  {

   //if both of these match this is a cell is occupied by a red peiece
   if(playerpieces[0][i] == rowvalue && playerpieces[1][i] == columnvalue )
   {
    //add to the counter
    consecutivepiecesinrow++;
    nonmatchedpieces = 0;
    break; //we found a piece here so break to the outer loop

   }

   else{ //if we found one add them to our counter otherwise if none of the items
    //match then it doesnt exist in this array

    nonmatchedpieces++;
   }
  }

  //if the red player has no piece on this cell
  if(nonmatchedpieces == playerpieces[0].length)
  {
   consecutivepiecesinrow = 0;
   nonmatchedpieces = 0;
  }

  //if we hit for matched then end the game
  if(consecutivepiecesinrow == 4){
   playersturnstring = "Game Over";
   gamefont.setColor(Color.RED);
   gameover = true;

  }

  rowvalue -= 100;
  columnvalue -= 100;
 }

}

//checks if a piece is already in this position on the board
public boolean CheckIfPieceExists(int row,int column,int[][] playerpieces){

 //for all of the pieces check to see if one matches this spot on the grid
 for(int i = 0; i < playerpieces[0].length;i++)
 {
  //if both of these match this is a cell is occupied by a red peiece
  if(playerpieces[0][i] == row && playerpieces[1][i] == column )
  {
   //there is already a piece here
   return true;
  }
 }
 return false;

}

@Override
public void resize(int arg0, int arg1) {
 // TODO Auto-generated method stub

}

@Override
public void resume() {
 // TODO Auto-generated method stub

}

@Override
public void show() {
 //set the processor to the new screen
 Gdx.input.setInputProcessor(gamestage);
 //render our game screen
 render(0);

}

A: The Problem is related to that line
font = new BitmapFont(Gdx.files.internal("assets/font.fnt"),
             Gdx.files.internal("assets/font.png"), false);

The file search patch (and classpath) is handled in a different way when starting applications from within your eclipse workspace.
The font is not exported (or not present) in your installed application.
1)
Try to print the file path to console or debug your application. I assume that the file-root is different.
2)
the font is not exported correctly and has to be aded to the build.properties

A:
It runs fine in eclipe but fails when exported

The correct way to export is:

File -> Export -> Java -> Runnable JAR file.

Be sure to check:

Package required libraries into Generated JAR.

That way, your assets will be packaged in the jar and the font will be found.