Retrofit fails to download binary file in an Android app – end result is a corrupted file that is larger than expected

I am trying to download PDF files using Retrofit 2 on an Android app written in Kotlin. The snippet below is basically my entire code. Based on my log output, it appears that the file downloads successfully and saves to the intended location.

package com.ebelinski.RetrofitTestApp  import android.app.Application import android.content.Context import android.os.Build import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log import com.google.gson.FieldNamingPolicy import com.google.gson.GsonBuilder import okhttp3.OkHttpClient import okhttp3.ResponseBody import org.jetbrains.anko.doAsync import retrofit2.Call import retrofit2.http.* import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.io.* import java.util.concurrent.Executors import java.util.concurrent.TimeUnit  interface FileService {      @Streaming     @GET     @Headers("Content-Type: application/pdf", "Accept: application/pdf")     fun fileFromUrl(@Url url: String,                     @Header("Authorization") tokenTypeWithAuthorization: String): Call<ResponseBody>  }  class MainActivity : AppCompatActivity() {      val TAG = "MainActivity"      val RETROFIT_CONNECT_TIMEOUT_SECONDS = 60     private val RETROFIT_READ_TIMEOUT_SECONDS = 60     private val RETROFIT_WRITE_TIMEOUT_SECONDS = 60      private val retrofit: Retrofit         get() {             val gson = GsonBuilder()                 .setDateFormat("yyyyMMdd")                 .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)                 .create()              val converterFactory = GsonConverterFactory.create(gson)              val okHttpClient = OkHttpClient.Builder()                 .connectTimeout(RETROFIT_CONNECT_TIMEOUT_SECONDS.toLong(), TimeUnit.SECONDS)                 .readTimeout(RETROFIT_READ_TIMEOUT_SECONDS.toLong(), TimeUnit.SECONDS)                 .writeTimeout(RETROFIT_WRITE_TIMEOUT_SECONDS.toLong(), TimeUnit.SECONDS)                 .addInterceptor { chain ->                     val userAgentValue = "doesn't matter"                     val originalRequest = chain.request().newBuilder().addHeader("User-Agent", userAgentValue).build()                      var response = chain.proceed(originalRequest)                     if (BuildConfig.DEBUG) {                         val bodyString = response.body()!!.string()                         Log.d(TAG, String.format("Sending request %s with headers %s ", originalRequest.url(), originalRequest.headers()))                         Log.d(TAG, String.format("Got response HTTP %s %s \n\n with body %s \n\n with headers %s ", response.code(), response.message(), bodyString, response.headers()))                         response = response.newBuilder().body(ResponseBody.create(response.body()!!.contentType(), bodyString)).build()                     }                      response                 }                 .build()              return Retrofit.Builder()                 .callbackExecutor(Executors.newCachedThreadPool())                 .baseUrl("https://example.com")                 .addConverterFactory(converterFactory)                 .client(okHttpClient)                 .build()         }      private val fileService: FileService = retrofit.create(FileService::class.java)      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          doAsync { downloadFile() }     }      fun downloadFile() {         val uri = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"         val auth = "doesn't matter"          val response = fileService.fileFromUrl(             uri,             auth         ).execute()          if (!response.isSuccessful) {             Log.e(TAG, "response was not successful: " +                     response.code() + " -- " + response.message())             throw Throwable(response.message())         }          Log.d(TAG, "Server has file for ${uri}") saveFileFromResponseBody(response.body()!!) } // Returns the name of what the file should be, whether or not it exists locally private fun getFileName(): String? { return "dummy.pdf" } fun saveFileFromResponseBody(body: ResponseBody): Boolean { val fileName = getFileName() val localFullFilePath = File(getFileFullDirectoryPath(), fileName) var inputStream: InputStream? = null var outputStream: OutputStream? = null Log.d(TAG, "Attempting to download$  fileName")          try {             val fileReader = ByteArray(4096)             val fileSize = body.contentLength()             var fileSizeDownloaded: Long = 0              inputStream = body.byteStream()             outputStream = FileOutputStream(localFullFilePath)              while (true) {                 val read = inputStream.read(fileReader)                 if (read == -1) break                  outputStream.write(fileReader, 0, read)                 fileSizeDownloaded += read.toLong()                  Log.d(TAG, "$fileName download progress:$  fileSizeDownloaded of $fileSize") } outputStream.flush() Log.d(TAG, "$  fileName downloaded successfully")             return true         } catch (e: IOException) {             Log.d(TAG, "$fileName downloaded attempt failed") return false } finally { inputStream?.close() outputStream?.close() } } fun getFileFullDirectoryPath(): String { val directory = getDir("test_dir", Context.MODE_PRIVATE) return directory.absolutePath } }  If it helps, here’s my build.gradle file: apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 28 defaultConfig { applicationId "com.ebelinski.RetrofitTestApp" minSdkVersion 21 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$  kotlin_version"     implementation 'com.android.support:appcompat-v7:28.0.0'     implementation 'com.android.support.constraint:constraint-layout:1.1.3'     implementation 'com.squareup.retrofit2:converter-gson:2.5.0'     implementation 'com.squareup.retrofit2:retrofit:2.5.0'     implementation 'com.squareup.okhttp3:okhttp:3.12.0'     implementation "org.jetbrains.anko:anko-commons:0.10.1"     testImplementation 'junit:junit:4.12'     androidTestImplementation 'com.android.support.test:runner:1.0.2'     androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } 

PowerShell – Return doesn’t behave as expected

I’m using PowerShell v5.1. I have a question about “Return”. Shouldn’t “Return” stop script execution?

Get-CimInstance Win32_OperatingSystem | ForEach-Object {     "Exiting"     Return } "It doesn't"  ForEach ($number in 1..2){ "Exiting" Return } "It doesn't"  Result is: Exiting => It doesn’t => Exiting As you can see “Return” behaves differently inside “ForEach-Object” loop then inside “ForEach” loop. What am I missing? Thank you 🙂 Alerts for A View not working as expected We have a library that includes a column with 3 choices. We have made a view that display all items where choice = Option2. We subsequently set alerts on new items added to that view and for testing alerts for the base library. Users will receive alerts set for all new docs and will not receive alerts for docs that fit a view. I have verified that all web servers and app servers can send email. I checked logs and have verified that immediate alerts jobs run and are sent and received, just not for the alerts based on a view. What else can I check? Is this a bug? Bash if clause not working as expected #!/bin/bash python3 -c "import numpy" if [$  ? ]; then     echo Numpy needs to be installed     sudo apt-get python3-numpy fi echo Everything is properly installed 

This is what I’m trying to run.

Supposedly, it checks if numpy is already installed and if not, install it. However, it installs everytime, even though I already have it.

When I change import numpy to import asdfas it still installs numpy, so the if is not doing anything at all!

Expected values of packing distance between vectors with Bernoulli trials?

Pick set $$\mathcal T$$ of $$2^k$$ vectors in $$\{-1,+1\}^n$$ with Bernoulli trials.

What are exact expected values or at least tight bounds of $$\min_{\substack {u,v\in\mathcal T\u\neq v}}\|u-v\|_2^2$$ $$\min_{\substack {u,v\in\mathcal T\u\neq v}}\|u-v\|_1$$ and their distributions?

Docker pull then start for running container – what is the expected behavior?

Let’s say I have a running Docker container X that is based on image foo.

If I pull a new version of foo, then stop and delete X, and then docker run foo – will it have the new version of the image?

Said differently – do I need to stop X before I can pull the new version of foo and then start it?

The context is Docker-EE on Windows Server 2016.

I´m trying to add a WebPart to a modern page via PnP.

Add-PnPClientSideWebPart -Page "home.aspx" -DefaultWebPartType ContentRollup -Section 3 -Column 1 -WebPartProperties @{layoutid="List"} 

It should be a list layout. But I´m getting a grid layout.

What is wrong?

Thanks!

Viktor

Random points on interval, expected lengths of pieces

Many years ago I came across the following task.

If we have the interval $$[0; 1]$$ and we throw $$N$$ uniformly distributed and mutually independent points on it, then we’ll get $$N+1$$ segments. What is the expected length of the longest segment? The 2nd longest? Etc.

For $$N=1$$, the solution is trivial: $$3/4$$ and $$1/4$$ (since the longest segment is uniformly distributed in [1/2; 1] and the shorter one is uniformly distributed in $$[0; 1/2]$$).

For $$N=2$$, the solution is not trivial, but possible. One just has to draw a quadrat 1 x 1. A point in it would mean that the longest segment has the x coordinate, and the 2nd longest segment has the y coordinate (and the shortest one is 1 – 1st – 2nd). One then has to carefully draw the possible area (this will be a triangle), and find its middle point.

But for $$N>2$$ I have no clue how to solve it.

I remember, the book I saw the task in, had a general solution for arbitrary $$N$$, but I don’t know anymore what book it was.

Note that the task is somewhat similar to Average Distance Between Random Points on a Line Segment, but just somewhat.

Random walks – expected number of steps

Mouse and cat walk randomly (and independently) on the same consistent 8-regular graph with 20 vertices. At the beginning, they are in non-neighboring vertices. When they are in the same vertex, the cat eats the mouse. Explain that the expected number of steps at which the mouse will be eaten is less than 625 · 2^15

I know that average cover time for a random walk over any consistent G graph, for any state initial, is smaller than 2e(G)v(G)., where e(G) is number of edges in graph and v(G) is number verticles.

I also have a small hint that this number of steps should be smaller than 8*(e(G)^2)(v(G)^2), but don’t know how to use it and moreover prove it.

OpenVPN install – Missing expected CA file

Hey everyone it’s my first time installing a VPN on my Celeron powered Intel NUC with a clean install of Ubuntu mate 18.04. And I can’t get past this ca file requirement. I have followed the commands to input from digital ocean exactly the way they wanted. But for some reason I’m getting an EasyRSA error, and I’m not getting what’s pictured in their tutorial. Any help would be greatly appreciated, because I’m totally lost. Thanks.