text:
Q: What are the symptomps of tightly coupled objects? When designing an application, when do you know that your objects are tightly coupled? What are the symptomps of tightly coupled objects/codes?

A: Lets take two objects A & B:
For the sake of simplicity lets asume that A has the following properties
Name: String
Age: Integer
DateOfBirth: DateTime
B has the following method:
CreateInstanceOfA(string Name, Integer Age, Datetime DateOfBirth) and returns an instance of A with its values initialized to the method arguments.
Now, suppose you add a new property to A:
StateCode: string
Now you have a problem. Do you update the CreateInstanceOfA to include the new property? If so, you have to change the code everywhere it's referenced to include the new field. If your language of choice supports operator overloading you can add a new method. It may not break compilation, but you still have to update the code. Even worse, you would use the old method and would have to manually set the new property after creation.
Son A & B are really tightly coupled.
It's not the best example but it's a quick way of seeing the possible ramifications of a change in a design

A: You know that your design is tightly coupled when a small change in your design affects a large number of (possible unrelated to your change) classes.
Class D is a class that provides some functionality to other classes.
Class A, Class B and Class C use it directly.
Any change in D can affect A, B and C.
Now suppose we want to enhance D to authenticate any action coming from class A. Not possible without affecting B and C for which we don't care about authenticating. Must refactor the whole thing due to a new requirement.
Other example: access to database directly. Any change in the database used could affect all over the code (if for example you do SQL statements all over without using a DAO).Your business logic would not have changed but the new requirement to switch DB would affect all of your code

A: A rule of thumb would be to count how many other classes a given class refers to. There are several ways to look at this:

*

*Number of imports (Java), usings (C#), includes (C++) etc.

*Number of fields / member variables in a class

*Number of parameters to a method

*Number of indirect type references (eg. a.getB().getC().getD())

A change to any of these types would potentially cause the tightly coupled class to also change.

A: You might be experiencing tight coupling if your objects are :

*

*Hard to change. Symptoms : you need to add if statements into your classes each time you write a new variant of a dependency and want to communicate with it. Your code base has forests of if statements possibly operating on global variables, making it a nightmare to debug and maintain.

*Fragile. Symptoms : a bug in an object can ripple through an unexpected number of other objects across the whole system. It is difficult to predict the consequences of changes you want to make in objects for lack of clear contracts between dependencies.

*Hard to reuse. Symptom : reusing an object in a different context implies dragging along all its dependencies and their details, some of which may be irrelevant to that new context.

*Hard to test. Symptoms : your automated tests need to glue together large clusters of objects before doing anything, which makes them slow as hell. Your tests are brittle - a change in the details of one object ripples through all its dependencies' test setups and they easily get red.

A: The Law of Demeter explains some simple guidelines for a loose coupling.
On the practical side, you may also take a look at Lattix, an Eclipse plugin that help you map and refactor your dependencies


text:
Q: Dynamic filepath in Java (writing and reading text files) Okay, so I want to read a file name myfile.txt and let's say I'll be saving it under this directory:
home/myName/Documents/workspace/myProject/files myfile.txt
hmmm.. I want to know what I should pass on the File(filePath) as my parameter... Can I put something like "..\myfile.txt"? I don't want to hard code the file path, because, it will definitely change if say I open my project on another PC. How do i make sure that the filepath is as dynamic as possible? By the way, I'm using java.
File teacherFile = new File(filePath);

A: You can references files using relative paths like ../myfile.txt. The base of these paths will be the directory that the Java process was started in for the command line. For Eclipse it's the root of your project, or what you've configured as the working directory under Run > Run Configurations > Arguments. If you want to see what the current directory is inside of Java, here's a trick to determine it:
File currentDir = new File("");
System.out.println(currentDir.getAbsolutePath());

A: You can use relative paths, by default they will be relative to the current directory where you are executing the Java app from.
But you can also get the user's home directory with:
String userHome = System.getProperty("user.home");

A: You can do it:
File currentDir = new File (".");
String basePath = currentDir.getCanonicalPath();

now basePath is the path to your application folder, add it the exact dir / filename and you're good to go

A: You can use ../myfile.txt However the location of this will change depending on the working directory of the application.  You are better off determining the base directory of you project is and using paths relative to that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sending emails with any kind of attachments I want to add an attachment (be it a link,image, video or anything else) along with the text that I send through email. Till now, I can only send the plain text as email. How do I add an attachment along with it?
Here's my code for sending the email process in the worker thread:
public class GMailSender extends AsyncTask<Void,Void,Void> {

//Declaring Variables
private Context context;
private Session session;

//Information to send email
private String email;
private String subject;
private String msg;

//Progressdialog to show while sending email

//Class Constructor
public GMailSender(Context context, String email, String subject, String msg){
    if (rb1 != null && rad.isChecked()){
        message=s1;
    }else if(rb1 != null && rad1.isChecked())
    {
        message=item;
    }
    //Initializing variables
    this.context = context;
    this.email = s4;
    this.subject = s3;
    this.msg = message;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    //Showing progress dialog while sending email
   // progressDialog = ProgressDialog.show(context,"Sending message","Please wait...",false,false);
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    //Dismissing the progress dialog
    //Showing a success message
    Toast.makeText(context,"Message Sent",Toast.LENGTH_SHORT).show();
}

@Override
protected Void doInBackground(Void... params) {
    //Creating properties
    Properties props = new Properties();

    //Configuring properties for gmail
    //If you are not using gmail you may need to change the values
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    //Creating a new session
    session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                //Authenticating the password
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(Smscreator.EMAIL, Smscreator.PASSWORD);
                }
            });

    try {
        //Creating MimeMessage object
        MimeMessage mm = new MimeMessage(session);

        //Setting sender address
        mm.setFrom(new InternetAddress(Smscreator.EMAIL));
        //Adding receiver
        mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
        //Adding subject
        mm.setSubject(subject);
        //Adding message
        mm.setText(msg);

        //Sending email
        Transport.send(mm);

    } catch (MessagingException e) {
        e.printStackTrace();
    }
    return null;
}
}

Here's the code for sending the mail :
GMailSender sm = new GMailSender(context, s4, s3, message);
    sm.execute();
    Toast.makeText(context, "Email sent :)",
            Toast.LENGTH_SHORT).show();

Edit : As suggested, I've looked into [Sending Email in Android using JavaMail API without using the default/built-in app. But nothing is written about adding an attachment in the solutions.

A: Fix all these common JavaMail mistakes.  Make sure you're using the JavaMail for Android.  And see the JavaMail FAQ for how to send a message with an attachment.  For example, see the sendfile.java sample program.


text:
Q: Why doesn't my method work in DioError catch in Flutter/Dart? I am making a request to my database  like this:
//Airtable (find a record)
  void airtableFind() async {
    try {
      final response = await Dio().get(
        'https://api.airtable.com/v0/'+projectBase+'/'+recordName,
        queryParameters: {
          'filterByFormula': 'SEARCH('+'"'+username+'"'+',{Name})' // Searches the value 'Cactus' in the {'Short description'} field.
        },
        options: Options(
          contentType: 'Application/json',
          headers: {
            'Authorization': 'Bearer'+' '+apiKey,
            'Accept': 'Application/json',
          },
        ),
      );

      // TODO: Whatever you want to do with the response. A good practice is to transform it into models and than work with them
      // print(response);
      // print(response.data['records'][0]['id']);
      idString = response.data['records'][0]['id'];
      // if (idString.isNotEmpty) (
      //     showInvalidUsernameDialog(context)
      //     // TODO: Need to inform about success
      // );

    } on DioError catch (e) {
      // TODO: Error handling
      if (e.response != null) {
        // print(e.response.data);
        print(e);
        showInvalidUsernameDialog(context);

      } else {
        // print(e.request);
        print(e.message);
        showInvalidUsernameDialog(context);
      }
    }
  }

If my user enters the correct word (username), then everything works correctly. But there is always a risk that a person is mistaken. And I want to indicate this with the showInvalidUsernameDialog(context); dialog box, but for some reason it does not pop up.
I see errors in the console:
I/flutter(4484): DioError [DioErrorType.response]: Http status error [422]
I/flutter ( 4484): Source stack:
I/flutter(4484): #0 DioMixin.fetch(package:dio/src/dio_mixin.dart:488:35)
I/flutter ( 4484): #1 DioMixin.request (package:dio/src/dio_mixin.dart:483:12)
I/flutter ( 4484): #2 DioMixin.patch (package:dio/src/dio_mixin.dart:249:12)
I/flutter(4484): #3 _RouteState.airtableUpdate(package:example/main.dart:1498:36)
I/flutter ( 4484): #4 _RouteState.build.<anonymous closure> (package:example/main.dart:1617:13)
I/flutter ( 4484): #5 _RouteState.build.<anonymous closure> (package:example/main.dart:1612:24)
I/flutter(4484): #6 EditableTextState._finalizeEditing (package:flutter/src/widgets/editable_text.dart:2148:18)
I/flutter(4484): #7 EditableTextState.performAction(package:flutter/src/widgets/editable_text.dart:1999:9)
I/flutter(4484): #8 TextInput._handleTextInputInvocation(package:flutter/src/services/text_input.dart:1746:37)
I/flutter ( 4484): #9 MethodChannel._handleAsMethodCall (package:flutter/src/services/platform_channel.dart:404:55)
I/flutter ( 4484): #10 MethodChannel.setMethodCallHandler.<anonymous closure> (package:flutter/src/services/platform_chan
E/flutter ( 4484): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0
E/flutter ( 4484): #0 List.[] (dart:core-patch/growable_array.dart:264:36)
E/flutter ( 4484): #1 _RouteState.airtableFind (package:example/main.dart:1473:42)
E/flutter ( 4484): <asynchronous suspension>
E/flutter ( 4484):

And that's to be expected, since I'm deliberately entering the wrong username. But I want to get not only a list of errors in the console, but also a dialog box. Why doesn't it appear?
The dialog box call method is correct. I put it in the part of the code that fires when the username is valid. It appears exactly as intended.
But why doesn't this method work in this part of the code?
on DioError catch (e) {
      // TODO: Error handling
      if (e.response != null) {
        // print(e.response.data);
        print(e);
        showInvalidUsernameDialog(context);

      } else {
        // print(e.request);
        print(e.message);
        showInvalidUsernameDialog(context);
      }

And how can I make this dialog appear in case of an error?
Edit 1. _RouteState.airtableFind (package:example/main.dart:1473:42) is referring to idString = response.data['records'][0]['id'];. This happens when my user enters their login incorrectly.

A: Use catch directly and check if its of type DioError. This is a known behaviour.. Its not catching 400 or 500 errors
https://github.com/flutterchina/dio/issues/1198
try{

}catch(e){
 print(e.toString());
}

or
try{
}catch(e){
 if(e is DioError)
 {
 }
}


text:
Q: opencv python copy mask region (black or white pixels) onto a BGR image region In OpenCV python, say we read an image with cv2.imread and get a BGR numpy array. We next generate a mask with the cv2.inRange command. The mask has the same width/height and each mask pixel is either black or white.
I want to copy a region from the mask (taken as an image of black and white pixels) onto a region of the color image.
How do I do that? This does not work
img[10:20,10:20] = mask[10:20,10:20]

Must I convert the mask to BGR image first? If so how?
Edit: I do not want to apply the whole mask to the image as in apply mask to color image. Another way to say what I want: see the mask as a black and white image. I want to copy a region of that image (as a set of black or white pixels) onto another image. The resulting image will be a color image except for one smaller rectangular region that contains only black or white pixels. The result will be similar to if I in photoshop copy a rectangular area of a black/white image and past that rectangle onto an area of a color image.
(I'm new to OpenCV)

A: If you try to do it with a single channel (grayscale) mask directly, the shapes of the array slices will not be the same, and the operation will fail.
>>> img[10:20,10:20] = mask[10:20,10:20]

ValueError: could not broadcast input array from shape (10,10) into shape (10,10,3)

You have to convert the mask to BGR, which will make it 3 channels, like the original image.
>>> bgr_mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
>>> img[10:20,10:20] = bgr_mask[10:20,10:20]


text:
Q: Have a Question to my SQL Query. It always duplicates my id that shoudl be unique Hei guys,
i made a sql query for work but it duplicates my document multiple times.
select
  dokid, doktyp, kontakt_id, verkn_kontakt_id, relatie_id,
  onderwerp, dok_nam,
  dok_bes,betrag, belegnr, gjahr, TANR, old_vertrouw_id,
  erstellt_am, impuser, gebr_bew, docname
from v_dok_xml
inner join corsa7.poststuk on poststuk_id=dokid
inner join v_alle_dokumente on dok_id=dokid
where doktyp in ('RECH','HY_DOK','HY_INT','IM_DOK','IM_INT',
                 'INT_SO','SONST_DOK','VB_DOK','VB_IN')
  and BELEGNR is not null
  and (GJAHR ='2018' or GJAHR is null) and rownum <=50
  and $where
order by erstellt_am desc

$where is for the output
you can click choose two dates and the data between it will get printed


text:
Q: Time-dependent Magnetic Field "Paradox" with Faraday's Law I have encountered a "paradox" while studying electromagnetism and I can't seem to understand where I am messing up.
Consider a uniform, time-dependent magnetic field B(t) = $t^4 \hat{i}$ in some region of space.
By Faraday's Law, there must be some induced electric field due to the changing magnetic field. However, since the magnetic field is uniform, any two points in the space are indistinguishable, so I believe that the electric field must also be uniform everywhere in that region of space. However, if the electric field at a point is independent of its position in space, then the E field must have curl 0.
So by Faraday's Law:
$\nabla \times E = -dB/dt$.
However, as per my above reasoning, the left side of this equation is 0 whereas the right side will be proportional to $t^3$? How can this be?
I have a few guesses as to where I went wrong, but no justification for why they should be true:

*

*Maybe it is impossible to create a perfectly uniform magnetic field that increases with $t^4$? But if so, why would this be impossible?

*Although the electric field is constant (at least per my reasoning) at any instantaneous moment, that constant value will change over time since the $E$ field is proportional to $t^3$. Maybe the time dependence of the $E$-field means something?

A: The left side of the equation will not be $0$. You are being misled by how symmetric the B field is.
One place you might expect to find a uniform time-dependent B field is inside a solenoid. This is a cylindrical region of space, with a current flowing around the cylinder. If you just think about how symmetric the B field is, you might expect no current could generate such a B field.
Likewise, the induced E field is cylindrical.

Picture from https://faculty.uml.edu//Andriy_Danylov/Teaching/documents/L18Ch33InducedEcovered.pdf

A:
However, since the magnetic field is uniform, any two points in the space are indistinguishable, so I believe that the electric field must also be uniform everywhere in that region of space.

This is not so. Any two points are not indistinguishable just because they have the same magnetic field. They are still distinguishable in that they have different position in space.
In a realistic scenario, magnetic field can be made only approximately uniform in a finite region of space. Then the points of space differ in how far they are from the source of the magnetic field or from boundary of that region.
In purely hypothetical case of magnetic field uniform in the whole infinite space, we can only conclude that curl of electric field is uniform. But this does not in any way imply electric field is uniform; on the contrary, it can't be, because then curl would vanish, as you have realized.

A: A uniform magnetic field means that $\vec{B}(r,t)=\vec{cst}$ ,i.e $\frac{d\vec{B}(x,t)}{dt}=\vec{0}$


text:
Q: Java Generics, how to avoid unchecked assignment warning when using class hierarchy? I want to use a method using generic parameters and returning generic result on a class hierarchy.
edit: no SupressWarnings("unchecked") answer allowed :-)
Here is a sample code illustrating my problem:
import java.util.*;

public class GenericQuestion {

    interface Function<F, R> {R apply(F data);}
    static class Fruit {int id; String name; Fruit(int id, String name) {
        this.id = id; this.name = name;}
    }
    static class Apple extends Fruit {
        Apple(int id, String type) { super(id, type); }
    }
    static class Pear extends Fruit {
        Pear(int id, String type) { super(id, type); }
    }

    public static void main(String[] args) {

        List<Apple> apples = Arrays.asList(
                new Apple(1,"Green"), new Apple(2,"Red")
        );
        List<Pear> pears = Arrays.asList(
                new Pear(1,"Green"), new Pear(2,"Red")
        );

        Function fruitID = new Function<Fruit, Integer>() {
            public Integer apply(Fruit data) {return data.id;}
        };

        Map<Integer, Apple> appleMap = mapValues(apples, fruitID);
        Map<Integer, Pear> pearMap = mapValues(pears, fruitID);
    }

      public static <K,V> Map<K,V> mapValues(
              List<V> values, Function<V,K> function) {

        Map<K,V> map = new HashMap<K,V>();
        for (V v : values) {
            map.put(function.apply(v), v);
        }
        return map;
    }
}

How to remove the generic exception from these calls:
Map<Integer, Apple> appleMap = mapValues(apples, fruitID);
Map<Integer, Pear> pearMap = mapValues(pears, fruitID);

Bonus question: how to remove the compilation error if I declare the fruitId Function this way:
Function<Fruit, Integer> fruitID = new Function<Fruit, Integer>() {public Integer apply(Fruit data) {return data.id;}};

I'm very confused about generics when it is dealing with hierarchy. Any pointer to a good resource about the usage of  and  will be greatly appreciated.

A: 2 small changes:
public static void main(final String[] args){

    // ... snip

    // change nr 1: use a generic declaration
    final Function<Fruit, Integer> fruitID =
        new Function<Fruit, Integer>(){

            @Override
            public Integer apply(final Fruit data){
                return data.id;
            }
        };

    // ... snip
}

public static <K, V> Map<K, V> mapValues(final List<V> values,

    // change nr. 2: use <? super V> instead of <V>
    final Function<? super V, K> function){

    // ... snip
}

For reference, read this:

The get-put principle


text:
Q: Update uncommitted data using Hibernate In a transaction, if there's a failure, is it possible to update the uncommitted data and commit instead of rolling back the transaction?

A: Nope. That's not possible, and for very good reasons.
When you get an Exception while flushing the JPA and Hibernate Persistence Context, it's not clear how many entity state transitions have been synchronized, and which state transitions haven't been flushed at all.
Just like an ACID transaction should be atomic, the JPA Unit of Work (Persistence Context) should be atomic as well.
Trying to break this behavior is a data access Design Smell and tels you that there is a better solution to the original problem that led you to this question.


text:
Q: how to fetch commented name on posts in laravel 5.4 i followed the convention to avail the required data with compact method to view
Schema User Table
id,name,email,password

Schema post Table
id,user_id,title,body,photo

Schema comment Table
id,post_id,user_id,comments,photo

in user model
public function post()
  {
      return $this->hasMany(post::class);
  }

 public function comments()
   {
     return $this->hasMany(comment::class);
   }

in post model
Public function User()
{
  return $this->belongsTo('App\User');
}

public function comments()
{
    return $this->hasMany(comment::class);

}

in comment model
public function posts()
{
 return $this->belongsTo('App\post');
}

in controller
$list = User::with('post','comments')->paginate(1);

  return view('dynamic',compact('list'));

in view
@foreach($lists->comments as $comments)
{{$comments->name}}
@endforeach

post showing successfully according to users
and comments showing successfully according to posts
but commented name not showing up // please help
how to make relationship for fetch comments with commented user name
please help thanks in advance

A: change code as below in your view:
@foreach($lists->comments as $comments)
    {{$comments->User->name}}
@endforeach

A: you have to change your code as below
@foreach($lists->comments as $comments)
    {{$comments->posts->user->name}}
@endforeach

or
you need to add relationship to your comment model as below
  Public function User()
{
  return $this->belongsTo('App\User');
}

after that you need to change your code as below
@foreach($lists->comments as $comments)
    {{$comments->user->name}}
@endforeach


text:
Q: Use containsLocation with Fusiontable point layer and drawn polygon I would like to be able to select all points from a fusiontable layer that are within a drawn polygon in google maps api 3.
I know in Google Maps API v3 there is the containsLocation method in geometry library, but I dont know how to extract lat/lon from the fusiontable layer and make a loop that will scan over all the markers in the layer.
Thank you very much if you can help with that.

A: You can extract the data from the FusionTable using the FusionTables API v1.
Example that extracts kml "Points" from a FusionTable and displays them as markers


text:
Q: Pegar dados de relatório XML em PHP Tenho o seguinte relatório no link em XML: http://api.openweathermap.org/data/2.5/weather?q=Armaz%C3%A9m,BR&mode=xml
Gostaria apenas de tratá-lo de uma maneira bem simples, tentei utilizando algo como:
<?php
$xml = simplexml_load_string("http://api.openweathermap.org/data/2.5/weather?q=Armazem,SC&mode=xml");
echo $xml->temperature;
?>

Porém sem sucesso. Qual seria a melhor maneira de lidar com tal relatório?

A: Para acessar o valor no XML você deve chamar o nome da tag e acessar o valor usando foo["value"].
Por exemplo, para:
<city id="3469115" name="Armazém">

Fica:
$xml->city["name"];

Para ler o XML da url informada utilizei o curl da seguinte forma:
<?php

function get_data($url)
{
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/xml; charset=ISO-8859-1"));
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$xml = get_data("http://api.openweathermap.org/data/2.5/weather?q=Armazem,SC&mode=xml");
$xml = simplexml_load_string($xml);
echo $xml->temperature["value"];
?>

A: Possui a maneira com file_get_contents.
<?php
    header ('Content-type: text/html; charset=utf-8');
    $data = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q=Armazem,SC&mode=xml');
    $xml  = simplexml_load_string($data);

    $cityID       = $xml->city['id'];
    $cityName     = $xml->city['name'];
    $cityCoordLon = $xml->city->coord['lon'];
    $cityCoordLat = $xml->city->coord['lat'];
    $cityCountry  = $xml->city->country;
    $citySunRise  = $xml->city->sun['rise'];
    $citySunSet   = $xml->city->sun['set'];

    $temperatureValue = $xml->temperature['value'];
    $temperatureMin   = $xml->temperature['min'];
    $temperatureMax   = $xml->temperature['max'];
    $temperatureUnit  = $xml->temperature['unit'];

    $humidityValue = $xml->humidity['value'];
    $humidityUnit  = $xml->humidity['unit'];

    $pressureValue = $xml->pressure['value'];
    $pressureUnit  = $xml->pressure['unit'];


text:
Q: Viewpager on kindle shows gray overlay when swipe between pages I have implemented viewpager with some webviews as its child (using PagerAdapter). When I run this in Kindle devices (I have tested with Kindle HD) during swipe I see a gray overlay during page transition and it disappear when transition finish. I do not have any custom animation. Same thing I run in Nexus 7 and there is no gray overlay which is expected behavior.
My webview initialization as follows:
@Override
public Object instantiateItem(ViewGroup container, final int position) {
    WebView webView = new WebView(this.ctx);
    webView.setWebViewClient(new MyWebViewClient());
    webView.setVerticalScrollBarEnabled(false);
    webView.setVerticalFadingEdgeEnabled(false);
    webView.setInitialScale(100);
    webView.setHorizontalFadingEdgeEnabled(false);
    webView.setHorizontalScrollBarEnabled(false);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    webView.setBackgroundColor(Color.WHITE);
    webView.setDrawingCacheBackgroundColor(Color.WHITE);

    webView.getSettings().setBuiltInZoomControls(false);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setSupportMultipleWindows(false);
    container.addView(webView);

    loadAsyncData(webView, position);

    return webView;
}

Has anyone faced this problem? Any suggestions to solve this problem?

A: Found the root cause. Its the default background on Kindle Fire.


text:
Q: I want to get info of each payments of a subscription in authorized.net Arb api I have been able to create a subscription , update subscription upto a lebel , delete / cacel a subscription and get status of a subscription !
But I want to verify if customer has been charged every month for this subscription .For that all payments details under that subscription .Is there anyway to do that ?
Thanks in advance :)

A: You can use Silent Post. This is Authorize.Net's version of Paypal's IPN.
(I am the author of that article)


text:
Q: How to pass form data to another page in Laravel I need some help in my laravel application with passing the values from a form though to another page. I have a table with data on area objects, and I want to be able to select two (or more) area objects, and then view those in a new page.
In my index.blade.php I have the hollowing form:
<form method = "POST" action="/areas/comparison" id="preferencesForm" class="form-group">
    !{csrf_field()}!

                    Select
                    Area
                    Overall Score
                    Housing Affordability Ratio
                    Mean House Price
                    Crime Level
                    Green Space
                    Good GCSE's
                    Number of Pubs & Restaraunts:
                    Superfast Broadband

            @foreach ($areas as $area)

                    <input type="checkbox" name="area[]" value="!{$area->id}!">
                    id}!">!{$area->name}!
                    !{Helpers::calculateOverallScore($area)}!
                    !{$area->housing_affordability_ratio}!
                    £!{$area->mean_house_price_2015}!
                    !{$area->crime}!
                    !{$area->greenspace*100}!%
                    !{$area->five_good_gcses*100}!%
                    !{$area->restaurants}!/km2
                    !{$area->superfast_broadband*100}!%

            @endforeach
        @endif

        <input type="hidden" name="_token" value="{{ csrf_token() }}">
        <input type="submit" id="compare_button" class="btn btn-primary" value="Compare"/>
</form>

And I would like to then go to show_comparison.blade.php and be able to display the data on the two (or more) areas that I selected.
In routes.php I have:
Route::post('/areas/comparison', 'AreasController@show_comparison');

And then in AreasController:
public function show_comparison(Area $area)
{
    $formData = Request::all(); //Get the form data with the facade

    return view('areas.show_comparison', compact('formData'));
}

However when I click submit and it tries taking me to show_comparison.blade.php it returns the error message "Trying to get property of non-object".
Here is show_comparison.blade.php:
    @extends('layout')
@section('content')

    Back

Comparison

Hello, this is the comparison page. !{$formData}!

@stop

Ideally I would like to be able to print the data in the form of !{ area1->name}! and !{area2->name}! according to my selection.
If anyone can show my how I should be passing form selected data through to another page that would be amazing. (Thank you for taking the time to read this.)

A: I was given an answer on another forum. This solution will take the id that the form passes it, then will fetch the corresponding area objects and pass these in an array to the show_comparisons.blade.php view.
public function show_comparison(Request $request)
{

$areas= Area::whereIn('id',$request->area)->get();

    return view('areas.show_comparison', compact('areas'));
}


text:
Q: Pgfplots rounded corners and plot problem I noticed something strange recently when trying to use rounded corners in pgfplots: it totally ruins the plot. See below without rounded corners:

and then with rounded corners:

Here is a minimal example:
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\begin{document}

\begin{tikzpicture}[scale=0.8,trim axis left, trim axis right]
\tikzset{every mark/.append style={scale=0.6}}
\pgfplotsset{legend style={font=\footnotesize}}

\begin{axis}[   grid=both,
            rounded corners,
            ]
    \addplot[samples=100,color=blue,very thick,smooth,domain=-10:10] {cos(x^(3))};
\end{axis}
\end{tikzpicture}

\end{document}

Thanks in advance for your ideas !

A: If you only want the axis lines to be rounded, you need to set the axis line style key. Otherwise, pgfplots applies the rounded corners style to all of the lines it draws, including the plots.
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\begin{document}

\begin{tikzpicture}[scale=0.8,trim axis left, trim axis right]
\tikzset{every mark/.append style={scale=0.6}}
\pgfplotsset{legend style={font=\footnotesize}}

\begin{axis}[   grid=both,
            axis line style={rounded corners},
            ]
    \addplot[samples=100,color=blue,very thick,smooth,domain=-10:10] {cos(x^(3))};
\end{axis}
\end{tikzpicture}

\end{document}


text:
Q: DataTables.net Change dynamic Columns change index order when initialize Hope someone can help me with the following as I am still getting to know DataTables.net
I have the following html table that gets initiated with the DataTables.net library. The Date Columns gets dynamically generated server side, so I never know how many Columns there will be.
The Description must stay as is, but I want to move entire Totals Column next to the Description Column. I also want an option to hide ALL Date Columns with a button if possible.
I really hope someone can point me in the right direction. Please ask if anything is unclear. Thanks in advance.

            Description
            1-Nov-2017
            2-Nov-2017
            3-Nov-2017
            4-Nov-2017
            5-Nov-2017
            Total

            [13] ADDED-3-Nov-2016
            13 463.30
            11 351.90
            29 513.00
            13 642.50
            0.00
            67 970.70

            [16] ADDED-16-Feb-2017
            10 791.60
            3 237.80
            14 054.80
            15 547.90
            0.00
            43 632.10

            [17] ADDED-18-Jul-2016
            20 021.60
            14 083.30
            23 634.40
            19 115.50
            10 230.20
            87 085.00

            [2] AAPSTERT
            20 544.40
            14 900.00
            23 156.30
            13 131.40
            0.00
            71 732.10

            [3] JANA
            11 883.30
            14 948.10
            12 525.10
            15 934.10
            6 824.20
            62 114.80

            [31] ADDED-8-Apr-2016
            32 813.50
            36 833.40
            33 099.10
            17 500.70
            4 295.00
            124 541.70

            [51] ADDED-16-Feb-2017
            6 235.10
            8 213.40
            14 132.40
            8 996.70
            6 105.30
            43 682.90

            [52] ADDED-16-Feb-2017
            5 425.30
            5 422.80
            7 295.80
            6 439.40
            6 458.80
            31 042.10

            [6] ADDED-28-Jul-2016
            10 088.90
            15 562.90
            17 760.70
            11 091.20
            0.00
            54 503.70

            [61] ADDED-16-Feb-2017
            8 346.80
            5 448.00
            16 083.60
            14 548.20
            16 670.60
            61 097.20

            [71] ADDED-28-Aug-2017
            18 956.10
            11 652.70
            24 738.00
            11 238.70
            7 665.90
            74 251.40

            [72] ADDED-8-Apr-2016
            12 277.10
            8 489.90
            13 718.10
            9 860.70
            9 619.10
            53 964.90

            Totals:
            170 847.00
            150 144.20
            229 711.30
            157 047.00
            67 869.10
            775 618.60

Below is the classic ASP server side code, if someone can perhaps help with this.

              Description
              <%if isArray(vntData) then%>
              <%for intX = 0 to DateDiff("d", StartDate, EndDate)%>
              <%=fmtDate(DateAdd("d", intX, StartDate))%>
              <%next%>
              <%end if%>
              Total

            <%
    RowTotal = 0
    GrandTotal = 0
    Striped = False
    if isarray(vntData) then
        dim table
        dim ShowRow

      for intX = 0 to ubound(vntData,2)
            HideRow = ""
            HideClass = ""
            ShowRow = true
            table = ""
            if intX > 0 then

                '- write the value
                if intX MOD (DateDiff("d", StartDate, EndDate) + 1) = 0 then
                    'Total Column
                    if RowTotal > 0 then
                        table = table & "" & formatNumber(RowTotal,2) & "	"
                    elseif RowTotal < 0 then
                        table = table & "" & formatNumber(RowTotal,2) & "	"
                    else
                        table = table & "" & formatNumber(RowTotal,2) & "	"
                    end if
                    'Total Column
                    GrandTotal = GrandTotal + RowTotal
                    table = table & "
"
                    RowTotal = 0
                    table = table & "
"
                    table = table & "" & vntData(0,intX) & "	"
                end if
                if vntData(2,intX) + vntData(3,intX) - vntData(4,intX) > 0 then
                    table = table & "" & formatNumber(vntData(2,intX) + vntData(3,intX) - vntData(4,intX),2) & "	"
                    RowTotal = RowTotal + (vntData(2,intX) + vntData(3,intX) - vntData(4,intX))
                    ColTotal(intX MOD (DateDiff("d", StartDate, EndDate) +1)) = ColTotal(intX MOD (DateDiff("d", StartDate, EndDate) +1)) + (vntData(2,intX) + vntData(3,intX) - vntData(4,intX))
                elseif vntData(2,intX) + vntData(3,intX) - vntData(4,intX) < 0 and Overs = "on" then
                    table = table & "" & formatNumber(vntData(2,intX) + vntData(3,intX) - vntData(4,intX),2) & "	"
                    RowTotal = RowTotal + (vntData(2,intX) + vntData(3,intX) - vntData(4,intX))
                    ColTotal(intX MOD (DateDiff("d", StartDate, EndDate) +1)) = ColTotal(intX MOD (DateDiff("d", StartDate, EndDate) +1)) + (vntData(2,intX) + vntData(3,intX) - vntData(4,intX))
                elseif vntData(2,intX) + vntData(3,intX) - vntData(4,intX) < 0 and Overs = "" then
                    table = table & "0.00	"
                    RowTotal = RowTotal + (0.00)
                    ColTotal(intX MOD (DateDiff("d", StartDate, EndDate) +1)) = ColTotal(intX MOD (DateDiff("d", StartDate, EndDate) +1)) + (0.00)
                else
                    table = table & "" & formatNumber(vntData(2,intX) + vntData(3,intX) - vntData(4,intX),2) & "	"
                end if
          else

                ' First row
                table = table & "
"
                table = table & "" & vntData(0,intX) & "	"
                if vntData(2,intX) + vntData(3,intX) - vntData(4,intX) > 0 then
                    table = table & "" & formatNumber(vntData(2,intX) + vntData(3,intX) - vntData(4,intX),2) & "	"
                    RowTotal = vntData(2,intX) + vntData(3,intX) - vntData(4,intX)
                    ColTotal(0) = vntData(2,intX) + vntData(3,intX) - vntData(4,intX)
                elseif vntData(2,intX) + vntData(3,intX) - vntData(4,intX) < 0 and Overs = "on" then
                    table = table & "" & formatNumber(vntData(2,intX) + vntData(3,intX) - vntData(4,intX),2) & "	"
                    RowTotal = vntData(2,intX) + vntData(3,intX) - vntData(4,intX)
                    ColTotal(0) = vntData(2,intX) + vntData(3,intX) - vntData(4,intX)
                elseif vntData(2,intX) + vntData(3,intX) - vntData(4,intX) < 0 and Overs = "" then
                    table = table & "0.00	"
                    RowTotal = RowTotal + (0.00)
                    ColTotal(0) = ColTotal(0) + (0.00)
                else
                    table = table & "" & formatNumber(vntData(2,intX) + vntData(3,intX) - vntData(4,intX),2) & "	"
                end if
          end if
            response.write(table)
      next
      tableF = ""
      ' last row row total
        'Total Column
        if RowTotal > 0 then
            tableF = tableF & "" & formatNumber(RowTotal,2) & "	"
        elseif RowTotal < 0 then
            tableF = tableF & "" & formatNumber(RowTotal,2) & "	"
        else
            tableF = tableF & "" & formatNumber(RowTotal,2) & "	"
        end if
        'Total Column
        GrandTotal = GrandTotal + RowTotal
        tableF = tableF & "
"

        response.write(tableF)
    %>

            Totals:
            <%for intX = 0 to DateDiff("d", StartDate, EndDate)%>
            <%=formatNumber(ColTotal(intX MOD (DateDiff("d", StartDate, EndDate) +1)),2)%>
            <%next%>
            <%=formatNumber(GrandTotal,2)%>

    <%end if%>


text:
Q: How to import dajaxice? I'm a nooby to django and I tried many hours to get a simple example of dajaxice running, but I don't seem to find the right way to look for the files.
I did and redid installation and tried to find answers in the numerous similar questions on stackoverflow like this one and this one.
I put {% dajaxice_js_import %} in the header of myapp_index.html which prints out as:
<script src="/static/dajaxice/dajaxice.core.js"
    type="text/javascript" charset="utf-8"></script>

but it cannot find this file:

ImproperlyConfigured: The storage backend of the staticfiles finder  doesn't have a valid location.

And the get fails:
GET /static/dajaxice/dajaxice.core.js HTTP/1.1" 500 59

Strangely enough dajax loads:
<script type="text/javascript"
    src="{% static  /static/dajax/jquery.dajax.core.js" %}"></script>

Here's my folder structure:
myproject
----manage.py
----myproject
--------settings.py
--------urls.py
----myapp
--------ajax.py
--------urls.py
--------templates
------------myapp_index.html

I also haven't really understood why we need two urls.py files, but somehow it seems to access myapp_index.html if I put
from django.views.generic.simple import direct_to_template

and then
url(r'^$', direct_to_template, {'template': 'myapp_index.html'}),

in myapp's url patterns.
I also tried uncountable filenames in
python manage.py findstatic dajaxice.core.js

but somehow it doesn't find dajaxice, even though dajaxice is installed and accepted in the settings.py file among the INSTALLED_APPS.
Also python manage.py collectstatic fails for the same reason, but if I understood correctly, I don't event have to make it run as long as I'm on a development server.
I guess I have some basic misunderstanding of the underlying structure. :(
I'm using the prepacked latest ubuntu packages:
django: 1.4.5,
dajaxice: 0.5.5

Thanks in advance for any hint!
here is the template file:
{% load static %}
{% load dajaxice_templatetags %}

<html>
  <head>
    <title>My base template</title>
    {% dajaxice_js_import %}
    <script type="text/javascript" src="{% static "/static/dajax/jquery.dajax.core.js" %}"></script>

<script type="text/javascript">
function my_js_callback(data){
alert(data.message);
}
Dajax;
Dajaxice;
  </script>
 </head>
...
 <button      onclick="Dajaxice.myproject.myapp.sayhello(my_js_callback);">Click here!</button>

I get no Django error, the page shows, but I get this in Firebug:
"NetworkError: 500 Internal Server Error -  http://localhost:8000/static/dajaxice/dajaxice.core.js"

and this:
ReferenceError: Dajaxice is not defined
Dajaxice;

A: It seems that you've messed up your urls.conf. It should contain something like:
url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),

Does it?
Also, the STATICFILES_FINDERS section of your settings.py file should include:
 'dajaxice.finders.DajaxiceFinder',


text:
Q: Expression: _CrtIsValidHeapPointer(block) - Получаю вот такую ошибку:

поискав в интернете, нашел что из-за двойного освобождения памяти, долго искав где я это делаю, я решил полностью закоментировать все деструкторы по очереди что бы найти где ошибка, но после того как я их все закоментировал, ошибка дале продолжает вылазить, потом присмотрелся, а там путь не к моему файлу, ошибка не у меня в коде, а в исходиках?

A: Если нет других ответов, то отвечу то что мне помогло. В итоге, у меня была проблема, что я удалял объект из памяти, но в итоге указатель указывал туда же, и в деструкторе я делал проверку на NULL, которая при удаленном объекте давала истину. В итоге после удаления просто установил указатель на NULL
delete pointer;
pointer = NULL;


text:
Q: Python3 : Azure Key Vault Keys, creating RAS key : TypeError Following example in :
https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-keys
whenever I run the below code :
rsa_key = key_client.create_rsa_key("rsa-key-demo", size=2048)
print(rsa_key.name)
print(rsa_key.key_type)

The key will be created in my Azure keyVult, however I always get the following error :

Traceback (most recent call last): File
  "c:/Users/user/Desktop/azure_keyValut_demo.py", line 152, in rsa_key =
  key_client.create_rsa_key("rsa-key-demo", size=2048) File
  "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\azure\core\tracing\decorator.py",
  line 62, in wrapper_use_tracer return func(*args, **kwargs) # type:
  ignore File
  "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\azure\keyvault\keys_client.py",
  line 131, in create_rsa_key return self.create_key(name,
  key_type="RSA-HSM" if hsm else "RSA", **kwargs) File
  "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\azure\core\tracing\decorator.py",
  line 62, in wrapper_use_tracer return func(*args, **kwargs) # type:
  ignore File
  "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\azure\keyvault\keys_client.py",
  line 96, in create_key
  **kwargs File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\azure\keyvault\keys_shared_generated\v7_0\operations_key_vault_client_operations.py",
  line 96, in create_key deserialized = self._deserialize('KeyBundle',
  response) File
  "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\msrest\serialization.py",
  line 1180, in call data = self._unpack_content(response_data,
  content_type) File
  "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\msrest\serialization.py",
  line 1334, in unpack_content return json.loads(data) File
  "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\json_init.py",
  line 348, in loads 'not {!r}'.format(s.class.name)) TypeError: the
  JSON object must be str, bytes or bytearray, not 'method'

I didn't quite understand why that exception is being thrown.
I found this on stackoverflow but still couldn't understand what's going on:
Why won't python3 load this json string?

The code run successfully with no issues with Python2.7
The exception will be thrown for all key operations (create, delete, get)
It also happens with all Cryptographic operations

A: According to my test, if we use msrest under version 0.6.x, we will get the error.
My test steps are as below
My requirements.txt
azure-common==1.1.23
azure-core==1.1.1
azure-identity==1.1.0
azure-keyvault-keys==4.0.0
certifi==2019.11.28
cffi==1.13.2
chardet==3.0.4
cryptography==2.8
idna==2.8
isodate==0.6.0
msal==1.0.0
msal-extensions==0.1.3
msrest==0.5.5
oauthlib==3.1.0
portalocker==1.5.2
pycparser==2.19
PyJWT==1.7.1
pywin32==227
requests==2.22.0
requests-oauthlib==1.3.0
six==1.13.0
urllib3==1.25.7

My code
from azure.identity import ClientSecretCredential
from azure.keyvault.keys import KeyClient

tenant_id=''
client_id=''
client_secret=''
credential = ClientSecretCredential(tenant_id, client_id, client_secret)
client = KeyClient("https://testkey08.vault.azure.net/", credential)

key = client.create_rsa_key("rsa-key-demo", size=2048)
print(key.name)
print(key.key_type)

So, please update the merest to 0.6.x. The detailed steps are as below

*

*Create project

python -m venv mytestenv # Might be "python3" or "py -3.6" depending on your Python installation
cd mytestenv
source bin/activate      # Linux shells (Bash, ZSH, etc.)
scripts\activate         # Windows shells (PowerShell, CMD)

*install SDK
My requirements.txt
azure-common==1.1.23
azure-core==1.1.1
azure-identity==1.1.0
azure-keyvault-keys==4.0.0
certifi==2019.11.28
cffi==1.13.2
chardet==3.0.4
cryptography==2.8
idna==2.8
isodate==0.6.0
msal==1.0.0
msal-extensions==0.1.3
msrest==0.6.10
oauthlib==3.1.0
portalocker==1.5.2
pycparser==2.19
PyJWT==1.7.1
pywin32==227
requests==2.22.0
requests-oauthlib==1.3.0
six==1.13.0
urllib3==1.25.7
xlrd==1.2.0

pip install -r requirements.txt

*Code

from azure.identity import ClientSecretCredential
from azure.keyvault.keys import KeyClient

tenant_id=''
client_id=''
client_secret=''
credential = ClientSecretCredential(tenant_id, client_id, client_secret)
client = KeyClient("https://testkey08.vault.azure.net/", credential)

key = client.create_rsa_key("rsa-key-demo", size=2048)
print(key.name)
print(key.key_type)


text:
Q: Prove that there exists $E_i, E_j,E_k$ such that $\mu (E_i \cap E_j \cap E_k) \gt 0$ I have two questions to solve :
(1) If $E_1$ and $E_2$ are measurable, show that $|E_1 ∪ E_2| + |E_1 ∩ E_2| = |E_1| + |E_2|$
My Attempt :
We may assume that both $|E_1| , |E_2|\lt + \infty$, or else the result is trivially true.
Otherwise, since
$$(E_1 \cup E_2) - E2 = E_1 - (E_1 \cap E_2),$$
$E_2 \subseteq (E_1 ∪ E_2)$, and $(E1 \cap E_2) \subseteq E_1$,
We have
$|E1 ∪ E2| − |E2| = |E1| − |E1 ∩ E2|$ ,
We need that $|E_1| , |E_2| \lt + \infty $ in order to subtract measures. It is possible to do this problem without
using any subtraction, though.
(2) Let $\{E_n\}_{n=1}^{\infty}$ be a sequence of measurable sets of $[0,1] \subset \mathbb{R}$ with $\sum_{n=1}^{\infty} \mu(E_n) \gt2$. Prove that there exists $E_i, E_j,E_k$ such that $\mu (E_i \cap E_j \cap E_k) \gt 0$
I don't know how to solve the second question, anyone know how to solve this question ?  and how about question number 1, is it true ?


text:
Q: Finding and Listing Duplicate Words in a Plain Text file I have a rather large file that I am trying to make sense of.
I generated a list of my entire directory structure that contains a lot of files using the du -ah command.
The result basically lists all the folders under a specific folder and the consequent files inside the folder in plain text format.
eg:
4.0G    ./REEL_02/SCANS/200113/001/Promise Pegasus/BMB 10/RED EPIC DATA/R3D/18-09-12/CAM B/B119_0918NO/B119_0918NO.RDM/B119_C004_0918XJ.RDC/B119_C004_0918XJ_003.R3D
3.1G    ./REEL_02/SCANS/200113/001/Promise Pegasus/BMB 10/RED EPIC DATA/R3D/18-09-12/CAM B/B119_0918NO/B119_0918NO.RDM/B119_C004_0918XJ.RDC/B119_C004_0918XJ_004.R3D
15G ./REEL_02/SCANS/200113/001/Promise Pegasus/BMB 10/RED EPIC DATA/R3D/18-09-12/CAM B/B119_0918NO/B119_0918NO.RDM/B119_C004_0918XJ.RDC

Is there any command that I can run or utility that I can use that will help me identify if there is more than one record of the same filename (usually the last 16 characters in each line + extension) and if such duplicate entries exist, to write out the entire path (full line) to a different text file so i can find and move out duplicate files from my NAS, using a script or something.
Please let me know as this is incredibly stressful to do when the plaintext file itself is 5.2Mb :)

A: Split each line on /, get the last item (cut cannot do it, so revert each line and take the first one), then sort and run uniq with -d which shows duplicates.
rev FILE | cut -f1 -d/ | rev | sort | uniq -d

A: I'm not entirely sure what you want to achieve here, but I have the feeling that you are doing it in a difficult way anyway :) Your text file seems to contain spaces in files which make it hard to parse.
I take it that you want to find all files whose name is duplicate. I would start with something like:
 find DIR -type f -printf '%f\n' | uniq -d

That means

*

*DIR - look for files in this directory

*'-type f' - print only files (not directories or other special files)

*-printf '%f' - do not use default find output format, print only file name of each file

*uniq -d - print only lines which occur multiple times

You may want to list only some files, not all of them. You can limit which files are taken into account by more rules to find. If you care only about *.R3D and *.RDC files you can use
find . \( -name '*.RDC' -o -name '*.R3D' \) -type f -printf '%f\n' | ...

If I wrongly guessed what you need, sorry :)

A: The following will scan the current subdirectory (using find) and print the full path to duplicate files. You can adapt it take a different action, e.g. delete/move the duplicate files.
while IFS="|" read FNAME LINE; do
    # FNAME contains the filename (without dir), LINE contains the full path
    if [ "$PREV" != "$FNAME" ]; then
        PREV="$FNAME"  # new filename found. store
    else
        echo "Duplicate : $LINE"  # duplicate filename. Do something with it
    fi
done < <(find . -type f -printf "%f|%p\n" | sort -s)

To try it out, simply copy paste that into a bash shell or save it as a script.
Note that:

*

*due to the sort, the list of files will have to be loaded into memory before the loop begins so the performance will be affected by the number of files returned

*the order the files appears after a sort will affect which files are treated as duplicates since the first occurence is assumed to be the original. The -s options ensures a stable sort, which means the order will be dictated by find.

A more straight-forward by less robust robust approach would be something along the lines of:
find . -type f -printf "%20f %p\n" | sort | uniq -D -w20 | cut -c 22-

That will print all files that have duplicate entries, assuming that the longest filename will be 30 characters long. The output differs from the solution above in all entries with the same name are listed (not N-1 entries as above).
You'll need to change the numbers in the find, uniq and cut commands to match the actual case. A number too small may result in false positives.
find . -type f -printf "%20f %p\n" | sort | uniq -D -w20 | cut -c 22-
----------------------------------   ----   ------------   ----------
                |                      |          |               |
   Find all files in current dir       |          |               |
   and subdirs and print out           |    print out all         |
   the filename (padded to 20          |    entries that          |
   characters) followed by the         |    have duplicates       |
   full path                           |    but only look at      |
                                       |    the first 20 chars    |
                                       |                          |
                                 Sort the output          Discard the first
                                                          21 chars of each line

A: I think you are looking for fslint: http://www.pixelbeat.org/fslint/
It can find duplicate files, broken links, and stuff like that.


text:
Q: How are through-hole boards mass-produced? I'm familiar with the manufacturing process of surface mount boards. Chips come on reels (very high volume smaller parts), trays, or tubes. They are loaded into pick-n-place machines. The PCB, with solder paste applied, is put into the machine as well, and the pick-n-place (PnP) will populate the board.
I was wondering how this used to be done/is still done with through hole components. Our classic ¼W resistors and such come with their leads sticking out on a form of tape. How are these put on PCBs in a mass production environment? Is this all manual labour, or are there machines for this as well? I've never seen or heard of machines for this, and I can see their round shape causing headaches for the suction cups on the PnP.
We like to say that "through-hole is dead" and "everything is SMT nowadays", but open up most cheap power supplies or even many audio amplifiers (which often have a handful higher power resistors, transistors, ...) and you have plenty of through-hole parts! Hence I was wondering, just how are these populated in high-volume production?

A: There are through hole assembly machines!
https://www.youtube.com/watch?v=2sm_qdeconI
But not all parts are rigid enough to be handled this way. Most of the through hole parts are assembled by hand before wave solder. Or also soldered by hand. This depends on other conditions, like dual loaded boards, or quality requirements.
Some through hole components can be placed with regular pnp. These are most found in short pin connectors. You can even reflow solder these by using the pin-in-paste method.
Most through hole parts remaining today are high power silicons, LEDs, electrolytic capacitors and connectors. Those will never die.

A: Mass production THT parts are either done with cheap people, or with axial insertion machines. You can find lots of videos on youtube:
https://www.youtube.com/watch?v=CCBST-qk2t8
https://www.youtube.com/watch?v=P17J5RzbsgQ
They pull the part off the bandolier, cut the leads, bend the leads, insert the part, and bend the leads on the opposite side in one stroke.

A: yea in a facility i used to work in that primarily did class 2 and 3 products, we would use what we called a SAPP machine i believe it stands for semi automated pick and place. the programs all had to be done manually, there were rotating bins off to one aide that would rotate to the correct part, the operator would grab 1 part from the open space in the bin, and the table would move to where the part was and highlight it with little led lights. they then had a foot pedal that they would press when they had the part in place, and clinchers from under the board would raise up, cut the leads and clinch them over. you populate entire runs this way and carefully send them to a wave solder machine that would solder the entire board from underneath at once. there is a small caveat to this and that is the smt on the boards had to be populated first, so any smt on the underside of the board had to be heavily masked before the wave solder process


text:
Q: Bootstrap 5 iframe unresponsive height iframe in bootstrap card scales with width but not height how do I make the height responsive as well?

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet"/>

Card title

Some quick example text to build on the card title and make up the bulk of the card's content.

          Go somewhere

A: From the bootstrap documentation: (https://getbootstrap.com/docs/5.2/helpers/ratio/#example)

Wrap any embed, like an , in a parent element with .ratio and an aspect ratio class. The immediate child element is automatically sized thanks to our universal selector .ratio > *.

I also removed the unneeded (hardcoded) width/height attributes.
See sample code below:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" />

Card title

Some quick example text to build on the card title and make up the bulk of the card's content.

          Go somewhere


text:
Q: Proof of every free homotopy class contains a unique minimizing closed geodesic I am trying to read the proof of the theorem:
On any closed hyperbolic $2$-manifold M there is a unique, closed geodesic in any non-trivial free homotopy class.
The reference I am using are these notes. I am unable to follow the argument here. He first considers the deck transformation associated to the homotopy class and then concludes that the transformation has to be a hyperbolic transformation. Then we know that a hyperbolic transformation leaves a geodesic invariant (the geodesic joining the two fixed points). He then says that the image of this geodesic is the require curve. But I am unable to see this. Thanks.

A: To add a few details, suppose that your given non-trivial free homotopy class is represented by a closed path $f : S^1 \to M$.
Consider the universal covering maps $\mathbb{R} \mapsto S^1$ defined by $t \mapsto e^{2 \pi i t}$, choose a locally isometric universal covering map $\mathbb{H}^2 \mapsto M$, and choose a lift $F : \mathbb{R} \to \mathbb{H}^2$.
The hyperbolic transformation $T : \mathbb{H}^2 \to \mathbb{H}^2$ has the property that $T(F(t)) = F(t+1)$.
The geodesic invariant under $T$ has a constant speed parameterization $\gamma : \mathbb{R} \to \mathbb{H}^2$ such that $T(\gamma(t)) = \gamma(t+1)$.
Now simply define a $T$-equivariant homotopy between $F$ and $\gamma$, by moving each point $F(t)$ at constant speed along a geodesic segment to $\gamma(t)$.
This $T$-equivariant homotopy, when projected to $M$, produces a homotopy from $f$ to a constant speed reparameterization of a closed geodesic in $M$.


text:
Q: Creating a new JTable from current JTable view I am working on a project that involves JTable and performing sorting and filtering operations on it. I am done with the sorting and filtering part and now I want to be able to create a new table from the current view of older table.
e.g. If I apply certain filters to my old table, some rows are filtered out. I don't want those filtered out rows in my new table. I figured that I can convert the new row indices to model indices and add the cell values manually to new table's model, but I was wondering if there's any other efficient way to do this?
Following is what I ended up doing:
//this code block will print out the rows in current view
int newRowCount = table.getRowCount();
int newColumnCount = table.getColumnCount();
for (int i = 0; i < newRowCount; i++) {
    for (int j = 0; j < newColumnCount; j++) {
    int viewIndex = table.convertRowIndexToModel(i);
    String value = (String) model.getValueAt(viewIndex, j);
    System.out.print(value + "\t");

    }
    System.out.println();

}

A: no need for any index conversion, simply ask query the table instead of the underlying model
for (int i = 0; i < table.getRowCount(); i++) {
    for (int j = 0; j < table.getColumnCount(); j++) {
        Object value = table.getValueAt(i, j);
        System.out.print(value + "\t");
    }
}

Note: better rename the i/j to row/column for readability, was too lazy ;-)


text:
Q: Upper bounds, infimum and supremum I have a question about bounds and others.
So, question is that:
$D$ is the set $D = \bigl\{ \frac{(-1)^n n}{n+1}\colon n \in \Bbb{N} \bigr\}$.
How to find $\inf(D)$ and $\sup(D)$ and show they do not belong to $D$?
My approach is that:
Clearly, $1$ is an upper bound for $D$. Let $M$ be the upper bound that is less than $1$.
I know that my approach is nothing to talk about but this is all I had. Please help me.

A: You are on the right track.   note that the same argument for sup and inf will work, since this alternates.  The key is to realize that $\frac n {n+1}$ gets as close to 1 as you want.   The easy way to see this is to do the following rewriting:
$$\frac n {n+1}=\frac {n +1 -1} {n+1}=\frac {n+1}{n+1}-\frac 1 {n+1}=1-\frac 1
{n+1}$$
so the positive terms get as close to 1 as you want.   The formal rule for this is called the Archimedean property of the real numbers,  for any $\epsilon>0$  we can find a natural number $n$ such that $\frac 1 n <\epsilon$.
So,  if you had an upper bound that was smaller than 1,  call it D,  we would have
$D<1$,   or $0<1-D$.  Thus,  by the Archimedean property, there is some natural number $n$ such that $\frac 1 n < 1 -D$.
Adding $D$ and subtracting $\frac 1 n$ gets us to $$D<1-\frac 1 n$$, but that contradicts $D$ being an upper bound.  (Technically we have to restrict $n$ to be even due to the alternating nature of the sequence to get the positive side, but that's no issue,  because once you have it works for one $n$, it works for all bigger $n$'s.
Can you mirror this argument for the infimum?


text:
Q: How to extract a single row table data from a pdf using python? I need to extract tabular data from pdfs. Some tables in the pdf comprise of only a single row.
I have been trying to extract the data using camelot library.
Code for extraction using Camelot:
pip install camelot-py[cv] tabula-py here
import camelot
file = 'xyz.pdf'
tables = camelot.read_pdf(file,pages ="all")
tables[6].df

The above code is not able to extract a single row table info.
For instance, in the pdf: https://www.nirfindia.org/nirfpdfcdn/2022/pdf/Engineering/IR-E-U-0306.pdf,
the tool is not able to detect the last table(under the heading Faculty Details) as it consists of only one row.
Can someone suggest a workaround?

A: As you can understand from the docs,
if you want to detect smaller lines, you should increase line_scale parameter (default: 15).
In your case, this command works fine:
tables = camelot.read_pdf(file, pages ="all", line_scale=80)


text:
Q: Fern-wifi-cracker won't install So i tried to install Fern wifi cracker but it won't let me install it and i get this;
root@john:~/Desktop# dpkg -i Fern-Wifi-Cracker_1.6_all.deb
Selecting previously unselected package fern-wifi-cracker.
(Reading database ... 251856 files and directories currently installed.)
Unpacking fern-wifi-cracker (from Fern-Wifi-Cracker_1.6_all.deb) ...
dpkg: dependency problems prevent configuration of fern-wifi-cracker:
 fern-wifi-cracker depends on aircrack-ng; however:
  Package aircrack-ng is not installed.
dpkg: error processing fern-wifi-cracker (--install):
 dependency problems - leaving unconfigured
Processing triggers for bamfdaemon ...
Rebuilding /usr/share/applications/bamf.index...
Processing triggers for desktop-file-utils ...
Processing triggers for gnome-menus ...
Errors were encountered while processing:
 fern-wifi-cracker
root@john:~/Desktop#

Anyone know how i can solve this problem please? Thanks!

A: You have to install aircrack-ng first from the repositories (Synaptic or Ubuntu Software Center, what you prefer). Then try to install fern-wifi-cracker again.


text:
Q: What is the best way to auto-remove .zsh_history after a certain time? I feel like there is no ZSH setup option to auto-remove .zsh_history after a certain time (e.g. older than one month from now). What would be the simplest hack to achieve it?

A: Correct, there are no time-based expiration options for .zsh_history. Probably because any sort of timed expiry requires the EXTENDED_HISTORY format (which includes start time for each command), and EXTENDED_HISTORY is a new(er) feature — newer than most of the expiration options, at least.
Also, zsh functionality doesn't have the best relationship with the fuzzy concept of "time" — just read the restrictions on the time-based globbing flags to appreciate that:

Any fractional part of the difference between  the  access  time and
the current part in the appropriate units is ignored in the
comparison.  For instance, echo *(ah-5) would echo  files
accessed  within  the  last five hours, while echo *(ah+5) would echo
files accessed at least six hours ago,  as  times  strictly between
five and six hours are treated as five hours.

Beyond that, if you have any of the duplicate-removal options turned on, zsh will remove older entries in favor of the newest one, so the list of "old" entries is in constant flux, making time-based expiration trickier.
If you do want to do it, as LSerni says, parsing it yourself is probably the best option. One tricky thing about doing that is, multi-line entries in the history are written out verbatim, meaning on multiple lines — so you can't parse it simply "line-by-line" because some lines aren't history entries, they're continuations.
My other worry is that there's probably no truly safe way to do this except to integrate it with zsh's history-management directly, because any outside code modifying the history file is in constant danger of interference from (or interfering with) a running instance of zsh. I mean, unless you were to write something in bash that only runs when you can't possibly be logged in, like during the single-user portions of the boot or shutdown processes.
This Python code avoids that issue by copying the history to a new file, reading from it, and then writing the entries that pass the cutoff date out to a different new file. The destination file could be changed to .zsh_history to overwrite the original file, but I take no responsibility for any file corruption that may occur.
Entries older than CUTOFF are dropped (I've used 7 days in the example, but you can easily change 7 to 30 or 31 for one month.) It's assumed this is running with $HOME as the working directory.
This also assumes the history is sorted by time, I don't know how safe an assumption that is. (If it's not true, you may end up keeping more entries than intended, because once it hits the first entry timestamped after the cutoff time, everything after is included. So, older entries that come after the first newer one will be accidentally preserved. Which seems like the right kind of incorrect output to favor, vs. possibly dropping anything unintended.)
#!/usr/bin/python3

import shutil
import time
from itertools import dropwhile

CUTOFF = time.time() - (86400 * 7)  # one week ago

hist = []
shutil.copy2(".zsh_history", ".zsh_history.bak")
with open(".zsh_history.bak", "rb") as f:
    for l in f.readlines():
        if l.startswith(b': '):
            # Start of a new history entry
            # Add a new tuple (time, history_line) to the list
            ts = int(l.split(b':')[1])
            hist.append((ts, l))
            continue
        # Continuation line, append it to the previous entry
        prev = hist.pop()
        hist.append((prev[0], b''.join([prev[1], l])))

with open(".zsh_history.new", "wb") as f:
    # Drop list entries while timestamp < CUTOFF,
    # Then write contents of each remaining entry to file
    for l in dropwhile(lambda x: x[0] < CUTOFF, hist):
        f.write(l[1])


text:
Q: Why is still Android Studio using Hello World TextView? Everytime I create a new project in Android Studio, by default I get in my MainActivity, a TextView containing "Hello World", which every single time I need to remove it. Why that? Is there any option that can allow me to create a new project witout it? Thanks!

A:
Everytime I create a new project in Android Studio, by default I get in my MainActivity, a TextView containing "Hello World",

That is because of the specific choices that you made in the new-project wizard. You chose to create an activity, and you chose an activity template that has that particular content.

Is there any option that can allow me to create a new project witout it?

Opt not to create an activity when you create the new project. In other words, in this screen, choose "Add No Activity":


text:
Q: Set Modal window height based upon browser window size using Bootstrap how to set the max-height for the modal window to be 80% of the current browser window size using bootstrap.
Thanks

A: One way to achieve this would be to just use a wrapper. For example you could use code like this:
HTML

CSS
#wrapper {
    height: 80%;
}

So simply you would just put that #wrapper around all of your code (of course after the body), and it would make the max height of all of your content 80%.

A: I think this is what you are trying to do: restrict dialog height.
.modal-dialog {
    position: fixed;
    margin: 0;
    width: 100%;
    height: 80%;
    padding: 0;
}

Example Snippet

body {
  background: #eee;
}
.modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: hidden;
}
.modal .modal-dialog {
  position: fixed;
  margin: 0;
  width: 100%;
  height: 80%;
  padding: 0;
}
.modal-content {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  border: 2px solid #3c7dcf;
  border-radius: 0;
  box-shadow: none;
}
.modal-header {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  height: 50px;
  padding: 10px;
  background: #6598d9;
  border: 0;
}
.modal-title {
  font-weight: 300;
  font-size: 2em;
  color: #fff;
  line-height: 30px;
}
.modal-body {
  position: absolute;
  top: 50px;
  bottom: 60px;
  width: 100%;
  font-weight: 300;
  overflow: auto;
}
.modal-footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  height: 60px;
  padding: 10px;
  background: #f1f3f5;
}
.btn {
  height: 40px;
  min-width: 100%;
  border-radius: 0;
  -webkit-transition: all 300ms ease-in-out;
  -moz-transition: all 300ms ease-in-out;
  -o-transition: all 300ms ease-in-out;
  transition: all 300ms ease-in-out;
}
.btn:focus,
.btn:active,
.btn:active:focus {
  box-shadow: none;
  outline: none;
}
.btn-modal {
  height: 50px;
  width: 100%;
  margin-bottom: 20px;
}
.btn-modal:hover,
.btn-modal:focus,
.btn-modal:active {
  height: 75px;
  color: #fff;
  background: #266080;
  font-size: 20px;
  border-bottom: 10px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}
.btn-primary {
  font-weight: 600;
  font-size: 1.6rem;
  color: #fff;
  text-align: center;
  background: #0791DE;
  border: 1px solid #266080;
  border-bottom: 6px solid #266080;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}
.btn-secondary {
  color: #fff;
  font-weight: 300;
  font-size: 1.6rem;
  text-align: center;
  background: #f00;
  border: 1px solid #fff;
  border-bottom: 3px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}
.btn-secondary:hover,
.btn-secondary:focus,
.btn-secondary:active {
  color: #f00;
  font-weight: 300;
  font-size: 1.6rem;
  text-align: center;
  background: #fff;
  border: 1px solid #f00;
  border-bottom: 3px solid #f00;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}
h1,
h2,
h3 {
  color: #266080;
  line-height: 1.5;
}
h1:first-child,
h2:first-child,
h3:first-child {
  margin-top: 0;
}
p {
  font-size: 1.4em;
  line-height: 1.5;
  color: #266080;
}
p:last-child {
  margin-bottom: 0;
}
::-webkit-scrollbar {
  -webkit-appearance: none;
  width: 10px;
  background: #f1f3f5;
  border-left: 1px solid #d3d9e0;
}
::-webkit-scrollbar-thumb {
  background: #b5c0cb;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

<button class="btn btn-primary btn-modal" data-toggle="modal" data-target="#ehModal">View Fullscreen Modal</button>

          Modal Title

1. Modal Sub-Title

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
          It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
          desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

2. Modal Sub-Title

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
          It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
          desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

3. Modal Sub-Title

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
          It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
          desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

4. Modal Sub-Title

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
          It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
          desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

5. Modal Sub-Title

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
          It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
          desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

        <button class="btn btn-secondary" data-dismiss="modal">Close</button>

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer
    took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset
    sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the
    industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially
    unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy
    text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five
    centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like
    Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type
    and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing
    Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard
    dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
    It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the
    printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,
    but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker
    including versions of Lorem Ipsum.

A: You can do this using max-height: calc(100% - 120px);
I hope this will help.
JSFiddle


text:
Q: C# How to declare a reference variable to store the address of an object I just need a basic understanding of reference variables as I am in a basic class.  My professor wants us to declare a reference variable to store the address of an object and I don't know how to do that or really what that even does.
He did teach us how to do something like this.
    public double Method(ref name)

But I don't get how that's supposed to store the 'address' of the object.
Any explanation is greatly appreciated.

A: Consider the following example:
public static double SeName0(MyType new_name)
{
    new_name = new MyType(); // only new_name reference to a new object
}

public static double SeName1(ref MyType new_name)
{
    new_name = new MyType(); // both name and ref new_name reference to a new object
}

public static void Main()
{
   MyType name;
   SeName0(name); // Do not touch name variable in this local scope
   SeName1(name); // Change name reference to new object
}

Let's imagine a stack program:

The thin arrow shows that ref name takes address of original name and at the same time is a reference to the same object.
If you call only functions on object nothing happens.
But if you change ref name reference to another object then the original reference name changes either.

A: The questions is a bit vague though, he may be simply checking whether you understand reference types and value types in C# which is far more important in my view than understanding the usage of ref keyword on method parameters.
With that it is no harm to mention, value types are stored on the stack and reference types are stored on the managed heap memory. Their address gets stored in the stack as value type and that is called the reference.
Below you instantiate an object, that is reference type and created on the heap. obj1 contains the reference, value of the pointer to the managed heap.
Object obj1 = new Object();
Below you declare another reference type variable called obj2. You do not instantiate it this time, you just assign the value of the obj1 reference to obj2.
Object obj2 = obj1;
And that may be what your prof was asking you. Even if that s not the case still good to know:)


text:
Q: How are the corruptor arrows supposed to work? The descriptive text that displays during map loads says that Corruptor arrows turn a machine hostile to ANY other machine.  However, I just shot a Longleg with a Corruptor arrow, and it was standing right next to another Longleg and it did not turn hostile toward the other.  What am I missing?

A: To corrupt a machine by the use of corruption arrows, you will need to fill up the corruption meter. It will appear once you managed to hit an arrow on your target. The symbol will be a gree circular UI element with a spiral in it.
You will need to hit corruption arrows until the green part is filled up all the way. Then a white ring will appear around it to indicate that the corruption debuff is applied on the enemy.
You will not be able to corrupt machines that are already corrupted in a different way (e.g. in a Corruption Zone). Also, Daemonic Machines are immune to it (those are the ones with purple markings on them). Furthermore notice that different machines may have different resistances to this debuff.
I am not sure, but distance may also affect how much an arrow will fill up the meter.


text:
Q: .scaleAspectFit - filling the blanks with black color I have UIImages that I show in a UIImageView. The UIImageView has the
contentMode = .scaleAspectFit

property. The UIImages show just fine on the UIImageView, but I want to edit the UIImages so that they don't have any blank (transparent) space, and instead fill the blank spaces with a black color, and I want it to do this dynamically, depending on the end-users screen size.
Example:

What I want to do is replace the areas I've drawn in, with a black color, and save it as an UIImage.

A: Simply set backgroundcolor for the uiimageview

A: Set the background Color of the imageView to black
Using imageView outlet
self.imageView.backgroundColor = UIColor.black

Using IB

A: Set black color for imageview as well as set frame equal to frame of main view.
self.imageView.backgroundColor = UIColor.black

For AutoRisize:
self.imageView.frame = self.view.frame

For AutoLayout:
Set leading, trailing, top and bottom constraints with main view (self.view)


text:
Q: Automatically redirect with this.props.history.push() on component I am setting up Authentication of a React App using Firebase. One thing that I would like to ensure is that a user once authenticated cannot go back to the login page.
Ultimately, I feel this could be done by adding a condition to redirect the user to /home when authenticated and visiting the /login page, whils when a user is not authenticated they see the loginForm with something similar to
const LoginPage = () =>
  <AuthUserContext.Consumer>
    {authUser => authUser
      ? <NavigationAuth />
      : <NavigationNonAuth />
    }
  </AuthUserContext.Consumer>

Whereas <AuthUserContext.Consumer> is already working and determining whether the user is authenticated - That works and not my question.
Next if the user is not authenticated, they get
const NavigationNonAuth = () =>
<NonAuthStyle>
  <LoginForm/>
</NonAuthStyle>

and if they are authenticated they get
const NavigationAuth = () =>
<AuthStyle>
  // What goes here to this.props.history.push("/home")
</AuthStyle>

Hopefully that makes sense but my question is how can I create an event inside NavigationAuth to automatically/force redirect the user to /home?

A: Have you considered using react-router for your project as this allows you to use some of their components to put routes in place and use redirecting?
Here's an example of some simple routing and using a custom PrivateRoute component that takes care of showing authenticated routes or not. You'll need to place this in your main app component.
<BrowserRouter>
  <Switch>
    <Route path="/login" component={NavigationNonAuth} />
    <Route exact path="/" component={Home} />
    <PrivateRoute path="/auth" component={NavigationAuth} />
  </Switch>
<BrowserRouter/>

The PrivateRoute component checks if the user is logged in. If not, it will route the user back to the login path by rendering the <Redirect> component from React Router, else it'll render the component provided. In this case NavigationAuth
Here's a working example to see it all in action. (https://codesandbox.io/s/k5j8wm401v)
Also, to understand React Router v4 and it's components better I found this article pretty helpful. (https://css-tricks.com/react-router-4)


text:
Q: SQL Server query Builder wrong? I have a query that I have developed in SQL and runs fine however when I place the query in the SQL Server (or .Net) query builder it builds it wrong. here is an example that is like the query I have written
This is what I write (and works)
Select Case when Table1.[Col 1] is null then Table2.[Col 1] Else Table1.[Col 1] END as 'col1' From
(Select Sum(Table3.[Col 1]) as 'col 1', Table3.[groupby col] from Table3 Group by  Table3.[groupbycol]) as Table1 FULL OUTER JOIN (Select Sum(Table3.[Col 1]) as 'col 1', 'Total' as 'groupby col' from Table3) as Table2 ON Table1.[groupby col] = Table2.[groupby col]

but then if I open this in the sql or asp.net query builder the "improvements" it makes break the query and it now looks something like this
Select
    Case
       when Table1. 'Col 1' is null
         then Table2. 'Col 1'
         Else Table1. 'Col 1'
    END as 'col1'
From
   (Select
        Sum(Table3.[Col 1]) as 'col 1',
        Table3.[groupby col]
    from
        Table3
    group by
        Table3.[groupbycol]) as Table1
FULL OUTER JOIN
   (Select
        Sum(Table3.[Col 1]) as 'col 1',
        'Total' as 'groupby col'
    from Table3 as Table3_1) as Table2 ON Table1. 'groupby col' = Table2. 'groupby col'

which no longer works as it as it replaces [] with ' and adds a space in front of the column name and creates an alias for Table 3 in the second query and then does not assign that alias to the other times the table is used
Anyone knows what is causing this as it may become annoying if every time I open a query builder it may mess up the query
Thanks

A: String literals as column aliases are on the deprecation list for SQL Server. Although not a portable syntax I have always been a fan of the Alias = Expression syntax in SQL Server. Aaron Bertrand makes a pretty good case for it too in his article Bad Habits to Kick : Using AS instead of = for column aliases.
With this in mind I would rewrite the entire query as:
SELECT  Col1 = ISNULL(table1.Col1, table2.Col1)
FROM    (   SELECT  Col1 = SUM(table3.[Col 1]),
                    GroupByCol = Table3.[groupby col]
            FROM    Table3
        ) table1
        FULL OUTER JOIN
        (   SELECT  Col1 = SUM(table3.[Col 1]),
                    GroupByCol = 'Total'
            FROM    Table3
        ) table2
            ON Table1.GroupByCol = Table2.GroupByCol;

Or
SELECT  ISNULL(table1.Col1, table2.Col1) AS Col1
FROM    (   SELECT  SUM(table3.[Col 1]) AS Col1,
                    Table3.[groupby col] AS GroupByCol
            FROM    Table3
        ) AS table1
        FULL OUTER JOIN
        (   SELECT  SUM(table3.[Col 1]) AS Col1,
                    'Total' AS GroupByCol
            FROM    Table3
        ) AS table2
            ON Table1.GroupByCol = Table2.GroupByCol;

I also suspect you can actually achieve the result you are after using ROLLUP:
SELECT  Col1 = SUM(table3.[Col 1]),
        GroupByCol = ISNULL(Table3.[groupby col], 'Total')
FROM    Table3
GROUP BY Table3.[groupby col]
WITH ROLLUP;


text:
Q: TextView looks different on Simulator and iPhone than what I design on Storyboard I have this multiline TextView. I load data into it from Core Data.
I edited text to be Thin Helvetica Neue 36px in White, just like how you see below-right, but it looks so different in simulators. Any idea why?
I'm using Xcode 6 Beta 5

Left: Simulator
Right: Storyboard (what I want)
Bottom: Simulator on iPhone

Thanks!


text:
Q: Random database disconnects with Django and Postgresql in AWS I'm trying to get to the bottom of a problem with Django and database connection errors. At this point I'm after debugging tips as I think the symptoms are too non-specific.
Some background - I've been using this stack, deployed in AWS for many years without issue:

*

*Ubuntu (in this case 20.04 LTS)

*Nginx

*Uwsgi

*Postgresql (v12 in RDS - tried v13 but same errors)

An AWS load balancer sends traffic to the Ubuntu instance, which is handled by Nginx, which forwards on to Django (3.2.6) running in Uwsgi. Django connects to the database using psycopg2 (2.9.1). Normally this setup works perfectly for me.
The issue I have it that the database connection seems to be closing randomly. Django reports errors like this:
Traceback (most recent call last):
  [my code...]
    for answer in q.select_related('entry__session__player'):
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 280, in __iter__
    self._fetch_all()
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 1324, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 51, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql
    cursor = self.connection.cursor()
  File "/usr/local/lib/python3.8/dist-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 259, in cursor
    return self._cursor()
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 237, in _cursor
    return self._prepare_cursor(self.create_cursor(name))
  File "/usr/local/lib/python3.8/dist-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 237, in _cursor
    return self._prepare_cursor(self.create_cursor(name))
  File "/usr/local/lib/python3.8/dist-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/postgresql/base.py", line 236, in create_cursor
    cursor = self.connection.cursor()
django.db.utils.InterfaceError: connection already closed

The location in my code varies. Sometimes (less frequently) I get this too:
Traceback (most recent call last):
  [my code...]
    group = contest.groups.create(restaurant = restaurant, supergroup = supergroup)
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/fields/related_descriptors.py", line 677, in create
    return super(RelatedManager, self.db_manager(db)).create(**kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 453, in create
    obj.save(force_insert=True, using=self.db)
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/base.py", line 726, in save
    self.save_base(using=using, force_insert=force_insert,
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/base.py", line 763, in save_base
    updated = self._save_table(
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/base.py", line 868, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/base.py", line 906, in _do_insert
    return manager._insert(
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 1270, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1416, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/utils.py", line 78, in _execute
    self.db.validate_no_broken_transaction()
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 447, in validate_no_broken_transaction
    raise TransactionManagementError(
django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.

Again, the location in my code varies, and it's not always in a simple create call - sometimes it's bulk_create, sometimes get_or_create. I'm guessing that the underlying cause is probably the same as the 'connection_closed' error but I'm not sure.
So that's what Django tells me. The Postgresql log doesn't contain any errors that coincide in time with the errors reported by Django. The only errors in the log are of this form:
LOG: could not receive data from client: Connection reset by peer

These coincide with uwsgi killing off worker processes (I have a 1000 request limit set for each worker to avoid any potential memory leak issues), so they aren't related.
So Postgresql is reporting no relevant errors - I can only assume that the connection was closed properly, and Django wasn't expecting that. There are no errors in the systemd journal at all on the Ubuntu instance.
I'm unsure how to proceed. I doubt this is a bug in Django but no other component in the system is complaining and it must be a low-level issue. This happens quite rarely, but enough to be a concern - something like 1 in 1000 requests.
Any insights or suggestions of how to investigate this further would be gratefully accepted :)

A: I've figured this out. It's pretty wild, but makes sense.
Fundamentally, the HTTP client is disconnecting early, while the request is still being processed.
uWSGI must be handling the disconnect in a separate thread than the request handler - this is fine because it acquires the Python GIL before calling into Python.
A totally unexpected (to me anyways!) consequence of this is that the close call is simply injected into the request handler's call stack - the request handler code is running, then suddenly execution switches to the HttpResponse close code. I observed this in stack traces during debugging - see this question for the details.
As part of Django's end-of-request handling, the DB connection may be closed if Django thinks it's broken - this happens because an unexpected transaction is in effect - one started by my own code above the injected HttpResponse.close() call.
When the HttpReponse.close() call finishes running and the interpreter returns to my code, the transaction error is raised because the DB connection has been closed.
So really I think this is all as it should be, more or less. It would be nice to have a more specific 'premature close' error rather than the more generic "connection already closed" error, but I'm not sure how you would neatly construct such a thing.