text:
Q: I am making a login/registration and right now im stuck on the registration page on flutter So this is the code for the register.dart file:
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'list.dart';
import 'main.dart';

class Register extends StatefulWidget {
  const Register({Key? key}) : super(key: key);

  @override
  _RegisterState createState() => _RegisterState();
}

class _RegisterState extends State<Register> {
  TextEditingController user = TextEditingController();
  TextEditingController pass = TextEditingController();

  Future register() async {
    var url = 'https://weplant.zanhrastnik.com/register.php';
    var response = await http.post(Uri.parse(url), body: {
      "email": user.text,
      "password": pass.text,
    });
    var data = json.decode(response.body);
    if (data == "Success") {
      Navigator.pushReplacement(
          context, MaterialPageRoute(builder: (context) => const AllPlants()));
    } else {
      showDialog(
        context: context,
        builder: (BuildContext context) => _buildPopupDialog(context),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'Login SignUp',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
      ),
      body: Container(
        height: 300,
        child: Card(
          color: Colors.amber,
          child: Column(
            children: <Widget>[
              const Padding(
                padding: EdgeInsets.all(8.0),
                child: Text(
                  'Register',
                  style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextField(
                  decoration: InputDecoration(
                    labelText: 'Username',
                    prefixIcon: const Icon(Icons.person),
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8)),
                  ),
                  controller: user,
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextField(
                  obscureText: true,
                  decoration: InputDecoration(
                    labelText: 'Password',
                    prefixIcon: const Icon(Icons.lock),
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8)),
                  ),
                  controller: pass,
                ),
              ),
              Row(
                children: <Widget>[
                  Expanded(
                    child: ElevatedButton(
                      child: const Text('Register',
                          style: TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                              color: Colors.white)),
                      onPressed: () {
                        register();
                      },
                    ),
                  ),
                  Expanded(
                    child: MaterialButton(
                      color: Colors.amber[100],
                      child: const Text('Login',
                          style: TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                              color: Colors.black)),
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const MyApp(),
                          ),
                        );
                      },
                    ),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
  Widget _buildPopupDialog(BuildContext context) {
    return AlertDialog(
      title: const Text('Error'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: const <Widget>[
          Text("Email or password are incorrect!"),
        ],
      ),
      actions: <Widget>[
        TextButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          child: const Text('Close'),
        ),
      ],
    );
  }

}

And this is the code for the file I'm trying to push to aka list.dart
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
import 'package:weplant/entities/plant.dart';
import 'package:line_awesome_flutter/line_awesome_flutter.dart';
import 'package:weplant/detail_plant.dart';
import 'package:google_fonts/google_fonts.dart';

void main() {
  runApp(const AllPlants());
}

class AllPlants extends StatelessWidget {
  const AllPlants({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'WePlant',
      theme: ThemeData(
          textTheme: GoogleFonts.robotoTextTheme(
            Theme.of(context).textTheme,
          ),
          scaffoldBackgroundColor: const Color(0xFFFEFFEE)
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  final List<Plant> _plants = <Plant>[];

  Future fetchPlants() async {
    var url = 'https://weplant.zanhrastnik.com/plants/';
    var response = await http.get(Uri.parse(url));

    var plants = <Plant>[];

    if (response.statusCode == 200){
      var plantsJson = jsonDecode(response.body);
      for (var plantJson in plantsJson){
        plants.add(Plant.fromJson(plantJson));
      }
    }
    return plants;
  }

  @override
  void initState() {
    fetchPlants().then((value) {
      setState(() {
        _plants.addAll(value);
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        leading: const Icon(
            LineAwesomeIcons.bars,
            color: Color.fromRGBO(254, 255, 238, 1.0)
        ),
        title: Image.asset(
          'assets/weplant_logo.png',
          height: 50,
        ),
        centerTitle: true,
        actions: const [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16),
            child: Icon(
                LineAwesomeIcons.search,
                color: Color.fromRGBO(254, 255, 238, 1.0)
            ),
          ),
        ],
        backgroundColor: const Color.fromRGBO(156, 175, 136, 1.0),
      ),

      body: Padding(
          child: ListView.builder(
            itemBuilder: (context, index) {
              return Card(
                  color: const Color.fromRGBO(254, 255, 238, 1.0),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16),
                      side: const BorderSide(color: Color.fromRGBO(230, 227, 211, 1.0), width: 1)
                  ),
                  child: Padding(
                    padding: const EdgeInsets.only(top: 8.0, bottom: 8.0, left:4.0, right: 4.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        ListTile(
                          leading: ClipRRect(
                            borderRadius: BorderRadius.circular(8.0),
                            child: Image.network(
                              _plants[index].pImage,
                              width: 50,
                            ),
                          ),
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                          trailing: const Icon(
                            LineAwesomeIcons.angle_right,
                            color: Color.fromRGBO(156, 175, 136, 1.0),
                          ),
                          title: Text(
                            _plants[index].pName,
                          ),
                          subtitle: Text(
                              _plants[index].pLatinName
                          ),
                          onTap: () {
                            Navigator.push(
                                context, MaterialPageRoute(builder: (context) => DetailPage(plant: _plants[index],)));
                          },
                        ),
                      ],
                    ),
                  ));
            },
            itemCount: _plants.length,
          ),
          padding: const EdgeInsets.only(top:4.0)
      ),
    );
  }
}

It only shows a blank screen when I'm pushing and I have no idea how does anybody know why it would do that? I tried adding the Hero as it was the only solution I found on the internet but that didn't work as well.

A: You need to call class in MaterialApp like this,
void main() {
  runApp(const AllPlants());
}

class AllPlants extends StatelessWidget {
  const AllPlants({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'WePlant',
      theme: ThemeData(
          textTheme: GoogleFonts.robotoTextTheme(
            Theme.of(context).textTheme,
          ),
          scaffoldBackgroundColor: const Color(0xFFFEFFEE)
      ),
      home: Register()
      // you call any class here as per your requirement
    );
  }
}


text:
Q: Why can't I test on my iPhone after upgrading it to iOS 6? I'm running Xcode 4.2 on Snow Leopard. I have upgraded my iPhone 4S to iOS 6, and now it's saying:

No provisioning iOS devices are available with a compatible iOS version...

whenever I try to perform tests on said device.
Am I going to need to completely upgrade my system, Xcode, etc. just because I upgraded iOS 6?
IS there any way I could just install the iOS 6 version on my Xcode 4.2?  I've been searching around, but sadly have had no real luck.

A: You have to match the iOS version with the SDK version, while the target iOS version can be different. So you need iOS SDK 6, that might require you to install Xcode 4.4 or 4.5 but you can still create projects targeting iOS 5. This way the signing and certificates will work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: global variable in all symfony2 app I am working in my project for the university with symfony2, and I have a problem since two days ago which I have not idea how to resolve.
I need a global variable shared between various users (various user sessions) but I don't know where I have to declare it.
I would like when user A change this variable then user B can read this variable updated.
Likely it is not possible but I am new in symfon2 and I am not sure.
Sorry if I have any mistake in the redaction but I am learning English now :)

A: You can write that variable to file or cache (apc-cache, for example). Cache will be shared between all requests, however,  it has lifetime.


text:
Q: How to fetch the location(Location at which image was taken) of selected image from gallery in Android Studio? I am developing an app, that performs operations such as take photo using camera and view the photos taken.Now, i have a button onclick of which it goes to the gallery where i can select the image.After selecting the image I am loading the image to an activity and also the location of the image. But, the location is the same(current location) for any photo selected.
I am using this for getting the location.But no matter which is the image i select the location is my current location.
GPSTRACKER.JAVA
package com.elno.bescomcoe;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import static android.content.ContentValues.TAG;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // Flag for GPS status
    boolean isGPSEnabled = false;

    // Flag for network status
    boolean isNetworkEnabled = false;

    // Flag for GPS status
    boolean canGetLocation = false;

    Location location; // Location
    double latitude; // Latitude
    double longitude; // Longitude

    int geocoderMaxResults = 1;

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context mContext) {
        this.mContext = mContext;
        getLocation();
    }

    @SuppressLint("MissingPermission")
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // Getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            System.out.println("GPS : " + isGPSEnabled);

            // Getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            System.out.println("NETWORK : " + isNetworkEnabled);

            if (isGPSEnabled) {
                this.isGPSEnabled = true;

            }

            if (!isGPSEnabled && !isNetworkEnabled) {
                // No network provider is enabled
                System.out.println("Inside gps and network");
            } else {
                System.out.println("outside gps and network");

                this.canGetLocation = true;
                if (isNetworkEnabled) {

                        //ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);

                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }

                }
            // If GPS enabled, get latitude/longitude using GPS Services
               if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
             }
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app.
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/Wi-Fi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog.
     * On pressing the Settings button it will launch Settings Options.
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing the Settings button.
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // On pressing the cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    //Get list of Addresses by latitude and longitude
    //return List<Adresses> - list of addresses or null
    public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {

            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

            try {
                /**
                 * Geocoder.getFromLocation - Returns an array of Addresses
                 * that are known to describe the area immediately surrounding the given latitude and longitude.
                 */
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

                return addresses;
            } catch (IOException e) {
                //e.printStackTrace();
                Log.e(TAG, "Impossible to connect to Geocoder", e);
            }
        }

        return null;
    }

    //Get the Address Line
    //Return address line or null
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;
        }
    }

    //Get the Locality
    //Return the locality or null
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        }
        else {
            return null;
        }
    }

    /**
     * Try to get Postal Code
     * @return null or postalCode
     */
    public String getPostalCode(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();

            return postalCode;
        } else {
            return null;
        }
    }

    /**
     * Try to get CountryName
     * @return null or postalCode
     */
    public String getCountryName(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();

            return countryName;
        } else {
            return null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

And, this is my Activity into which I am loading the selected image and location.
package com.elno.bescomcoe;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ViewGalleryAcitvity extends AppCompatActivity {

    private TextView LocationTextView;
    private ImageView SelectedImageView;

    GPSTracker gps;
    double latitude ;
    double longitude;
    String country;
    String city;
    String postalcode;
    String addressline;

    Uri imageUri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_gallery);
        LocationTextView = findViewById(R.id.LoctextView);
        SelectedImageView = findViewById(R.id.selectedimage);
        Bundle bundle = getIntent().getExtras();

        if(bundle != null){

            imageUri = Uri.parse(bundle.getString("picture"));
            SelectedImageView.setImageURI(imageUri);
            gps = new GPSTracker(getApplicationContext());
            if(gps.canGetLocation())
            {
                latitude = gps.getLatitude();
                longitude = gps.getLongitude();
                country = gps.getCountryName(this);
                city = gps.getLocality(this);
                postalcode = gps.getPostalCode(this);
                addressline = gps.getAddressLine(this);

                Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                LocationTextView.setText("Latitude - "+latitude+"\nLongitude - "+longitude);

            } else  {
                // Can't get location.
            }
        }
        else {
           //Bundle is empty
        }
    }
}

Now i want help on how to fetch the location of the image where it was taken rather than only my current location.

A: You can get Image attributes using ExifInterface
Example :
    ExifInterface exif = new ExifInterface(filepath);
    String LATITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
    String LATITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
    String LONGITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
    String LONGITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);

or
  ExifInterface exif = new ExifInterface(filepath);
  float[] latLong = new float[2];
  boolean hasLatLong = exif.getLatLong(latLong)
   if (hasLatLong) {
      System.out.println("Latitude: " + latLong[0]);
      System.out.println("Longitude: " + latLong[1]);
   }

A:     ExifInterface exif = new ExifInterface(getContentResolver().openInputStream(selectedImage));
float[] latLong = new float[2];
  boolean hasLatLong = exif.getLatLong(latLong)
   if (hasLatLong) {
      System.out.println("Latitude: " + latLong[0]);
      System.out.println("Longitude: " + latLong[1]);
   }

Have a look at this link for better understanding.
Also, it's better to refer the documentation here.


text:
Q: How can I slove SyntaxError: positional argument follows keyword argument I am trying to run this code here:
threads = [threading.Thread(name='ThreadNumber{}'.format(n),target=SB, args(shoe_type,model,variant)) for size in SizeList for n in range(ThreadCount)]

However this is what my terminal is returning:
   threads = [threading.Thread(name='ThreadNumber{}'.format(n),target=SB, args(s
hoe_type,model,variant)) for size in SizeList for n in range(ThreadCount)]
                                                                           ^

SyntaxError: positional argument follows keyword argument

Is there anyway I can Fix this?
SB is referring a function that I am trying to run.

A: In Python, the order in which we pass (and receive) arguments to a function matters.
Positional arguments come first, variable-length arguments come next, vairable-length keyword arguments come last.
The expected syntax looks like this:
function(arg, *args, **kwargs)

The argument names above are only conventional examples, so a real-world function will look like:
about_user(name, *hobbies, **favorite_foods)

If we call (or receive) with the argument types out of order, we get errors similar to the one you encountered. In your specific case, your keyword arguments are first, when they should be last.
I wrote a small article about *args and **kwargs that has a few more related details and examples.


text:
Q: Memory function for R Shiny Input I have a Shiny app with lots of input files to specify. Each time I reopen my Shiny app, I need to specify all of them again. Is there a way that Shiny remembers the selected files? (Not by writing default values in the code but by clicking on a save button or something similar).

A: You can create a button which saves the values of all the inputs when clicked, and another button which updates the inputs with the saved values.
Here is an minimal example :
library(shiny)

# Global variables
path_to_save <- "save_param.RData"

ui <- fluidPage(

  titlePanel("Hello Shiny!"),
  sidebarLayout(

    sidebarPanel(
      sliderInput(inputId = "bins",
                  label = "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30),
      checkboxGroupInput(inputId = "color",
                         label = "Bins color",
                         choices = c("red", "blue", "green")),

      actionButton(inputId = "save",
                   label = "Save parameters"),
      tags$hr(),
      actionButton(inputId = "apply_save",
                   label = "Load saved parameters")

    ),

    mainPanel(
      plotOutput(outputId = "distPlot")
    )
  )
)

# Define server logic required to draw a histogram ----
server <- function(input, output, session) {

  output$distPlot <- renderPlot({

    x    <- faithful$waiting
    bins <- seq(min(x), max(x), length.out = input$bins + 1)

    hist(x, breaks = bins, col = input$color, border = "white",
         xlab = "Waiting time to next eruption (in mins)",
         main = "Histogram of waiting times")

  })

  observeEvent(input$save,{
    params <- list(bins = input$bins, color = input$color)
    save(params, file = path_to_save)
  })

  observeEvent(input$apply_save,{
    load(path_to_save) # of course you need to add verifications about the existence of the file
    updateSliderInput(session = session, inputId = "bins", min = 1, max = 50, value = params$bins)
    updateCheckboxGroupInput(session = session, inputId = "color", label = "Bins color", choices = c("red", "blue", "green"),
                        selected = params$color)
  })

}

shinyApp(ui, server)

You could upgrade this idea with the possibility of making several savings, naming these savings, chosing the one you want with a selectInput etc ...


text:
Q: jQuery Form Submit Function Ignored On Change I'm trying to execute a function on form submit whenever another html element is changed. However, the function inside my form submit seems to be ignored.
$("element1").change(function(){
    alert("Works!");
    $("#form").submit(function() {
        console.log("Submitted!");
    });
});

The "Works!" alert displays but for some reason it will not print "Submitted!" to the console and I'm unsure why. Is it possible to execute a function within a form submit if it's being triggered by another element ".change" event? Thank you in advance.
EDIT: I forgot to mention, I need my code to invoke a form submission when this field is changed. Ultimately, I'm having users upload a csv and after it's selected from the file explorer it submits the form. I would like to keep the user on the same page after the file is uploaded as well.

A: All you have to do is trigger the submit function like this
$("#form").submit();//Triggers the submit function.

However, the code you have written is not the write way to write it.You don't want submit event to be binded to the form every time the element is changed.
So it can be rephrased as
/*In this case the event binding happens only once*/
$("#form").submit(function() {
    console.log("Submitted!");
});
/*Now simply trigger it when the element is changed*/
$("element1").change(function() {
    alert("Works!");
    $("#form").submit();
});

For you clear understanding have a look at this fiddle


text:
Q: Ecto's fragment Compile Error I'm trying to systematize the act of searching my Postgres JSON columns using Ecto's fragment.
So let's assume I have the following object in the profile column
{
  "first_name": "Margarita",
  "last_name": "Fernandez",
  "rut": "17.754.041-2"
}

and I'm trying to do something like
from(u in Users.User, where: fragment("?->>'first_name' LIKE ?", u.profile, ^("%" <> "Marga" <> "%"))) |> Users.Repo.all

but in a function
def search(field, value) do
    from(u in Users.User, where: fragment("?->>'#{field}' LIKE ?", u.profile, ^("%" <> value <> "%"))) |> Repo.all
end

But I get the following error
** (Ecto.Query.CompileError) fragment(...) expects the first argument to be a string for SQL fragments, a keyword list, or an interpolated value, got: `"?->>'#{field}' LIKE ?"`

I've tried to escape it, interpolated in a previous variable but there's something I'm doing wrong.
Any hints?

A: You can't do string interpolation like that with fragment. In this particular case, you can fix this by putting ? after ->> and putting ^field in the fragment arguments:
fragment("?->>? LIKE ?", u.profile, ^field, ^("%" <> value <> "%"))


text:
Q: List Custom Setting retrieval failing - getValues() + getInstance() both return null. Thoughts? I've been using Custom Settings for a while, and now I'm running into situations where I don't see the results coming back - this setting is one of the first I created, to turn code on & off, although this particular value/reference is new:
The API Name is NxCode_Switch__c, and it has values for Active(Active__c) and Debug(Debug__c), among others.  I reference it the way I've been doing (although I typically use .getValues()):
        NxCode_Switch__c callRefAssociation = NxCode_Switch__c.getInstance('Call Reference processing');
        Boolean isActive = (callRefAssociation == null || callRefAssociation.isActive__c == false) ? false : true;
        Boolean bDebug = (callRefAssociation == null || (isActive == false || callRefAssociation.Debug__c == false)) ? false : true;

Pretty straightforward.  Both the code & this particular value of custom setting are in the same Sandbox, but now both getInstance() and getValues() are returning null.
I'm using eclipse, API version 31.0, for what that's worth.


text:
Q: How to get category id in single.php wordpress? I need to get category id in single.php. I tried this:
$cat_ID = get_query_var('cat');
It didn't work. What should I use instead?

A: Use wp_get_post_categories()
Retrieve the list of categories for a post.
<?php wp_get_post_categories( $post_id, $args ) ?>

Be aware that the function returns an array (of category ids) even if you only have one category in your post.
The example below shows how categories are retrieved, and then additional information is retrieved for each category.
$post_categories = wp_get_post_categories( $post_id );
$cats = array();

foreach($post_categories as $c){
    $cat = get_category( $c );
    $cats[] = array( 'name' => $cat->name, 'slug' => $cat->slug );
}

Reference: http://codex.wordpress.org/Function_Reference/wp_get_post_categories
Another Option:
Use get_the_terms();
<?php
    $id = get_the_id();
    $terms = get_the_terms( $id, 'category' );
    // print_r( $terms );
    foreach($terms as $term) {
        echo $term->cat_ID;
    }
?>

A: You can simply use
$categories = get_the_category();

to get the assigned categories.


text:
Q: Navigation Engine not able to process request I get the following error in Endeca:
com.endeca.navigation.ENEException: Navigation Engine not able to process
request `http://myhost:15000/search?terms=remote&rank=0&offset=0&irversion=601`

My MDEX version is 6.3.0
The referenced jar files in my app is:
endeca_navigation.jar : Specification-IR-Version: 6.3.0 (Read from MANIFEST file)
endeca_logging.jar: Specification-Version: 6.1.2 (Read from MANIFEST file)
Even with these referenced jars, why is the request parameter still irversion=601?
I'm using java 1.5 and building my app in eclipse. At first, it was referencing older jar files (601), but i removed those completely and replaced them with the newer jar files listed above. I've rebuilt my app and I still see the parameter irversion=601. I've been trying to find out what the issue is for a few hours, but i'm having no luck.
Any ideas?

A: If nothing else I think that you need an N=0 parameter for you request to work.
Also if you are using an application server like Weblogic to run you app, it has a tendency of caching referenced jars which may have to be cleared for it to pick up the new versions of the jars.
Finally if all else fails there is a --back_compat 601 parameter on your dgraph which indicated the accepatble navigation.jar versions. You can use this parameter to determine if the issue is the jar version or something else in between.
Good Luck

A: Additionally to Wiszh's response, it is useful to take a look at the dgraph request query logs (located in /logs/dgraph/Dgraphxx/Dgraphxx.log and .reqlog) which will show a more specific error and the query that caused it.

A: Do your jars match the version of Endeca server you are querying?

A: This issue is due to an old navigation api jar in your class path
Check the ToolsAndFrameworks\version\assembler\lib to get the correct version of navigation api jar. That should fix this issue.

A: correct jar path fixed the issue for me
ToolsAndFrameworks\version\assembler\lib


text:
Q: Use IAM credentials for S3 Maven Repository in Gradle Kotlin DSL I've configured an S3 backed Maven repository per the instructions here, eg:
repositories {
    maven {
        url "s3://myCompanyBucket/maven2"
        authentication {
           awsIm(AwsImAuthentication) // load from EC2 role or env var
        }
    }
}

I am trying to convert my script to use the Kotlin DSL instead of groovy, but can't figure out the equivalent code, specifically for the authentication portion.
What is the equivalent Kotlin DSL for the Groovy snippet above?

A: I just managed to configure a HttpHeaderAuthentication through the following:
maven {
    credentials(HttpHeaderCredentials::class.java) {
        name = "Private-Token"
        value = "xxxxxxx"
    }
    authentication {
        val header by registering(HttpHeaderAuthentication::class)
    }
    url = uri("https://xxxxxxxx/")
}

So I guess yours should be something like
repositories {
  maven {
    url = uri("s3://myCompanyBucket/maven2")
    authentication {
       val awsIm by registering(AwsImAuthentication::class) // load from EC2 role or env var
    }
  }
}

HTH

A: I was able to make it work like this:
maven {
    url = uri("s3://$repoBucketName/release")
    authentication {
        register("awsIm", AwsImAuthentication::class)
    }
}

At least no warnings from unused variables. =)


text:
Q: How many trailing zeroes in $11^{50}-1$? The problem asks us to find how many trailing zeroes there are in decimal representation of $11^{50}-1$. I really don't know how to "attack" this problem. There is a tip that I should try using binomial theorem, but:
$$(1+10)^{50}=\sum_{i=0}^{50}\binom{50}{i}10^i$$
does not look like anything helpful. So how should I use binomial theorem to get something useful?

A: Let $A_n=11^n-1$. Then:
$$ A_{2n} = A_n (A_n+2), $$
$$ A_{5n} = A_n (A_n^4+5A_n^3+10A_n^2+10A_n+5 ),$$
from which, given that $A_1=2\cdot 5$:

$$\forall n\geq 2,\qquad  \nu_2(A_{n}) = 2+\nu_2(n),\qquad \nu_5(A_n)=1+\nu_5(n).$$

The previous identities give:
$$\nu_2(A_{50}) = 2+\nu_2(50) = 3,\qquad \nu_5(A_{50})=1+\nu_5(50) = 3,$$
hence the number of trailing zeroes of $A_{50}$ is $\color{red}{3}$.
Here, as usual, $\nu_p(n)$ stands for $\max\{m\in\mathbb{N}:p^m\mid n\}$.

A: The binomial tip can work.
Take $$11^{50}-1=\sum_{i=\mathbf1}^{50}\binom{50}i10^i$$
Observe that the $i$th term has at least $i$ trailing zeros (could be more if the binomial coefficient has trailing zeros too). This means that the $i$th term will not "fix" any of the $i$ rightmost digits obtained in the first $i-1$ terms.
Your job now is to sum $i$ terms until one of your $i$ rightmost digits is not zero. (Hint: that happens quickly)

A: Here's a tedious solution which only uses the binomial theorem. We want to compute the largest $m$ such that:
$$ 11^{50} - 1 \equiv 0 \pmod{10^m}$$
As you noted:
$$ 11^{50} - 1 = \sum_{i=1}^{50} \binom{50}{i} 10^i $$
In order to find this modulo $10^m$, we can ignore every term after the $m-1$th term. That is:
$$ 11^{50} - 1 \equiv \sum_{i=1}^{m-1} \binom{50}{i} 10^i \pmod{10^m} $$
Time for some arithmetic:
$ \binom{50}{1} 10^1 = 500 $
$$ 500 \equiv 0 \pmod{100} $$
$ \binom{50}{2} 10^2 = 122500 $
$$ 500 + 122500 \equiv 0 \pmod{1000} $$
$ \binom{50}{3} 10^3 = 19600000 $
$$ 500 + 122500 + 19600000 \equiv 3000 \pmod{10000} $$
hence there are 3 trailing zeroes.

A: If you compute the first three terms of the binomial expansion, you get
$$\begin{align}
(1+10)^{50}&=1+50\cdot10+{50\cdot49\over2}100+{50\cdot49\cdot48\over6}1000+(\text{a multiple of }10000)\\
&=1+500+122500+(\text{a multiple of }10000)\\
&=3001+(\text{a multiple of }10000)
\end{align}$$

A: An alternate approach - finding the highest power of $2$ that divides $11^{50}-1$, and then show that the same power of $5$ divides $11^{50}-1$.
Factor $11^{50}-1=(11^{25}-1)(11^{25}+1)$.
$$11^{25}+1\equiv 4\pmod 8\\11^{25}-1\equiv 2\pmod 8$$ so the highest power of $2$ which divides $11^{50}-1$ is $2^3$.
Now you just need to show that $11^{50}-1$ is divisible by $125$. But $11^5\equiv 1\pmod {25}$ and $\frac{11^{50}-1}{11^5-1}=\sum_{k=0}^{9} 11^{5k} \equiv 0\pmod 5$. So $11^{50}-1$ is divisible by $5^3$.
(Why is $11^5-1\equiv 1\pmod {25}$? You can think of it via binomial theorem, $(10+1)^5-1$, or you could think of it as $\mathbb Z_{25}^\times$ being cyclic or order $20$, and $11\equiv 1\pmod 5$ shows that $11$ is a fourth power modulo $25$. Or just work out that $9^4\equiv 11\pmod{25}.$)

A: Hint: How many trailing zeros are there in
$$\begin{pmatrix}50\\37\end{pmatrix}10^{37}?$$
It is certainly true that the $10^{37}$ has $37$ trailing zeros.  Now, consider $$\frac{50!}{37!13!}.$$
The numerator of this fraction is divisible by $5$, $10$ times and by $25$ twice.  Therefore, the numerator is divisible by $12$ 5's.  $37!$ is divisible by $5$ $7$ times and divisible by $25$ once.  This means that $37!$ is divisible by $8$ $5$'s.  Finally, $13!$ is divisible by $5$ twice.  Therefore, the numerator has $12$ factors of $5$ and the denominator has $10$ factors of $5$.  Therefore,  $$\frac{50!}{37!13!}$$
has 2 trailing zeros (you can check that there are enough $2$'s to make this work).
Now, generalize.


text:
Q: Android fixed layout 3/4 + 1/4 I am struggling with android layout settings. I would like to keep the same fixed size no matter what the content is and want to show everything in the center!
---------------------------------
-                       -       -
-                       -       -
-      3/4 (center)     -  1/4  -
-                       -  (ct) -
-                       -       -
-                       -       -
---------------------------------

Here is my layout.xml code, but it not works:
<LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_centerInParent="true"
            android:orientation="horizontal"
            android:weightSum="1" >

         <VideoView
            android:id="@+id/videoView1"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:layout_gravity="center"
            android:layout_weight=".25" />

         <TextView
            android:id="@+id/textView1"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:layout_gravity="center"
            android:layout_weight=".75"
            android:freezesText="false"
            android:includeFontPadding="false"
            android:scrollHorizontally="false"
            android:selectAllOnFocus="false"
            android:text="@string/Runstring" />
         </LinearLayout>

EDIT:
I tried some codes from below and experienced: If I make the @string/Runstring = just an "a" or if I make it "..........LONG STRING........." IT is changing the whole layout! It's not keep the 3/4 + 1/4 ratio! Why is that?

A: change
android:layout_width="fill_parent"

to
android:layout_width="0dp"

layout_weight will work with width set to 0dp. your layout will look like:
 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:orientation="horizontal"
        android:weightSum="4" >

     <VideoView
        android:id="@+id/videoView1"
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:layout_gravity="center"
        android:layout_weight="3" />

     <TextView
        android:id="@+id/textView1"
        android:layout_height="wrap_content"
         android:layout_width="0dp"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:freezesText="false"
        android:includeFontPadding="false"
        android:scrollHorizontally="false"
        android:selectAllOnFocus="false"
        android:text="@string/Runstring" />
     </LinearLayout>

A: The problem with your layout is that you have defined the width of Parent layout as wrap_content you must set this as fill_parent. You are dividing the views into some proportion but you have not set the attribute to parent as fill_parent. Thats why it as not able to divide the screen into the right proportion.
Here is your updated layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1" >

        <VideoView
            android:id="@+id/videoView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight=".25" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight=".75"
            android:freezesText="false"
            android:includeFontPadding="false"
            android:scrollHorizontally="false"
            android:selectAllOnFocus="false"
            android:text="@string/Runstring" />
    </LinearLayout>

</LinearLayout>

A: In code you can  do it like this
metrics = getResources().getDisplayMetrics();
        height = metrics.heightPixels;
        weight = metrics.weightPixels;//RETURNS THE SCREEN WIDTH
  videosView1.setLayoutParams(new LinearLayout.LayoutParams(
                width/4,LinearLayout.LayoutParams.MATCH_PARENT));
  TEXTVIEW1.setLayoutParams(new LinearLayout.LayoutParams(
                3*width/4,LinearLayout.LayoutParams.MATCH_PARENT));

OR IN XML YOU CAN DO IT LIKE THIS
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <VideoView
            android:id="@+id/videoView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="3" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:freezesText="false"
            android:includeFontPadding="false"
            android:scrollHorizontally="false"
            android:selectAllOnFocus="false"
            android:text="@string/Runstring" />
    </LinearLayout>

</LinearLayout>


text:
Q: how to draw with UIGraphicsBeginImageContext() Im trying to generate an image, and have found UIGraphicsBeginImageContext() in the Apple docs which looks perfect. Ive been looking at some Quartz tutorials and in each one they use a custom view to do their drawing which doesn't seem necessary in this case, but i dont know enough to be sure. Whats the best way to do my drawing using UIGraphicsBeginImageContext()?

A: Well, you probably want to use UIGraphicsBeginImageContextWithOptions() and scale=0.0 to get resolution independence, but yes, once you call the function the frameworks will have set up a normal graphics context you can use as in the tutorials. You can get at it with UIGraphicsGetCurrentContext().
When you have finished drawing you will likely want to use UIGraphicsGetImageFromCurrentImageContext()to actually capture what you have drawn.
And don't forget to call UIGraphicsEndImageContext() when finished.


text:
Q: Curl sends but Lambda (Netlify function) forbidden I'm developing a function on Netlify to process a contact form using MailGun as the email sender (via API)
I tested the service by sending from my localhost using curl - fine. But when I invoke the function (again on the localhost) I receive a "forbidden" error. In the function, I've received the same error with and without /messages on the end or the url.
Is my error in the code or does MailGun respond differently to the two different cases - I am using another email provider so I don't have MX records pointing to MailGun.
Here's the curl
curl -s --user 'api:exampleofverylongsecretkey' https://api.eu.mailgun.net/v3/mg.example.com/messages
-F from='Excited User <mailgun@mg.example.com>'
-F to=boreduser@otherexample.com
-F subject='Hello'
-F text='Testing some Mailgun awesomeness!'

Here is the function paired down to basics with hard-coded everything just to get mailgun working
const mailgun = require('mailgun-js');

exports.handler = async (event) =>
{
   const mg = mailgun({
       apiKey: "key-exampleofverylongsecretkey",
       domain: "mg.example.com",
       url: "https://api.eu.mailgun.net/v3/mg.example.com"
   });

   const data = {
       from: 'Name <mailgun@mg.example.com>',
       to: 'bored@otherexample.com',
       subject: 'Worldish',
       text: 'Hello W',
       html: 'HTML'
       };

   return mg.messages().send(data).then(() => ({
       statusCode: 200,
       body: "Your message was sent successfully! We'll be in touch."
   })).catch(error => ({
       statusCode: 422,
       body: `Error: ${error}`
   }));
} ```

ps - I've tried it with 'key-exampleofsecretcode' and 'exampleofsecretcode' and with and without the url and with the url with and without /messages - same result for all

A: Resolved -
First sent successfully from hardcoded sandbox details, then live details - failing when using process.env
Re-installed dotenv - now all working


text:
Q: Exponential curve fitting with a constant Assuming I have the following model:
$$ y(t) = \alpha {e}^{- \beta t} + \gamma + n(t) $$
Where $ n(t) $ is additive white Gaussian noise (AWGN) and $ \alpha, \beta, \gamma $ are the unknown parameters to be estimated.
In this case linearization using the logarithm function won't help.
What could I do?
What would be the ML Estimator / LS Method?
Is there a special treatment to non positive data points?
How about the following model:
$$ y(t) = \alpha {e}^{- \beta t} + n(t) $$
In this case, it would be helpful to use the logarithm function, yet, I could I handle the non positive data?
Thanks.

A: I don't really get what you mean with AGWN, is this simply that $n(t_i)$ are independent with $n(t_i) \sim N(0,\sigma^2)$?
The least squares estimator (which, as usual with a normal model, coincide with maximum likelihood estimator, see eg this answer) is easy to find with numerical methods, here is a piece of R code:
a <- 2; b <- 0.2; c <- -1
t <- seq(-5,10, length=100)
y <- a*exp(-b*t)+c+rnorm(length(t), sd=2)
f <- function(par, t, y) {
  a <- par[1]; b <- par[2]; c <- par[3];
  return(sum((a*exp(-b*t)+c-y)**2 ) ); }
nlm( function(par) f(par, t, y), c(0,0,0))

The result of the last call is
$minimum
[1] 430.8242

$estimate
[1]  2.0875336  0.1961210 -0.8672079

$gradient
[1]  1.301591e-05 -2.745537e-05  2.603429e-05

$code
[1] 1

$iterations
[1] 19

Our initial values (2, 0.2, -1) are estimated by (2.088, 0.196, -0.867). You can get a plot of the data points, the "true model" (red line) and the estimated model (dotted red line) as follows:
plot(t,y)
lines( t, a*exp(-b*t)+c, col="red")
nlm( function(par) f(par, t, y), c(0,0,0))$estimate -> r
lines( t, r[1]*exp(-r[2]*t)+r[3], col="red", lty=2)

Also, be sure not to miss this related question already quoted by whuber in the comments.
A few hints for numerical optimization
In the above code the numerical optimization is done using nlm, a function of R. Here are a few hints for a more elementary solution.
If $b\ne 0$ is fixed, it is easy to find $a$ and $c$ minimizing $f(a,b,c) = \sum_{i=1}^n (a \exp(-b\cdot t_i) +c -y_i)^2$: this a the classical least squares for the linear model.  Namely, letting $x_i = \exp(-b\cdot t_i)$, we find
$$ \begin{array}{rcccl}
a &=& a(b) &=& { n \sum_i y_i x_i - \left( \sum_i y_i \right)\left(\sum_i x_i  \right)\over n \sum x_i^2 - \left(\sum_i x_i \right)^2 }, \\
c &=& c(b) &=& { \sum_i y_i \sum_i x_i^2 - \left( \sum_i y_i x_i \right)\left(\sum_i x_i  \right)\over n \sum x_i^2 - \left(\sum_i x_i \right)^2 }. \\
\end{array}$$
Then set
$$ g(b) = f(a(b), b, c(b)).$$
The optimization problem is now reduced to find the minimum of $g(b)$. This can be done either using Newton method or a ternary search.


text:
Q: How to center a line under a figure I want to put a line to distinguish the graphics from the text in my document.  I found a way to add the line but I want it to be at the same length as the caption and not \linewidth.
Although, when I set it to a fraction of \linewidth it automatically starts from the left edge and I can't put it exactly under the caption.
Here is my code:
\documentclass{memoir}
\usepackage{lipsum}                 %Needed to create dummy text
\usepackage{graphicx}

\newcommand{\botfigrule}{
\vspace*{5pt}{\hrule height0.8pt width 0.9\linewidth}\vspace{1pt}}

% My caption style
\newcommand{\mycaption}[2][\@empty]{
\captionnamefont{\scshape}
\changecaptionwidth
\captionwidth{0.9\linewidth}
\captiondelim{.\:}
\captionstyle[\centering]{}
\setlength{\belowcaptionskip}{10pt}
\ifx \@empty#1 \caption{#2}\else \caption[#1]{#2}
}

\begin{document}
\lipsum[2]

\begin{figure}[h!]
\centering
\includegraphics[width=0.4\textwidth]{images/example.jpeg}
\mycaption{ \lipsum[1]}
\botfigrule
\label{fig:gr_lattice}
\end{figure}

\lipsum[2]

\end{document}

A: The memoir manual has examples of ruled figures (see p. 173 of the documentation). It suffices to use the following as your \botfigrule command:
\newcommand{\botfigrule}{\rule{.9\linewidth}{0.4pt}\vspace{\onelineskip}}

Here's a full example.
\documentclass{memoir}
\usepackage{lipsum}                 %Needed to create dummy text
\usepackage[draft]{graphicx}

\newcommand{\botfigrule}{\rule{.9\linewidth}{0.4pt}\vspace{\onelineskip}}

% My caption style
\newcommand{\mycaption}[2][\@empty]{
\captionnamefont{\scshape}
\changecaptionwidth
\captionwidth{0.9\linewidth}
\captiondelim{.\:}
\captionstyle[\centering]{}
\setlength{\belowcaptionskip}{10pt}
\ifx \@empty#1 \caption{#2}\else \caption[#1]{#2}
}

\begin{document}
\lipsum[2]

\begin{figure}[h!]
\centering
\includegraphics[width=0.4\textwidth]{images/example.jpeg}
\mycaption{ \lipsum[1]}
\botfigrule
\label{fig:gr_lattice}
\end{figure}

\lipsum[2]

\end{document}

A: Here is my solution
\documentclass{article}

\newcommand{\botfigrule}{
  \vspace*{5pt}{\hrule height0.8pt width \textwidth}\vspace{1pt}}

\usepackage{graphicx}

\begin{document}

\begin{figure}[t]
  \centering
  \includegraphics[width=\textwidth]{potatoes.jpg}
  \caption{ very very very very very very very very very very
            very very very very very very very very very very
            very very very very very very very very very very
            very very very very very very very very very very
            long text }
  \label{fig:try}
  \botfigrule
\end{figure}

\end{document}

I just used \textwidth instead of 0.9\linewidth and a \centering in
the figure environment
EDIT:
\documentclass{memoir}
\usepackage{lipsum}                 %Needed to create dummy text
\usepackage{graphicx}

\newcommand{\botfigrule}{
\vspace*{5pt}
\parbox{0.5\textwidth}{
{\hrule height0.8pt width 0.5\textwidth}
}}

% My caption style
\newcommand{\mycaption}[2][\@empty]{
\captionnamefont{\scshape}
\changecaptionwidth
\captionwidth{0.9\linewidth}
\captiondelim{.\:}
\captionstyle[\centering]{}
\setlength{\belowcaptionskip}{10pt}
\ifx \@empty#1 \caption{#2}\else \caption[#1]{#2}
}

\begin{document}
\lipsum[2]

\begin{figure}[h!]
\centering
\includegraphics[width=0.4\textwidth]{potatoes.jpg}
\mycaption{ \lipsum[1]}
\botfigrule
\label{fig:gr_lattice}
\end{figure}

\lipsum[2]

\end{document}


text:
Q: Android: Using several version of the same library for different flavors I'm needing help again with my strange projects ;)
So I'm still building a library, and I need to use libA-1.01.jar and libA-2.1.jar
Of course I don't want them in the same flavor, so I used in my gradle file:
flavorACompile files('libs/libA-1.01.jar')
flavorBCompile files('libs/libA-2.1.jar')

This works fine when compiling with gradlew in command line. But the issue is that my classes don't see both libraries. So when I'm coding I can only import the first one (1.01). So I can't use my IDE to code properly I have to guess emacs style if everything is ok and compile to see...
How can I tell Android Studio that the 2 libraries are present? I tried added them both to compile without flavor (just to force android studio to use them) but it didn't work.
I'm sure there is a simple way to do this, but I can't seem to find it :(


text:
Q: Vertical Hex Grid: Get x rings of tiles surrounding a specific coordinate Problem
What I am trying to do is get x numbers of rings from a specified point, and store those rings in a List<List<HexCoordinate>> where the inner list is a list of all the hexes in that ring and HexCoordinate is a structure defined below
Ideally, I would like to be able to specify the Coordinate, and how many rings out I would like to search and have the algorithm grab the tiles for me.
Images and Attempts
I have a Vertical (Flat Top) Hex Grid that looks like this

In code, each tile is represented by a simple HexCoordinate structure GitHub
public struct HexCoordinate : IEquatable<HexCoordinate>
{
    public int X { get; private set; }
    public int Y { get; private set; }

    public HexCoordinate(int x, int y)
    {
        X = x;
        Y = y;
    }

    public HexCoordinate North() => this + new HexCoordinate(0, -1);
    public HexCoordinate South() => this + new HexCoordinate(0, 1);

    public HexCoordinate West() => this + new HexCoordinate(-1, 0);
    public HexCoordinate East() => this + new HexCoordinate(1, 0);

    public HexCoordinate NorthWest() => this + new HexCoordinate(-1, -1);
    public HexCoordinate NorthEast() => this + new HexCoordinate(1, -1);

    public HexCoordinate SouthWest() => this + new HexCoordinate(-1, 1);
    public HexCoordinate SouthEast() => this + new HexCoordinate(1, 1);

    public bool Equals(HexCoordinate other)
    {
        return X == other.X &&
               Y == other.Y;
    }
    public static HexCoordinate operator +(HexCoordinate one, HexCoordinate two)
    {
        return new HexCoordinate(one.X + two.X, one.Y + two.Y);
    }
}

For my example in particular, I have an image I have drawn out to try and figure this problem out myself

What I have Tried
And because I need to show what I have already tried, this is what I have tried so far
public const int MAX_RINGS = 3;
public List<List<HexCoordinate> GetsRingsWithinHex(HexCoordinate coordinate, int maxRings = MAX_RINGS)
{
    // Attempt One Pseudocode
    // reference: http://gamedev.stackexchange.com/questions/51264/get-ring-of-tiles-in-hexagon-grid
    // int ring = 1
    //   Travel around the ring by traversing N,SE,S,SW,NW,N,NE multiplied by the ring number
    //   ring++
    //      Travel Around ring again
    //      cont until desired ring...

    var hexRings = new List<List<HexCoordinate>>();

    // Add in the current hex to the list
    var currentHex = new List<HexCoordinate>();
    currentHex.add(coordinate);
    hexRings.Add(currentHex);

    // Now go through and add the other rings
    while (hexRings.Count <= maxRings)
    {
        var ring = new List<HexCoordinate>();
        HexCoordinate tempCoordinate = coordinate;
        int currentRingNumber = hexRings.Count;

        // We start off by going north to the correct ring, and then adding it to our list
        for (int i = 0; i < currentRingNumber; i++)
        {
            tempCoordinate = tempCoordinate.North();
        }
        ring.add(tempCoordinate);

        // After that, we proceed to go clockwise around the ring until we come back to the start
        for (int i = 0; i < currentRingNumber; i++)
        {
            tempCoordinate = tempCoordinate.SouthEast();

            // If the ring is an odd number, you need to re-align the coordinates back to where whey should be
            if (IntExtensions.IsOdd(i)) tempCoordinate = tempCoordinate.North();

            ring.add(tempCoordinate);
        }

        // The rightmost segment is east because we can go straight down the required number of times
        for (int i = 0; i < currentRingNumber; i++)
        {
            tempCoordinate = tempCoordinate.South();
            ring.add(tempCoordinate);
        }

        // We utilize Current Ring - 1 because we only want this to run on rings that are greater than 1
        for (int i = 0; i < currentRingNumber - 1; i++)
        {
            tempCoordinate = tempCoordinate.SouthWest();
            ring.add(tempCoordinate);
        }

        // Coming into this statement, we are now at the bottom 3 coordinates.
        // Since our grid is laid out vertically, we can assume that these three hexes will be directly west of eachother
        // So we only have to go west twice to make our way to the next north segment
        for (int i = 0; i < 2; i++)
        {
            tempCoordinate = tempCoordinate.West();
            ring.add(tempCoordinate);
        }

        // We utilize Current Ring - 1 because we only want this to run on rings that are greater than 1
        for (int i = 0; i < currentRingNumber - 1; i++)
        {
            tempCoordinate = tempCoordinate.NorthWest();
            ring.add(tempCoordinate);
        }

        // The left most segment is easy because we can just go straight up
        for (int i = 0; i < currentRingNumber; i++)
        {
            tempCoordinate = tempCoordinate.North();
            ring.add(tempCoordinate);
        }

        // We utilize Current Ring - 1 because we only want this to run on rings that are greater than 1
        for (int i = 0; i < currentRingNumber - 1; i++)
        {
            tempCoordinate = tempCoordinate.NorthEast();

            // If the ring is an even number, you need to re-align the coordinates back to where whey should be
            if (IntExtensions.IsEven(i)) tempCoordinate = tempCoordinate.South();

            ring.add(tempCoordinate);
        }

        // Finally, we add the ring to our system rings and loop until we no longer fit the criteria
        hexRings.Add(ring);
    }

    return hexRings;
}

And in case it is needed, here is my IntExtensions
public static class IntExtensions
{
    public static bool IsBetween(this int num, int low, int high)
    {
        return num >= low && num <= high;
    }

    public static bool IsOdd(this int value)
    {
        return value % 2 != 0;
    }

    public static bool IsEven(this int value)
    {
        return value % 2 == 0;
    }
}

My current problem is that this algorithm works for the 1st and 2nd rings, but once it gets to the third ring (and presumably further if I ran it past 3) the Coordinates along the bottom and corners start to become offset by 1... as can be seen by the output in my console below (with what it should be manually edited by hand)
Ring 0 - System 5, 5

Ring 1 - System 5, 4
Ring 1 - System 6, 5
Ring 1 - System 6, 6
Ring 1 - System 5, 6
Ring 1 - System 4, 6
Ring 1 - System 4, 5

Ring 2 - System 5, 3
Ring 2 - System 6, 4
Ring 2 - System 7, 4
Ring 2 - System 7, 5
Ring 2 - System 7, 6
Ring 2 - System 6, 7
Ring 2 - System 5, 7
Ring 2 - System 4, 7
Ring 2 - System 3, 6
Ring 2 - System 3, 5
Ring 2 - System 3, 4
Ring 2 - System 4, 4

Ring 3 - System 5, 2
Ring 3 - System 6, 3
Ring 3 - System 7, 3
Ring 3 - System 8, 4
Ring 3 - System 8, 5
Ring 3 - System 8, 6
Ring 3 - System 8, 7
Ring 3 - System 7, 8 //(Should be 7, 7)
Ring 3 - System 6, 9 //(Should be 6, 8)
Ring 3 - System 5, 9 //(Should be 5, 8)
Ring 3 - System 4, 9 //(Should be 4, 8)
Ring 3 - System 3, 8 //(Should be 3, 7)
Ring 3 - System 2, 7
Ring 3 - System 2, 6
Ring 3 - System 2, 5
Ring 3 - System 2, 4
Ring 3 - System 3, 4 //(Should be 3, 3)
Ring 3 - System 4, 3

Would anybody be able to help put me in the right direction, or provide me with an algorithm that would allow me to get the rings of hexes? I have personally be stuck on this problem for about a day and a half now and I can't seem to figure this one out.

A: Alright, so I think I may have come up with a solution to my problem. I have tested it up to 4 rings and it is giving me all of the correct hexes in the corresponding rings.
public List<List<HexCoordinate>> GetsRingsSurroundingHex(HexCoordinate coordinate, int maxRings)
    {
        // idea reference: http://gamedev.stackexchange.com/questions/51264/get-ring-of-tiles-in-hexagon-grid
        // int ring = 1
        //   Travel around the ring by traversing N,SE,S,SW,NW,N,NE multiplied by the ring number
        //   ring++
        //      Travel Around ring again
        //      cont until desired ring...

        var hexRings = new List<List<HexCoordinate>>();

        // Add in the current hex to the list
        var currentHex = new List<HexCoordinate>();
        currentHex.Add(coordinate);
        hexRings.Add(currentHex);

        // Now go through and add the other rings
        while (hexRings.Count <= maxRings)
        {
            var ring = new List<HexCoordinate>();
            HexCoordinate tempCoordinate = coordinate;
            int currentRingNumber = hexRings.Count;

            // We start off by going north to the correct ring, and then adding it to our list
            for (int i = 0; i < currentRingNumber; i++)
            {
                tempCoordinate = tempCoordinate.North();
            }
            ring.Add(tempCoordinate);

            // After that, we proceed to go clockwise around the ring until we come back to the start
            for (int i = 0; i < currentRingNumber; i++)
            {
                tempCoordinate = tempCoordinate.SouthEast();

                // If the ring is an odd number, you need to re-align the coordinates back to where whey should be
                if (IntExtensions.IsOdd(i)) tempCoordinate = tempCoordinate.North();

                ring.Add(tempCoordinate);
            }

            // The rightmost segment is east because we can go straight down the required number of times
            for (int i = 0; i < currentRingNumber; i++)
            {
                tempCoordinate = tempCoordinate.South();
                ring.Add(tempCoordinate);
            }

            // We utilize Current Ring - 1 because we only want this to run on rings that are greater than 1
            for (int i = 0; i < currentRingNumber - 1; i++)
            {
                if (currentRingNumber.IsEven())
                {
                    if (i.IsEven())
                        tempCoordinate = tempCoordinate.SouthWest();
                    else
                        tempCoordinate = tempCoordinate.West();
                }
                else
                {
                    if (i.IsEven())
                        tempCoordinate = tempCoordinate.West();
                    else
                        tempCoordinate = tempCoordinate.SouthWest();
                }

                ring.Add(tempCoordinate);
            }

            // Coming into this statement, we are now at the bottom 3 coordinates.
            // Since our grid is laid out vertically, we can assume that these three hexes will be directly west of each other
            // So we only have to go west twice to make our way to the next north segment
            for (int i = 0; i < 2; i++)
            {
                tempCoordinate = tempCoordinate.West();
                ring.Add(tempCoordinate);
            }

            // We utilize Current Ring - 1 because we only want this to run on rings that are greater than 1
            for (int i = 0; i < currentRingNumber - 1; i++)
            {
                if (i.IsEven())
                    tempCoordinate = tempCoordinate.NorthWest();
                else
                    tempCoordinate = tempCoordinate.West();

                ring.Add(tempCoordinate);
            }

            // The left most segment is easy because we can just go straight up
            for (int i = 0; i < currentRingNumber; i++)
            {
                tempCoordinate = tempCoordinate.North();
                ring.Add(tempCoordinate);
            }

            // We utilize Current Ring - 1 because we only want this to run on rings that are greater than 1
            for (int i = 0; i < currentRingNumber - 1; i++)
            {
                if (currentRingNumber.IsEven())
                {
                    if (i.IsEven())
                        tempCoordinate = tempCoordinate.East();
                    else
                        tempCoordinate = tempCoordinate.NorthEast();
                }
                else
                {
                    if (i.IsEven())
                        tempCoordinate = tempCoordinate.NorthEast();
                    else
                        tempCoordinate = tempCoordinate.East();
                }

                ring.Add(tempCoordinate);
            }

            // Finally, we add the ring to our system rings and loop until we no longer fit the criteria
            hexRings.Add(ring);
        }

        return hexRings;
    }


text:
Q: SQL Teradata- Syntax error while removing duplicates using row_number() over I need to delete duplicates from a table. I've tried to do this following exactly the code from this website as well as this
    WITH cte (Id,
    Proname,
    Cityname,
    Companyname,
    ItemsNo,
    row_num)
    AS (SELECT
    Id,
    Proname,
    Cityname,
    Companyname,
    ItemsNo,
    ROW_NUMBER() OVER
    (PARTITION BY
    Id,
    Proname,
    Cityname,
    Companyname
    ORDER BY
    Id,
    Proname,
    Cityname,
    Companyname) AS row_num
    FROM dba.tabdupes)
    DELETE FROM cte
    WHERE row_num > 1;

but every time I'm getting a syntax error in Teradata:
[3707]syntax error expected something like a 'SELECT' keyword or '(' or a 'TRANSACTION TIME' keyword or a 'VALIDRIME' keyword between ')' and the 'DELETE' keyword.
I've tried multiple solutions but can't get what is wrong here.

A: There is no way to DELETE "all but one" row from a set of duplicate rows in a table. You can eliminate duplicates within the result set of a SELECT, and INSERT the result into a second table.
Teradata's special "SET" tables will also quietly remove entirely duplicate rows when you do an INSERT ... SELECT though whether that performs well depends on how unique the primary index values are in the target table.

A: Teradata is not SQL server.
You could try following approach
But before you run the cede
make a Backup of your database, or make da test database to run  tessif the query does make that what you want
DELETE dba.tabdupes
 FROM (
    SELECT
    Id, Proname, Cityname,  Companyname, ItemsNo
    , ROW_NUMBER() OVER
    (PARTITION BY Id, Proname, Cityname, Companyname ORDER BY Id, Proname, Cityname, Companyname) AS row_num
    FROM dba.tabdupes) AS d, edba.tabdupes t
    WHERE t.id = d.id
 AND   row_num = 1


text:
Q: Android - NetworkSecurityConfig: No Network Security Config specified, using platform default I have an event on a Button which makes a HttpURLConnection in order to access an API Service which is on my local server to retrieve a JSON. When I click the Button it gives me :
"D/NetworkSecurityConfig: No Network Security Config specified, using platform default"
But then when I press again the Button it gives me the JSON string. So my question is : how do I make it to give me the JSON the first time I press the Button without pressing it 2 times.
This is the code
        URL url = new URL(params[0]);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.setDoInput(true);

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        json = reader.readLine();

        return json;


text:
Q: Does Kubernetes support hundreds PODs in "terminating" status for a week? Our worker service is a long running service. When scale in happen or deployment happen, we expect the PODs can finish existing works (max alive 1 week) then exit.
What I have tried is I make a deployment with 10 pods and set terminationgraceperiodseconds = 604800, and then scale down instance to 1, that works good.
Question here is our service will have hundreds POD, which means worse case is hundreds pod will be in terminating status, run 7 days then exit. Is this workable in K8s world, or any potential issue?
Thank you if any comment~

A: Google starts and destroys over 7 billion pods per week. This is the purpose they were made for. As long as you are persisting the necessary data to disk, Kubernetes will replicate the state of the pod exactly as you have configured. A paper has also been published on how this scale may be achieved.


text:
Q: Three.js Raycaster intersectObjects too slow? I'm writing a Three.js prototype for interacting with objects using the Leap Motion. Each frame (or regularly anyway), I want to check if the representation of the user's finger is above or beneath an object in the scene.
I've done this with the code below, but the intersectObject call is taking about 200 milliseconds, even though it's just testing one object. This is causing the animation to slow down and become very jerky (I've tried doing it e.g. once every 20 frames instead of every frame, but then it still jerks every 20 frames).
Is there a way to do this quicker? Am I doing something wrong? How do other people deal with this?
Thanks!
Code:
...

var filepath = '../models/Scissors.js';

loader.load(filepath, function(geometry, materials) {

  scissors = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial(materials) );
  scene.add( scissors );

});

...

function update() {

  ...

  // NB. Sphere1 has been positioned to represent the user's index finger
  // in 3D space

  var vector = sphere1.position.subSelf( camera.position );

  var ray = new THREE.Raycaster( camera.position, vector.clone().normalize() );

  var start = new Date().getTime();

  var collisions = ray.intersectObjects( [scissors] );

  // Takes about 200ms
  console.log('Took ' + (new Date().getTime() - start) + ' ms' );

  if( collisions.length > 0 ) {
    console.log('HIT!');
  }

  ...

  requestAnimFrame(update);

}

A: Silly me, of course the reason it's slow is because the scissors object is a non-trivial model. Now I'm containing it within an invisible cube and testing against that instead. And it's super fast now (0-1 milliseconds) :-)


text:
Q: How to find the limit $\lim_{x \to 0} \frac{1-\sqrt{1-x^2}}{x}$? Not sure where to even start at this one. I think I could get it to this form:
$$\lim_{x \to 0} \frac{1-\sqrt{(x+1)(x-1)}}{x}$$
Why cant I do this any further?
EDIT:
That square root really messes me up often and I get confused about what to do next when I see it

A: \begin{eqnarray}
\lim_{x\to0}\frac{1-\sqrt{1-x^2}}{x}&=&\lim_{x\to 0}\frac{(1-\sqrt{1-x^2})(1+\sqrt{1-x^2})}{x(1+\sqrt{1-x^2})}=\lim_{x\to 0}\frac{1-(1-x^2)}{x(1+\sqrt{1-x^2})}\\
&=&\lim_{x\to0}\frac{x^2}{x(1+\sqrt{1-x^2})}=\lim_{x\to0}\frac{x}{1+\sqrt{1-x^2}}=0.
\end{eqnarray}

A: $$ \frac{1-\sqrt{1-x^2}}{x}= \frac{x^2}{x(1+\sqrt{1-x^2})} $$ Can you take it from there?


text:
Q: Create transparent css border with triangle I'm trying the find a way to have a dynamic border with a triangle. For the moment, with the basic gradient effect, this is what I did:
My current effect in action
But as you can see, the background has a gradient and we can see the border background that does not match..
How can I achieve this effect? Also, the text may vary on different screen size and with other words.
Thank you!

A: To achieve this you can make it with a background image, for exemple http://bootsnipp.com/snippets/featured/carousel-reviews-with-rating.
As you can see he take an image and resize it to take only a triangle like this:
.sprite-i-triangle {
background-position: 0 -1298px;
height: 44px;
width: 50px;
}

Try to find an image that meets your expectations. Otherwise you have some exemples in this site. (http://bootsnipp.com)

A: Using pseudo-elements and skewX is one clean way to achieve this. Check this out, I'm using a top, left & right border on the element, and then style the before as the left bottom border and the after as the right one:

body {
  background-color: white;
  background-image: linear-gradient(45deg, #999 25%, transparent 25%, transparent 75%, black 75%, black), linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, #999 75%, #999);
  background-size: 10px 10px;
  background-position: 0 0, 50px 50px;
}

.dialog {
  text-align: center;
  color: green;
  font-size: 65px;
  width: 300px;
  height: 120px;
  background-color: transparent;
  border-width: 5px 5px 0 5px;
  border-color: red;
  border-style: solid;
  display: inline-block;
  position: relative;
}
.dialog:before {
  content: '';
  border-top: 5px solid red;
  border-right: 5px solid red;
  transform-origin: left top;
  transform: skewX(45deg);
  position: absolute;
  content: ' ';
  height: 10px;
  width: 46%;
  background: inherit;
  left: -5px;
  bottom: -10px;
}
.dialog:after {
  content: '';
  border-top: 5px solid red;
  border-left: 5px solid red;
  transform-origin: left top;
  transform: skewX(-45deg);
  position: absolute;
  content: ' ';
  height: 10px;
  width: 46%;
  background: inherit;
  right: -5px;
  bottom: -10px;
}

Here I am


text:
Q: Warning: Data for foo has hit the 0.0323 GB daily cap and the collection of your app's telemetry data will be stopped until June 23, 2018 9:00 AM UTC I've been getting these alerts lately, however if I search events in my Application Insights account, I only have 5 events in the last 24 hours, and 7 events in the last 48 hours. The largest event contains a 660 characters long message. I doubt these events are close to 33 MB, which is equivalent to 0.0323 GB, right?

Am I misunderstanding something?

A: I found the Application Insights Analytics tool:

In the Analytics page, I noticed not all the tables were included in the query. Once I included the missing tables, I realized that 29,430 performanceCounter events and 88,290 customMetric events have been created in the last 48 hours.
Query:
union (traces
| where timestamp >= datetime(2018-06-22T07:40:59.999Z) and timestamp < datetime(2018-06-24T07:41:00.001Z)), (customEvents
| where timestamp >= datetime(2018-06-22T07:40:59.999Z) and timestamp < datetime(2018-06-24T07:41:00.001Z)), (pageViews
| where timestamp >= datetime(2018-06-22T07:40:59.999Z) and timestamp < datetime(2018-06-24T07:41:00.001Z)), (requests
| where timestamp >= datetime(2018-06-22T07:40:59.999Z) and timestamp < datetime(2018-06-24T07:41:00.001Z)), (dependencies
| where timestamp >= datetime(2018-06-22T07:40:59.999Z) and timestamp < datetime(2018-06-24T07:41:00.001Z)), (availabilityResults
| where timestamp >= datetime(2018-06-22T07:40:59.999Z) and timestamp < datetime(2018-06-24T07:41:00.001Z)), (exceptions
| where timestamp >= datetime(2018-06-22T07:40:59.999Z) and timestamp < datetime(2018-06-24T07:41:00.001Z)), (customMetrics
| where timestamp >= datetime(2018-06-22T07:40:59.999Z) and timestamp < datetime(2018-06-24T07:41:00.001Z)), (performanceCounters
| where timestamp >= datetime(2018-06-22T07:40:59.999Z) and timestamp < datetime(2018-06-24T07:41:00.001Z)), (browserTimings
| where timestamp >= datetime(2018-06-22T07:40:59.999Z) and timestamp < datetime(2018-06-24T07:41:00.001Z))
//| top 101 by timestamp desc
| summarize count() by itemType

Results:
itemType             count_
performanceCounter   29,430
request              2
customMetric         88,290
trace                5

I guess this explains the alert I've been receiving.


text:
Q: How can data be extracted from this kind of JSON format? How can "orderDetails" be extracted from the following JSON payload?
{
    "itemId": "111",
    "count": "20",
    "bookOrders": [
        {
            "bookName": "book1",
            "bookId": "1234",
            "bookPrintDate": "2015-05-18",
            "orderDetails": {
                "chapter1": "description1",
                "chapter2": "description2"
            }
        },
        {
            "bookName": "book2",
            "bookId": "1111",
            "bookPrintDate": "2015-05-20",
            "orderDetails": {
                "chapter1": "description1",
                "chapter2": "description2"
            }
        }
    ]
}

Thanks in advance.

A: Christian's answer is probably the quickest way to do that and it caters for more complex scenarios.
Most of the time I tend to use json2apex to generate the class and the parser for me. Depending on the case, sometimes it's more convenient and scalable.

A: You can use the build in JSON deserializer.
The easiest solution would look like this:
String jsonContent = [YOUR JSON CONTENT];
Object jsonObj = Json.deserialize(jsonContent);
List<Object> bookOrders =(List<Object>) ((Map<String, Object>)jsonObj).get('bookOrders');
for(Object bookOrder : bookOrders)
{
    System.debug(bookOrder.get(orderDetails));
}

Besides from using the json parser you can consider to use JSON Parser.

A: Here is the JSON Parser way:
OrdDetails od;
JSONParser parser = JSON.createParser(jsonString);
while (parser.nextToken() != null) {
    if (parser.getText() == 'orderDetails') {
        while (parser.nextToken() != null) {
            if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                    od = ( OrdDetails)parser.readValueAs(OrdDetails.class);
                    break;
            }
        }
    }
}

System.debug(od);

This depends on there being an OrderDetails object like this:
class OrdDetails{
    String chapter1;
    String chapter2;
}

Looking at the code of the other questions, in this case definitely, I think using deserializeUntyped is going to be quicker and easier to read. As you can see, in my code, there are two nested while loops - not a very maintainable way of parsing JSON!
Anyway, it's here as the other way to do it.


text:
Q: Ruby not iterating through an array that has one element Here is my loop
 subscriptions.each do |s|
     if s.is_active? && s.is_current?
        #do some stuff
     end
  end

subscriptions is an array that has one element. However it does not hit the if statement inside the loop.
When I step through it using rdebug I get this
(rdb:1748) p subscriptions.count
1

I am on ruby version 1.8.7
Am I missing something?
Thank you in advance for your help.

A: Check if it works?
subscriptions.each { |s| puts s }

If above code prints your elements, then there is some issue with your condition i.e. below code is not proper:
if s.is_active? && s.is_current?
  #do some stuff
end

A: The problem ended up being Case sensitivity on some data in the DB. All is good now. It is peculiar that it seemed to have skipped the block, but I am sure it is my own ignorance of how ruby-debug works. I am after all relatively new to ruby/rails development. Thanks all!


text:
Q: In pycharm Pandas Datafram want to highlight specific column with specific color I have following code ,working in Pycharm, It not working is any basic problem? there is many similar questions in stack overflow forum, I have gone through that , I came to conclusion that style function not works in Pycharm I have to switchover to Jupiter Notebook , is it true ? please guide
import pandas as pd
import numpy as np
data =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
#print (data)
def highlight_cols(x):
#copy df to new - original data are not changed
df = x.copy()
#select all values to default value - red color
df.loc[:,:] = 'background-color: red'
#overwrite values grey color
df[['B','C']] = 'background-color: grey'
#return color df
return df
data.style.apply(highlight_cols, axis=None)
print(data)

A: looks like your trying to print it should be
import pandas as pd import numpy as np

df = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))

def color_negative_red(val):
  color = 'red' if val < 0 else 'black'
  return 'color: %s' % color

# from the resource given I assume apply is an actual method, while the resource
# below uses applymap method
styled = df.style.applymap(highlight_cols)
# you previous code, your attempting to print instead of render.
# styled.render() #will return the css styling as string
styled

Personally, I like to use pycharm for personal project while, Colab or junypter I like to run quick. Here's a note book if you want to see the code in action.
https://colab.research.google.com/drive/1deWaFprBv3IB1NNFOHB9ce-ebAOKOBXB?usp=sharing
NOTE: The apply method vs applymap, the usage can be better explained in the resource below. Though, to the point the apply method is expecting an 'axis' not of Null or None; while applymap is expecting a scalar value.
Padas API reference: https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html


text:
Q: Download File in Java Spring rest api I want to download a file and for that I have written this code:
public void downoadResume(@PathVariable("id") int id, HttpServletResponse response) {
try {
    Applicant applicant = applicantService.getOne(id);
    File file = new File(DocumentConstants.DOCUMENTS_PATH + "/" + applicant.getOriginalDocPath());
    // get your file as InputStream
    InputStreamReader is = new InputStreamReader(new FileInputStream(file.getAbsolutePath()));
    // copy it to response's OutputStream
    org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
    is.close();
    response.flushBuffer();
} catch (IOException ex) {
    ex.printStackTrace();
} catch (ResourceNotFoundException e) {
    e.printStackTrace();
}

}

But I am getting this kind of response instead of file, please check:
PK!�?�*��[Content_Types].xml �(���Oo�@��H|k���i�8=��X*���8Y���3i�o��I�RLHs���罟��3��g��G�hc��e5?
�Z|�ߕE?��Q.��P\�޿��7    ��ꀵX�OR�^?WX�?O���"��K����� �&�R�@��VC̦��QkG��3��%��P7�[�Z���Պ�T>�ʥ�9T\�݃+���1�thO�n�����dk�xP���g���&���g��pƦ���V-���3���O��a�?ġ�H���NZ�?c�˓qz�V2Y�3b��k����'��F/}(�i�ߞ`�{��wK�ۦ�]?����Z��w"���߿�r��p�<����g�x!>
��H!�9�}/=
���a�<����#:����� ^ ���gQ'sȒGe7�x���x���h�K��G̻ޑ���9C���o٭��/��PK!���N_rels/.rels �(����JA���a�}7�
"���H�w"����w̤ھ�� �P�^����O֛���;�<�aYՠ؛`G�kxm��PY�[��g
Gΰino�/<���<�1��ⳆA$>"f3��\�ȾT�?I    S?���������W����Y
ig�@��X6_�]7~
f��ˉ�ao�.b*lI�r?j)�,l0�%?�b�
6�i���D�_���,   �   ���|u�Z^t٢yǯ;!Y,}{�C��/h>��PK!����g�word/_rels/document.xml.rels �(����N�0��H�C�;�:`�n@�����N[��U�{{¦u۲K/��G����?���:��*4)K���H�+S��-{��c�#arQ�?�������b�� ��+��E>�q)+���?,AcƟ(�Z?m�!?E|8����`ӽ��<O�?��~�j|���Q�J�#ʥCGJp0�A�W�2a��m��s2~��OG����C��}�W������    a�z֯�n��H��?KG�?���e�cު�"�I�f�'�7,^?�����1r�'�;��*!���Fϔ�}�n,�?���?ܜ`Е��PQ,Q�?K���x߀��)�WT>)�:�88
5���;<oY

Can you please tell me what wrong I have done in this code?

A: You need to set the response headers and content-type which triggers the browser to treat the response content as a file and not as a web page:
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=download.xlsx");

A: It seems that you are downloading an xlsx file, Try the code below:
    public void downoadResume(@PathVariable("id") int id, HttpServletResponse response) {
    try {
        Applicant applicant = applicantService.getOne(id);
        File file = new File(DocumentConstants.DOCUMENTS_PATH + "/" + applicant.getOriginalDocPath());
response.reset();
            response.resetBuffer();
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment; filename=test.xlsx");
        // get your file as InputStream
        InputStreamReader is = new InputStreamReader(new FileInputStream(file.getAbsolutePath()));
        // copy it to response's OutputStream
        org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
        is.close();
        response.flushBuffer();
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (ResourceNotFoundException e) {
        e.printStackTrace();
    }

    }


text:
Q: What is the Difference between HttpContext.Request and Request a .NET Core controller? There are similar questions but they pertain to the legacy .NET Framework.  This question is about the .NET Core.
What is the difference between the two statements below when executed in a controller that inherits from ControllerBase:
var request1 = Request;
var request2 = HttpContext.Request;

A: It's exactly the same instance of the object HttpRequest.
If you want you look the source code of ControllerBase you can see that only difference is the method to access to object.


text:
Q: Metal multisampling results in darkened textures So I'm trying to implement full-screen MSAA in my Metal app. I have it working and when drawing solid-filled polygons the edges appear smooth as expected. However, my textured polygons appear dark, and get darker as I increase the number of samples, indicating that the shader might be taking only one sample of the texture per fragment and blending it with n - 1 samples of black therefore making it darker.
However, in my app I also have textures that I render to and then draw to the screen. These textures show up perfectly fine. I can't really see a difference between the two kinds of textures that would change the behavior of multisampling.
Anyway, if anyone could maybe give me any clues as to what's going on, I would greatly appreciate it. I'm pretty stumped on this one.
EDIT:
Here is how I am setting up all my pipeline state(s)
Here is how the texture pipeline state is set up specifically

A: I figured it out. The problem was that I hadn't set my stencil draw pipeline state to be multisampled. Therefore it was only reading the value in the stencil buffer for 1 out of n samples and hence darkening the output. Works fine now.


text:
Q: Cannot animate a view that is off screen I am animating a view that is off screen with .animate(), but this view will not animate if it is not at least partially on screen. The view should slide up over the entire screen from the bottom.
For example:
If I set the Y-offset to 615 dp which is exactly the height of the visible screen, the view will not animate.
<View
    android:id="@+id/purple_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FF0FF0"
    android:layout_y="615"/>

However, if the view is partilaly visible on screen, even just by 1 dp for example, it will animate
<View
    android:id="@+id/purple_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FF0FF0"
    android:layout_y="614"/>

Now why is this may I ask? Here is the entire layout file
<AbsoluteLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="0dp"
    android:paddingRight="0dp"
    android:paddingTop="0dp"
    android:paddingBottom="0dp"
    tools:context=".MainActivity">

    <View
        android:id="@+id/white_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFFFF0"
        android:layout_y="0dp"
        />

    <View
        android:id="@+id/purple_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FF0FF0"
        android:layout_y=""
        />

</AbsoluteLayout>


text:
Q: 18.04 on MacBook Pro 8-2 is stuck on purple screen when booting For the last 3 days I've been trying to install Ubuntu on a MacBookPro8-2 running High Sierra, in order to run an IOTA node.
I've tried Ubuntu 18.04 into a VM first and I quite like it.
I also can use it when booting from USB drive.
So, I started from a clean install of my MacBook Pro and followed all the tutorials I could find online. The one that appeared to me as the most Beginner friendly was this one, even though its for 16.04. I tried 16.04, but couldn't even install it (from https://www.lifewire.com/dual-boot-linux-and-mac-os-4125733):

*

*Partitioning the SSD

*Creating Bootable USB Drive with Etcher

*Installing rEFInd

*Booting

*nomodeset to prevent getting stuck on Boot

*Installing from "Try Ubuntu without installing"

*Selecting FAT32 partition

*Installing

All these steps are going flawlessly. Then I Restart, and remove USB Drive.
Upon restart I select my Ubuntu install in rEFInd and press Enter. But then I see a black screen with some text in the middle. It does not stay more than a fraction of a second so I can't read it. Then I get the Ubuntu purple background screen, without the logo or login prompt. And it just stays there forever.
I ended up having the same issue regardless which tutorial I was following. I even tried to install Ubuntu as my only OS, removing OS X, ending up with the same problem.
I've tried other post from Stack Exchange saying I should press Shift to access GRUB, but after I select Linux in rEFInd, the purple screen comes instantly. I never managed to get the grub screen.

A: I would recommend following this site https://www.youtube.com/watch?v=GcdhJfe3aP8, it uses different software called Balena Etcher and downloads linux from the official site. It doesn't use rEFInd, so you have to hold option/alt, I have installed around ten linux's and this method has never failed.
EDIT:
Plug in flash drive. Wipe flash drive. download ubuntu here "https://ubuntu.com/download/desktop/thank-you?version=20.04.3&architecture=amd64". Then download balena etcher here. "https://www.balena.io/etcher/". Next, open balena etcher and select the iso image that you downloaded from ubuntu.com, then select flash drive and hit start. When you reboot, hold the option/alt key and wait until a boot screen comes up, select UEFI and hit enter.
EDIT: I wouldn't use rEFInd, because it is manufactured by less people and is updated less often, it also compatible with less computer hardware. I would uninstall that and just hit alt/option key on reboot to enter grub.


text:
Q: how to write a query in orientDB to store array of data How to store and retrieve array of data in orientDB. eg array of hobbies
{
  'hobbies':[
     'cooking',
     'dancing'
  ]
}

A: Try the following:
 INSERT INTO V SET hobbies = [ 'cooking', 'dancing' ]

And
 SELECT FROM V WHERE hobbies CONTAINS 'cooking'


text:
Q: How to fix this error while trying to build a ns3 simulation? I have a simulation called adhoc-simulation.cc in a folder called scratch so it should be running fine, however when I build it using this command sudo ./waf --run adhoc-simulation in the ns-3.33 folder I get this error:
FileNotFoundError: [Errno 2] No such file or directory: '/home/*/ns-3-allinone/ns-3.33/build/ns3/yans-wifi-helper.h'

A: I got the same error using latest version of ns3,I used ./ns3 run filename command,it worked for me.


text:
Q: Converting data type of a column from object to numeric i tried to convert dtype from object to numeric using pd.to_numeric(df.col,errors='coerce')it ran well,but in the next cell when i did df.col the dtype is showing object.what is the problem here.
pd.to_numeric(df.col,errors='coerce')

A: I think you need reassign back column col:
df.col = pd.to_numeric(df.col,errors='coerce')


text:
Q: InternetOpenA EXCEPTION_ACCESS_VIOLATION I do call InternetOpenA in assembler
It is failing with EXCEPTION_ACCESS_VIOLATION on this command:
movdqa xmmword ptr [rsp + 0x20], xmm0

source
start:

    sub rsp,30h

    lea rcx, [userAgent]
    mov rdx,INTERNET_OPEN_TYPE_DIRECT
    mov r8,0
    mov r9,0
    mov qword ptr ds:[rsp+20],0
    call qword ptr ds:[<&InternetOpenA>] <---------------

A: i edit 1st post
its entry point
i will add
sub rsp, 8

and its work
start:

    sub rsp, 8
    sub rsp,30h

    lea rcx, [userAgent]
    mov rdx,INTERNET_OPEN_TYPE_DIRECT
    mov r8,0
    mov r9,0
    mov qword ptr ds:[rsp+20],0
    call qword ptr ds:[<&InternetOpenA>] <---------------

but i dont understand why stack not aligned at start


text:
Q: Is there a way to compact a SQL2000/2005 MDF file? I deleted millions of rows of old data from a production SQL database recently, and it didn't seem to shrink the size of the .MDF file much. We have a finite amount of disk space.
I am wondering if there is anything else I can do to "tighten" the file (like something analogous to Access' Compact and Repair function)?

A: Use the Shrink File option in Sql Server Management Studio
Right-click on Database  > Tasks > Shrink > Database (or Files)

A: DBCC SHRINKDATABASE etc. - read up on transaction logs and backups in the Books Online

A: If large log files are the problem, this may help:
backup log MY_DATABASE WITH TRUNCATE_ONLY;

Then right click on MY_DATABASE and choose All Tasks->Shrink Database as teller suggested.

A: This worked for me and shrank my log files by a thousand.

*

*Using the SQL Server Manager.

*Right Click on the database in question.

*Choose Properties, then the options tab.

*Change the Recovery Model to Simple From Full.

If you need it in full mode switch it back after it shrinks.
    That's it!


text:
Q: How can we filter columns according to a mask for rows which their items are tuples? Let's assume that we have a numpy array which is built like this:
import numpy as np

data = [(1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6)]
data1 = [1 for i in data]

table = np.asarray(list(zip(data, data1, data1, data1, data1))).transpose()

which results in:
[[(1, 2) (1, 3) (1, 4) (1, 5) (2, 1) (2, 2) (2, 3) (2, 4) (2, 5) (2, 6)]
 [1 1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1 1]]

Now there is another list test = [(1, 2), (1, 3), (1, 4)].
I want to filter the columns in the table if the tuples in first row do not match the tuples in test list.
I want it to result like this:
[[(1, 2) (1, 3) (1, 4)]
 [1 1 1]
 [1 1 1]
 [1 1 1]
 [1 1 1]]

I tried this code:
mask = np.in1d(table[0, :], test)
table = table[:, mask]
print(table)

but it resulted an empty list.
Any suggestions?
Thank you

A: #use a bool array to select columns
table[:,np.array([e in test for e in table[0]])]
Out[306]:
array([[(1, 2), (1, 3), (1, 4)],
       [1, 1, 1],
       [1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]], dtype=object)

A: Not quite as elegant, but I find this more intuitive:
tb = set(table[0,:].reshape(table[0,:].size))
table[:,[i for i, t in enumerate(tb) if tuple(t) in test]]