text:
Q: Android + exoplayer: play AES encrypted videos, locally On a linux box, I have an MP4 video that is encrypted with openssl:
openssl enc -aes-128-ecb -a -in video.mp4 -out video.enc -K `cat aes.key`

Please note, this is an exercise, the strength of the algo doesn't matter.
That file is sent to an Android app, and I'm trying to play it using ExoPlayer.
I've done some tests beforehand with text files to make sure the decryption was working properly
fun decrypt(key: ByteArray, data: ByteArray): ByteArray {
    val spec = SecretKeySpec(key, "AES")
    val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
    cipher.init(Cipher.DECRYPT_MODE, spec)
    globalCipher.init(Cipher.DECRYPT_MODE, spec)
    return cipher.doFinal(data)
}

Regarding ExoPlayer, it's a bit overwhelming between AesCipherDataSource, AesCipherDataSink, SimpleCache etc. I was not able to put together a simple way to play the video.
fun playVideo() {
    val player = SimpleExoPlayer.Builder(this).build()
    playerView.player = player

    val dataSourceFactory = DefaultDataSourceFactory? // <-- what's the factory?
    val dataSource = AesCipherDataSource(globalCipher, ?) // <-- what's the data source?
    val extractorsFactory: ExtractorsFactory = DefaultExtractorsFactory()
    try {
        val uri = Uri.fromFile(File(path, "video.enc"))
        val videoSource =
                ExtractorMediaSource(uri, dataSourceFactory, extractorsFactory, null, null)
        player.prepare(videoSource)
        player.playWhenReady = true
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

So questions:

*

*how to achieve playing this encrypted video locally?

*what would need to change once that video is served over HTTP? (need to add a manifest? headers?)

A: here's the solution. Might need some adjustments to handle skipping frames, fast forward etc, but this plays an AES/ECB/PKCS5Padding encrypted video
class EncryptedDataSourceFactory(
    private val key: String
) : DataSource.Factory {
    override fun createDataSource(): EncryptedDataSource =
        EncryptedDataSource(key)
}

class EncryptedDataSource(private val key: String) : DataSource {
    private var inputStream: CipherInputStream? = null
    private lateinit var uri: Uri

    override fun addTransferListener(transferListener: TransferListener) {}

    override fun open(dataSpec: DataSpec): Long {
        uri = dataSpec.uri
        try {
            val file = File(uri.path)
            val skeySpec = SecretKeySpec(key.toByteArray(), KeyProperties.KEY_ALGORITHM_AES)
            val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
            cipher.init(Cipher.DECRYPT_MODE, skeySpec)
            inputStream = CipherInputStream(file.inputStream(), cipher)
        } catch (e: Exception) {

        }
        return dataSpec.length
    }

    @Throws(IOException::class)
    override fun read(buffer: ByteArray, offset: Int, readLength: Int): Int =
        if (readLength == 0) {
            0
        } else {
            inputStream?.read(buffer, offset, readLength) ?: 0
        }

    override fun getUri(): Uri? =
        uri

    @Throws(IOException::class)
    override fun close() {
        inputStream?.close()
    }
}

    private fun playVideo(key: String) {
        val player = SimpleExoPlayer.Builder(this).build()
        playerView.player = player

        val dataSourceFactory: DataSource.Factory = EncryptedDataSourceFactory(key)
        val extractorsFactory: ExtractorsFactory = DefaultExtractorsFactory()
        try {
            val uri = Uri.fromFile(video)
            val videoSource: MediaSource = ExtractorMediaSource(uri, dataSourceFactory, extractorsFactory, null, null)
            player.prepare(videoSource)
            player.playWhenReady = true
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


text:
Q: jetty+jersey servlet mapping not working i am trying to implement a REST web service using jetty and jersey. I created a maven webapp project and i also want to use the maven jetty plugin in this project.
The problem i am facing right now is that the servlet-mapping does not seem to work. I want the resource being mapped to http://localhost:8080/rest/test which i tried in the web.xml but when accessing the URI i get 404 not found.
Here is the pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.testproject</groupId>
  <artifactId>rest</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>rest Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-server</artifactId>
    <version>2.22.1</version>
</dependency>

    <dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet-core</artifactId>
    <version>2.22.1</version>
</dependency>

    <dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.22.1</version>
</dependency>

    <dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-jetty-http</artifactId>
    <version>2.22.1</version>
</dependency>
    <dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-jetty-servlet</artifactId>
    <version>2.22.1</version>
</dependency>

  </dependencies>

  <build>

  <plugins>
      <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>9.3.6.v20151106</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>

      </plugins>
    <finalName>rest</finalName>
  </build>
</project>

RestResource.java
package com.testproject.rest.resource;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/rest")
public class RestResource {

@GET
@Path("/test")
@Produces(MediaType.TEXT_PLAIN)
public String testService(){
    return "success!";
}

}

web.xml
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

    <servlet>
        <servlet-name>REST</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.testproject.rest.resource</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>REST</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

I did search for this problem in google but none of the solutions i found seem to work. And since this is my first time working with web servers and web services, i dont't entirely understand the whole topic yet.

A: Change @Path("/rest") to @Path("/test"), and get rid of the other @Path("/test") on the method. Every method not annotated with @Path, will go to /test on the class.
/rest/* is already define in the servlet mapping in the web.xml, so that will be be the root.
How you currently have it, you would need to access. /rest/rest/test

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using BeautifulSoup to exploit a URL and its dependent pages and store results in csv? This code does not crash, which is good.  However, it generates and empty icao_publications.csv f.  I want to populate icao_publications.csv with all record on all the pages from the URL and capture all the pages. The dataset should be about 10,000 rows or their about in all.
I want to get these 10,000 or so rows  in the csv file.
import requests, csv
from bs4 import BeautifulSoup

url = 'https://www.icao.int/publications/DOC8643/Pages/Search.aspx'

with open('Test1_Aircraft_Type_Designators.csv', "w", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["Manufacturers", "Model", "Type_Designator", "Description", "Engine_Type", "Engine_Count", "WTC"])

    while True:
        html = requests.get(url)
        soup = BeautifulSoup(html.text, 'html.parser')
        for row in soup.select('table tbody tr'):
            writer.writerow([c.text if c.text else '' for c in row.select('td')])

        if soup.select_one('li.paginate_button.active + li a'):
            url = soup.select_one('li.paginate_button.active + li a')['href']
        else:
            break

A: Here you go:
import requests
import pandas as pd

url = 'https://www4.icao.int/doc8643/External/AircraftTypes'
resp = requests.post(url).json()
df = pd.DataFrame(resp)
df.to_csv('aircraft.csv',encoding='utf-8',index=False)
print('Saved to aircraft.csv')


text:
Q: HTML5 Canvas not rendering automatically I am building a html5 js ionic mobile app. and short story is I cannot get my canvas to initialize the first image in a sequence on each view load. So each view is a task and each task has a set of images that I cycle through on click... My problem is that I'm trying to show the 1st image in each set before any clicks happen. So a case would be: a user chooses a task, navigates to that view and is presented with a canvas (blank at the moment, well sometimes this behavior miraculous works).
Each time the controller loads, I load the images for that specific task and then call an automatic load of the first image. Alas this is not working...
I have attached a link to show how the method where I believe she is braking -codepen...
$rootScope.getInitialScreen = function () {

I have not included a full example (would be too hectic to code a standalone version) but I have shown how the initial method is called on a loadImages() function, all images load perfectly so that is not where the error is, so I have just put the initialization code up.
Console.logging the image in the initialization function does show the correct image, it simply is not rendering onto my canvas... I've tried sizing of image, position of image, image itself and nothing.. Any ideas I would be super grateful!
Thanks.


text:
Q: Trying to extract names of worksheets in workbook I am trying to extract names of worksheets within all excel workbooks in the folder selected. The codes doesn't run reminding type mismatch on IF row.
I am not really familiar with FSO, object and shell function in vba so if I did anything wrong please point out, thanks.
Sub extractname()

    Dim Fso, Fld, sFld, Fl
    Dim Wb As Workbook, Sheeet As Worksheet, Sh As Worksheet
    Dim Arr
    Dim count As Long

    count = 0

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Set Fso = CreateObject("Scripting.FileSystemObject")
    Set Fld = Fso.getfolder(CreateObject("Shell.Application").BrowseForFolder(0, "Please select folder", 0, "").Self.Path & "")
    Set Sheeet = ActiveSheet
        For Each Fl In Fld.Files
            'On Error Resume Next
            If Fl.Name Like "*.xls" Or "*.xlsm" Or "*.xlsx" Then
                count = count + 1
                Set Wb = Workbooks.Open(Fl)
                ReDim Arr(count, 4)
                Arr(count, 1) = Wb.Worksheets(1).Name.Text
                Arr(count, 2) = Wb.Worksheets(2).Name.Text
                Arr(count, 3) = Wb.Worksheets(3).Name.Text
                Arr(count, 4) = Wb.Worksheets(4).Name.Text
                Wb.Close
            End If
        Next
    Sheeet.[B65536].End(3).Resize(count, 4) = Arr

End Sub

I expect 4 columns of worksheet names shall be tabulated but the code does not run.

A: Change :
If Fl.Name Like "*.xls" Or "*.xlsm" Or "*.xlsx" Then

to
If Fl.Name Like "*.xls" Or Fl.Name Like "*.xlsm" Or Fl.Name Like "*.xlsx" Then

Why not just use:
If Fl.Name Like "*.xls*" Then

Edit 1: modified code
the code below will get you what you want (if I understand your code intentions correctly).
Option Explicit

Sub extractname()

    Dim Fso, Fld, sFld, Fl
    Dim Wb As Workbook, Sheeet As Worksheet, Sh As Worksheet
    Dim Arr
    Dim count As Long, i As Long, ShtCount As Long

    count = 0

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Set Fso = CreateObject("Scripting.FileSystemObject")
    Set Fld = Fso.getfolder(CreateObject("Shell.Application").BrowseForFolder(0, "Please select folder", 0, "").Self.Path & "")
    Set Sheeet = ActiveSheet

    For Each Fl In Fld.Files
        ReDim Arr(1 To Fld.Files.count, 1 To 4)

        If Fl.Name Like "*.xls*" Then
            count = count + 1
            Set Wb = Workbooks.Open(Fl)

            ' need to make sure each workbook has 4 sheet (not less)
            ShtCount = Wb.Worksheets.count
            If ShtCount > 4 Then ShtCount = 4

            For i = 1 To ShtCount
                Arr(count, i) = Wb.Worksheets(i).Name
            Next i

            Wb.Close
        End If
    Next Fl

    Sheeet.Range("B" & Sheeet.Cells(Sheeet.Rows.count, "B").End(xlUp).Row).Resize(count, 4) = Arr

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True

End Sub

A: Sub F()

    '// Tools -> References -> Microsoft Scripting Runtime

    Dim fso As FileSystemObject, xFile As File
    Dim strFolder$
    Dim book As Workbook

    With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False
        .Title = "Select folder"
        If .Show() Then strFolder = .SelectedItems(1) Else Exit Sub
    End With
    Set fso = New FileSystemObject
    For Each xFile In fso.GetFolder(strFolder).Files
        If fso.GetExtensionName(xFile.Name) Like "xls*" Then
            Set book = Workbooks.Open(xFile.Path)
            '// Do your thing
        End If
    Next

End Sub

A: There are a few issues with your code.
1) You can't redim the rows in VBA arrays
2) it errors if your file doesn't have exactly 4 worksheets
3) If you don't preserve the array when you redim it loses all data.
You could still use the FSO instead of the open folder dialog box macro.
Option Base 1  'so that the VBA array starts on row 1 and column 1, not 0,0
Sub Worksheet_names_in_Dir()
Dim direct As String
Dim Arr()
'
' directory Macro
Let direct = UseFolderDialogOpen & "\"
'
  Set Sht = ActiveSheet
f = Dir(direct & "\*.xls*", 7) 'sets f equal to the first file name and only files that are xls* files (XLSX, XLSB, XLSM)
Do While f <> ""        'loops until there are no more files in the direstory

    F1 = direct & f
                        Count = Count + 1
                        ReDim Preserve Arr(4, Count)  'you can't redim the rows in VBA, just the columns
                Set wb = Workbooks.Open(F1)
                wkshts = wb.Sheets.Count    'count number of worksheets in file
                If wkshts > 4 Then wkshts = 4  'to only do 4 worksheets per file or less if there are less than 4 worksheets
                For i = 1 To wkshts
                    Arr(i, Count) = wb.Worksheets(i).Name
                Next i
                wb.Close

     f = Dir            'set f equal to the next file name in the directory

Loop

'this transposes the array and writes it to the active worksheet starting in A!, you can change this to fit your needs
Sht.Range("A1:D" & Count).Value = WorksheetFunction.Transpose(Arr)

End Sub

Public Function UseFolderDialogOpen() As String
    Dim lngCount As Long

    ' Open the folder dialog
    With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False 'only allows the user to pick one directory
        .Title = "pick directory"
        .Show

        ' Set Current Folder Path
        For lngCount = 1 To .SelectedItems.Count
            UseFolderDialogOpen = .SelectedItems(lngCount)
        Next lngCount

    End With

End Function


text:
Q: Unable to instantiate app and cannot find class This is the main problem below when I ran flutter run in my terminal
Launching lib\main.dart on TECNO LB7 in debug mode...
Running Gradle task 'assembleDebug'...

Running Gradle task 'assembleDebug'... Done                       178.4s (!)
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...                31.1s
E/AndroidRuntime(17767): FATAL EXCEPTION: main
E/AndroidRuntime(17767): Process: com.example.firebasepractice, PID: 17767
E/AndroidRuntime(17767): java.lang.RuntimeException: Unable to instantiate application com.example.firebasepractice: java.lang.ClassNotFoundException: Didn't find class "com.example.firebasepractice" on path: DexPathList[[zip file "/data/app/com.example.firebasepractice-LyPE1lNorhYSOJyU9fBj_Q==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.firebasepractice-LyPE1lNorhYSOJyU9fBj_Q==/lib/arm, /data/app/com.example.firebasepractice-LyPE1lNorhYSOJyU9fBj_Q==/base.apk!/lib/armeabi-v7a, /system/lib,
/vendor/lib]]
E/AndroidRuntime(17767):        at android.app.LoadedApk.makeApplication(LoadedApk.java:999)
E/AndroidRuntime(17767):        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5757)
E/AndroidRuntime(17767):        at android.app.ActivityThread.-wrap1(Unknown Source:0)
E/AndroidRuntime(17767):        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1691)
E/AndroidRuntime(17767):        at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(17767):        at android.os.Looper.loop(Looper.java:164)
E/AndroidRuntime(17767):        at android.app.ActivityThread.main(ActivityThread.java:6549)
E/AndroidRuntime(17767):        at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(17767):        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
E/AndroidRuntime(17767):        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888)
E/AndroidRuntime(17767): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.firebasepractice" on path: DexPathList[[zip file "/data/app/com.example.firebasepractice-LyPE1lNorhYSOJyU9fBj_Q==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.firebasepractice-LyPE1lNorhYSOJyU9fBj_Q==/lib/arm, /data/app/com.example.firebasepractice-LyPE1lNorhYSOJyU9fBj_Q==/base.apk!/lib/armeabi-v7a, /system/lib, /vendor/lib]]
E/AndroidRuntime(17767):        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:125)
E/AndroidRuntime(17767):        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
E/AndroidRuntime(17767):        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
E/AndroidRuntime(17767):        at android.app.Instrumentation.newApplication(Instrumentation.java:1087)
E/AndroidRuntime(17767):        at android.app.LoadedApk.makeApplication(LoadedApk.java:993)
E/AndroidRuntime(17767):        ... 9 more

when I run flutter doctor it gave me this :
[√] Flutter (Channel beta, 1.20.2, on Microsoft Windows [Version 10.0.18362.418], locale en-US)
    • Flutter version 1.20.2 at C:\flutter
    • Framework revision bbfbf1770c (3 weeks ago), 2020-08-13 08:33:09 -0700
    • Engine revision 9d5b21729f
    • Dart version 2.9.1

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at C:\Users\FutureAlex\AppData\Local\Android\sdk
    • Platform android-30, build-tools 30.0.2
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

[√] Android Studio (version 4.0)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 48.1.2
    • Dart plugin version 193.7361
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)

[√] VS Code, 64-bit edition (version 1.48.1)
    • VS Code at C:\Program Files\Microsoft VS Code
    • Flutter extension version 3.13.2

[√] Connected device (3 available)
    • TECNO LB7 (mobile) • 043803395H000877 • android-arm    • Android 8.1.0 (API 27)
    • Web Server (web)   • web-server       • web-javascript • Flutter Tools
    • Chrome (web)       • chrome           • web-javascript • Google Chrome 84.0.4147.135

• No issues found!

A: Did you change your package name? It seems like it's looking on a different path

A: /i solved my bug by adding a Application.kt file in project path like: "project_name\android\app\src\main\kotlin\com\example\firebasepractice\Application.kt"
    package com.example.project_name;

    import io.flutter.app.FlutterApplication;
    import io.flutter.plugin.common.PluginRegistry;
    import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
    import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;

    class Application : FlutterApplication(), PluginRegistrantCallback {
        override fun onCreate() {
            super.onCreate()
    FlutterFirebaseMessagingService.setPluginRegistrant(this);
}

    override fun registerWith(registry: PluginRegistry?) {
       registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin");
}

}


text:
Q: Problem with formatting Flash Disk I have installed Arch Linux ISO file into Flash disk with the following command:
dd bs=2M if=~/archlinux-2013.11.01-dual.iso of=/dev/sdd

Now I'm trying to format the flash disk with the following command:
sudo mkfs.vfat -F 32 /dev/sdd

But it gets me the following error :

mkfs.vfat: Device partition expected, not making filesystem on entire
  device '/dev/sdd' (use -I to override)

The output of sudo fdisk -l:
Disk /dev/sda: 298.1 GiB, 320072933376 bytes, 625142448 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xf3286bd2

Device    Boot     Start       End    Blocks  Id System
/dev/sda1 *    119700315 154850534  17575110  83 Linux
/dev/sda2       19834880 119700314  49932717+  7 HPFS/NTFS/exFAT
/dev/sda3      154850535 174385574   9767520  83 Linux
/dev/sda4      174385575 625137663 225376044+  f W95 Ext'd (LBA)
/dev/sda5      174385638 185610192   5612277+ 82 Linux swap / Solaris
/dev/sda6      185610256 338423679  76406712   7 HPFS/NTFS/exFAT
/dev/sda7      338423808 477687807  69632000   7 HPFS/NTFS/exFAT
/dev/sda8      477689856 625137663  73723904   7 HPFS/NTFS/exFAT

Partition table entries are not in disk order.

Disk /dev/sdd: 7.5 GiB, 8019509248 bytes, 15663104 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x00000000

A: You generally don't want to write the filesystem on the entire block device (ie. /dev/sdd), you want to create a partition and then put the filesystem in there (ie. /dev/sdd1). That is also what your mkfs complained about.
If you are sure you only want to have one filesystem on this disk at a time, and you don't need a bootloader, you can safely ignore this warning using mkfs.vfat -I, and use the whole device. Otherwise, create a partitioning scheme using fdisk or similar (you can create a basic, full one with o, n, p, 1, Enter, Enter, w), and install the filesystem at /dev/sdd1 (or whichever partition you want to use).
If you only plan to use FAT on this device, with no MBR, then it is safe to install to the full device. Otherwise, use a partition table.


text:
Q: Does java have something similar to C# properties? C# properties (I mean get and set methods) are a very useful feature. Does java have something similar to C# properties too? I mean how we can implement something like the following C# code in java:
public string Name
{
    get
    {
        return name;
    }

    set
    {
        name = value;
    }
}

A: There has been a proposal to add C#-like support for properties (and events) to Java, but it looks like this is rejected for the next version of Java (Java 7).
See:

*

*Why will there be no native properties in Java 7?

*Java Properties Without Getters and Setters

A: You could have a look at Project Lombok as it tries to take the pain out of writing boiler plate Java code. It allows you to either use @Getter and @Setter annotations, which will provide getBlah() and setBlah() methods:
public class GetterSetterExample {
  @Getter @Setter private int age = 10;
}

Or you can just use @Data and it will automatically implement your hashCode(), equals(), toString() and getter methods, along with setters on non-final fields:
@Data public class DataExample {
  private String name;
}

Problems I have found with the project, however, are that it's all a bit voodoo, which can be off-putting, and that you have to install an Eclipse (or what ever) plugin to get auto compilation to work.

A: Properties are not only convenient in terms of writing getters and setters encapsulated in a unit , but also they provide a good syntax at the point of call.
Window.Title =  "New"; //which looks natural

while with getters and setters it is usually
Window.setTitle("New");

A: No, Java does not have the equivalence.  It only has accessor and mutator methods, fancy names for getter and setter methods.  For example:
public class User {
    private String name;

    public String getName() { return this.name; }
    public void setName(String name) { this.name = name; }
}

A: You can just declare a private variable, and write the methods by hand. However, if you are using Eclipse, you can click on a variable, select "Source" and "Generate getters and setters." This is about as convenient as C# properties.


text:
Q: How to implement an XSLT file within HTML I'm trying to display a whole XML database through an HTML file, but in order to display all the elements, I need XSLT. Since I used Javascript for manipulation with the way the database is displayed, I assume I'll have to implement XSLT file within the HTML code, but I can't find a solution on how I'd go about doing so.

A: It's quite possible to invoke an XSLT transformation from within Javascript. You can even use an XSLT 2.0 transformation with the help of Saxon-CE, which probably offers better cross-browser compatibility than the XSLT 1.0 processors shipped by the browser vendors.


text:
Q: onActivityResult() not called onActivityResult() is not getting called. Below is my code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to

    Log.e("CALLED", "OnActivity Result");

    if (requestCode == TEAM_SELECTED_REQUEST_CODE) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            try {
                 mySelectedTeam = getIntent().getStringExtra("teamName");
                txtSelectTeamCreateMatch.setText(mySelectedTeam);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Here's I'm starting the SelectTeamActivity:
Intent intent=new Intent(CreateMatch.this,SelectTeamActivity.class);
startActivityForResult(intent, TEAM_SELECTED_REQUEST_CODE);
//overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);

Intent intent = getIntent();
intent.putExtra("teamID", teamDataList.get(position).getTeamId().toString());
intent.putExtra("teamName", teamDataList.get(position).getTeamName().toString());
setResult(1, intent);

A: Option 1 :
If you're calling startActivityForResult() from the Fragment then you should call startActivityForResult() and not getActivity().startActivityForResult(), as it will result in Fragment's onActivityResult().
If you're not sure where you're calling on startActivityForResult() and how you will be calling methods.
Option 2:
Since Activity gets the result of onActivityResult(), you will need to override the Activity's onActivityResult() and call super.onActivityResult() to propagate to the respective Fragment for unhandled results codes or for all.
If above 2 options do not work, then refer option 3 as it will definitely work.
Option 3 :
Explicit call from Fragment to onActivityResult() function as follows
In parent Activity class, override the onActivityResult() and even override the same in Fragment class and call as the following code.
In parent class:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.dualPane);
    fragment.onActivityResult(requestCode, resultCode, data);
}

In child class:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   //in fragment class callback
}

A: I had same issue. My calling activity was 'singleInstance'. Removing that solved my issue.

A: onActivityResult called but using wrong intent reference to get data from result intent :
getIntent().getStringExtra("teamName")

Replace with this :
data.getStringExtra("teamName")

Here data is result intent.

A: I had similar problem and my issue was about requestCode parameter which was set to -1 in startActivityForResult method.
So when I changed requestCode value to 1 or 0 onActivityResult started getting called.

A: I just had the same issue and I'm surprised none of the solutions I've looked at have mentioned the following:
The value of the constant RESULT_OK is -1, and if you give the value of 1 in the method setResult, then the resultcode wouldn't be equal to the RESULT_OK and the condition wouldn't get processed.
I hope someone finds this helpful.

A: After reviewing pradip tilala's answer, I have solved my problem by removing below line from AndroidManifest.xml
android:noHistory="true"

A: I solved my problem by removing android:noHistory="true" from AndroidManifest.xml.

A: I had the same issue and I solved that by adding these parameters to activity:
AlwaysRetainTaskState = true, LaunchMode = Android.Content.PM.LaunchMode.SingleTop

A: After referring answer of @spgodara.
I have below AndroidManifest.xml for my SecondActivity class:
<activity android:name=".SecondActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait"
            android:theme="@style/AppThemeHome"
        android:windowSoftInputMode="adjustResize"/>

I have put simple Toast to find when callback onActivityResult of MainActivity is being called. I found that is just called on create of SecondActivity (On opening of the SecondActivity). It's working fine on Redmi Note 3 device with Marshmallow, but not working on Kitkat device.
After removing below the line from AndroidManifest.xml deceleration mentioned above:
android:launchMode="singleTask"

and calling intent like below worked for me:
 Intent intent = new Intent(this, SecondActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);

A: Removed this line and its working fine.
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Thanks for hint.


text:
Q: How to specify custom layout for a DropdownPreference? I want to use a custom layout for a DropDownPreference.
When I specify the layout as an android:layout="@layout/mylayout", I get a runtime error. Can anyone confirm if they have done this previously?

A: I solved it myself.
The issue was that I was not implementing Spinner component inside my custom Layout and DropDownPreference uses a Spinner component internally.


text:
Q: Stack Exchange App keeps crashing After the latest update the app crashes every time I open to view a question and then once I start scrolling it crashes this happens every single time, very annoying.
I went into Settings -> Privacy -> Diagnosis but I couldn't find any file crash with having the name stack exchange

*

*App Version: 1.6.3.6

*Device: iPhone 6

*OS Version: Version 8.3 (Build 12F70)

A: Crash logs are automatically reported to developers. So there is no need to do it manually.
To prevent crashing you could try any of Crash Recovery options from iOS system settings:

After upgrading to 1.6.4 (TestFlight) but on iOS 10, I also had an issue with crashing. Crash Recovery options helped me.
Another problem may be due to you using old iOS version. See Brian's answer for another question here.


text:
Q: Execute php code before going to index.html I want to create a link inside a php code to redirect to the index.html page, I am able to achieve that with the following line:
echo "Main page";

But I want to execute another php code which simply removes the content of a file before going back to the index page.
I can execute my php code as I did to go to the index, I mean:
    echo "Clear configuration";

But I haven't been able to execute both instructions within a same click (first execute clear_config.php and then go to index.html).
How can I do it?
By using redirection within php code I can get the expected result, but I'm just curious about if it is possible to do it with href tags since clear_config.php is also used in another places where doesn't need to redirect to index.html

A: You can use
header('Location: index.html');

In your clear_config_and_go_to_page.php to redirect to other location.


text:
Q: Data Structure/Algo for a Queue with Dynamic Limits Based on Attribute I have a stack (implemented as an array) that contains HTTP requests to be made as sockets become available, with the number of active sockets being limited. I would like to expand this so that there is a maximum number of sockets per host (and a maximum number of total sockets, but that doesn't particularly come in to my question here).
So the queue should continue to be processed in the order that they were received. But of course, if the maximum number of sockets has been reached for the host of the next request in the queue, it's not going to be possible to service it, so the next host in the queue that has not reached maximum sockets should be taken.
I looked at using a Priority Queue, with a comparator to check for the max sockets available on the hosts, but this doesn't really do the job. I want to take the next one in the queue that can be serviced, not reorder the queue based on socket availability as a priority metric.
I thought about a queue per host, but then it's difficult to maintain the original order.
I'm thinking to have a single queue, an attribute for the host on each item, and a routine to go through the queue until it finds the first one that has available sockets, and then dequeue it by splicing. This maintains the original order but seems like it could be inefficient.
So I'm thinking to combine the approaches with something like this (maintaining the overall queue with an "order" attribute):
const queues = [
  {
    host: 'www.example.org',
    queue: [
      { order: 1 },
      { order: 3 }
    ]
  },
  {
    host: 'www.example.com',
    queue: [
      { order: 2 },
      { order: 4 },
      { order: 5 }
    ]
  }
];

With the above approach, an order attribute would be added to each request as it is added to the appropriate queue for its host. Then, each time a new item is needed, the set of host queues can be sorted based on the order value of its first item. Then the check for the next item only needs to run once per host, instead of scanning the entire queue each time.

A: I did something like this in the past for a web crawler.
I had a Host class that contained information about the host: name, maximum number of concurrent requests, the current number of active requests, a copy of its robots.txt file, statistics about its history (number of requests I made to it, average response speed, error rate, etc.), and other host-specific information.
I also had a priority queue of requests. Each request structure had the URL to be visited, and a reference to the corresponding Host instance. The priority key was a combination of a priority value based on the URL's value (computed by a machine learning algorithm that isn't really relevant here), and the time.
When I removed a request from the queue, the first thing I would do is check the Host to see if there were sockets available. If not, I would just re-queue the request with a time value of now + host's average request time.
That worked, although urls for some very busy hosts tended to get recycled often.
I experimented with a priority queue of hosts. Each host had a queue or URLs. There also was a timeout list: a dictionary of hosts that were currently in "timeout" for various reasons, but mostly because there were no available sockets, or its URL queue was empty. Here's how it worked:
A host would be removed from the priority queue, and a request made. If the host still had available sockets, then I would add it back to the queue. If not, it would go into the timeout queue. In either case, when the request completed, the host's number of available sockets would be increased, the host removed from the timeout list and re-inserted into the priority queue.
That approach looked promising. We were testing it when the project was canceled for other reasons.


text:
Q: Warning. Current NDK support is depreciated. Alternative will be provided in the future Using Visual Studio 2015 RTM, default TypeScript Cordova (5.1.1) project and CrossWalk Cordova Plugin.  I get the following warning:
Current NDK support is depreciated.  Alternative will be provided in the future

The project Link in the error window is : https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(%22%5BProject%22);k(TargetOS-8.1)&rd=true
The warning doesn't appear to be affecting the build.  However, I'm not sure why the error is appearing.
Is this a Visual Studio 2015 issue?
Is this a Cordova problem?
Is this a CrossWalk problem?
Windows 8.1

A: This definitely seems like a Crosswalk plugin issue. Folks using Ionic/Angular are also seeing this


text:
Q: How to set the DPI of Java Swing apps on Windows/Linux? If you have an monitor with a DPI over 150 (such as Macbook Pro), you may also find the problem: the font on the Java Swing app is too small for high DPI monitor, and I cannot change the font size at all ( It ignores the Windows DPI directly, only displaying the very original DPI-->96 ). I can do nothing but changing the screen resolution, which could absolutely make everything blurry on LCD.
Yes, I have a laptop with a high DPI monitor, 15.6' with 1920x1080 resolution, some Java desktop apps look very small on my laptop, such as Matlab, Burpsuite etc. I have been searching the Internet for a very very long time, but still cannot find a method for the problem. I know I can change the JRE fonts through JRE_HOME/lib/font/fontconfig.properties.src, but I cannot find any place to set the default font size or DPI for Java desktop fonts.
Does the problem have no solution? Do you have a high DPI monitor? How do you do with such apps? Does Swing give up high DPI users?

A: This answer solved the issue on my 4K-screen Ubuntu laptop.
In the application's config file, I added the -Dsun.java2d.uiScale=2.5 Java parameter and now, upon executing, the application is scaled well and is usable.

A: It appears that on Linux (Gtk) you can work around this by scaling the Apps DPI using the following before starting the app.
export GDK_SCALE=2

(You can also reduce you monitor resolution but that's no solution at all).

A: I'm currently investigating this issue on Windows. Here's what I found:
Most Swing Look & Feels don't support high DPI at all, not even Nimbus even though it's supposed to be scalable. I found some old blog posts saying that Nimbus might eventually offer high DPI scaling, but apparently that never happened.
The one exception is System LAF but its default font is ~10% smaller than the actual system font size, at all DPI settings. Moreover, System must be selected explicitly as described here:
http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
There's no single scaling factor that you could set in Swing, either. The specific LAF has to provide code to handle scaling. So the best you can do is select System and hope it's good enough.
However, JavaFX does correctly and automatically scale all the way up to 150% on my system. If at all possible, I suggest you use JavaFX to build your GUI.
edit: I made a couple small test programs and took comparison screenshots for various GUI frameworks, Swing themes, and DPI settings. This might be informative for people reading this question: http://kynosarges.org/GuiDpiScaling.html

A: On Linux, it doesn't seem possible to do scaling with any Swing look and feel, according to my experiments. However, it is possible to do it using a hack involving VNC, vncdesk. Here is my configuration for running gradle --gui under vncdesk:
.vncdesk/1/settings.ini:
[desktop]
width = 1050
height = 650

[window]
title = gradle
name = gradle in vncdesk
class = GradleInVncdesk
scale_factor = 2

.vncdesk/1/startup:
#!/bin/sh
cd "$INVOCATION_DIR"
matchbox-window-manager&
exec gradle --gui "$@"

A: I managed to solve it following these instructions: Link.
It's in German, but I will translate the important stuff.
Create this registry-key:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide]
"PreferExternalManifest"=dword:00000001

Create a manifest file with this content:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">

<dependency>
  <dependentAssembly>
    <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*">
    </assemblyIdentity>
  </dependentAssembly>
</dependency>

<dependency>
  <dependentAssembly>
    <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.21022.8" processorArchitecture="amd64" publicKeyToken="1fc8b3b9a1e18e3b">
    </assemblyIdentity>
  </dependentAssembly>
</dependency>

<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
  <security>
    <requestedPrivileges>
      <requestedExecutionLevel level="asInvoker" uiAccess="false"/>
    </requestedPrivileges>
  </security>
</trustInfo>

<asmv3:application>
  <asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
    <ms_windowsSettings:dpiAware xmlns:ms_windowsSettings="http://schemas.microsoft.com/SMI/2005/WindowsSettings">false</ms_windowsSettings:dpiAware>
  </asmv3:windowsSettings>
</asmv3:application>

</assembly>

Copy it into the bin directory where the java.exe and javaw.exe is inside and named it java.exe.manifest and javaw.exe.manifest (You will have two files with the same content but different names).
HTH.
Bernd

A: Short answer: You need to run it on JRE 9+.
Long answer:
This is because the Java runtime declared itself to be "DPI-aware" but didn't really supported it for AWT and Swing. Java applications were sized and rendered based on pixels rather than being properly scaled, this included HiDPI displays.
Anyways, this has been recently solved.
See the issue JEP 263: HiDPI Graphics on Windows and Linux
and the upgrade.
So, increasing the font size does not work (because it does not increase the rest of the things); the jvm argument -Dsun.java2d.dpiaware=false does not work (because it is not really supported); and the manifest file + registry edit (for Windows) just does not work.
Solution: You need to run it on JRE 9+ because it really supports this feature.

A: As @demented hedgehog said setting the  GDK_SCALE=2  environment variable does work under Linux.
If you are using JetBrains IntelliJ you can set Enviroment variables just for your project under Edit configurations > Build and Run > Enviroment variables
You can see below where to put the GDK_SCALE=2.


text:
Q: the code " : " in php I'm curious to know what the syntax " : " mean in php I've seen it a couple of times but I can't seem to explain it to myself. Can you also use it in a sentence....or i mean, sample code?
**edit:
sorry folks, I was referring to the ternary operator. Thanks for the other entries as well. I didn't know what to call it at first, apologies.

A: It's the ternary operator:
echo ($a == 1 ? "A is 1" : "A is not 1");

A: How about the shorthand syntax for blocks in PHP embedded in HTML? For example

Some Header

   <?php if($somevariable == '4') : ?>

Some other thing

Some text

   <?php else: ?>

Else!

   <?php endif; ?>

Probably doesn't necessarily count as an operator. More of a delimiter here.

A: It can also refer to a goto
MyGoto:
    if (DoSomething())
        goto MyGoto;

Very few circumstances warrant a goto, but that's what it can mean if not a ternary operator.

A: The ?: operator is a ternary operator called the conditional operator.
It is conditional because the expressions expr2 and expr3 in expr1 ? expr2 : expr3 are evaluated based on the evaluated return value of expr1:

*

*If expr1 evaluates to true, expr2 is evaluated and the return value of expr2 is the return value of the whole ?: operator expression;

*otherwise expr3 is evaluated and the return value of the ?: operator expression is the return value of expr3.

Here's an example:
echo 1 == 1 ? "true" : "false";

If 1 == 1 evaluates to true, "true" will be echoed, otherwise "false".
Note that the ?: operator is just a and not the ternary operator. The word ternary just means that there are three operands (op1 ? op2 : op3) just like a binary operator has two operands (e.g. op1 + op2, op1 / op2, op1 % op2, etc.) and unary operators just have one operand (e.g. !op, -op, ~op, etc.).

A: Perhaps you are referring to the ternary operator, which uses a ? and : as follows:
$variable = boolean_expression ? "true_value" : "false_value";

This code is shorthand for an if-else:
if (boolean_expression) {
   $variable = "true_value";
}
else {
   $variable = "false_value";
}

A: Are you talking about the conditional operator?

$a = $gork === 1 ? $foo : $bar;

Check out the "Ternary Operator" section on this page: http://php.net/manual/en/language.operators.comparison.php
It's basically a short cut for an if else, the above code is the same as:

if($gork === 1)
    $a = $foo;
else
    $a = $bar;

A: This is a short-form conditional expression, known in PHP as the "ternary operator."  See the PHP manual for more details on its usage.
echo ($sheLovesMe ? "She loves me!" : "She loves me not!");


text:
Q: How to compare two ordered lists with LINQ? Checking equality on unordered lists can be done with Intersect, but how would you compare ordered lists with LINQ? The expression should return true if both sequences have the same elements in the same order.
Thanks

A: a.SequenceEqual(b);

From the documentation:

Returns true if the two source
  sequences are of equal length and
  their corresponding elements are equal
  according to the default equality
  comparer for their type; otherwise,
  false.

See MSDN for more.

A: Just use SequenceEqual():
list1.SequenceEqual(list2)


text:
Q: TE_find_text returning ascii characters in certain machines I have recorded some scripts in legacy system(telnet, vt100) and I use TE_find_text to verify some of the contents on the screen. It all works fine in my machine. But when it is run on other ones, ASCII characters are returned and TE_find_text fails without finding the expected text.
What could be the possible solution for this? The machine in which it works is core i7 laptop. Has anyone faced the similar situation?


text:
Q: Unity GUITexture doesnt display correctly so i am making a game for android but the display window no matter what ratio i choose from the list the GUI textures never show same size as my phone or tablet so making things very hard to work out correct sizes and positions etc
is there anything i may be doing wrong or is this normal for GUI texturesin the display window?
i'm running a xperia 2 and a xperia z2 tablet in-case it is needed

A: My limited research shows that the Xperia Z2 is 1920x1080.  So, in order to actually see the game view in the editor, you have to have a monitor that is bigger than 1920x1080 to display both the 1920x1080 game view plus the border.
If you happen to have a monitor with a resolution higher than 1920x1080, which is not common, then you can add your own 1920x1080 (Fixed Resolution) setting to the Editor and actually be able to increase the size of the window until the game view reaches 1920x1080.


text:
Q: Powershell and WinApi EnumWindows function $f=@'
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
);
'@

$winList = Add-Type -memberDefinition $f -name "EnumWindows" -namespace Win32Functions -passThru

$winList::EnumWindows(...)

How do I write this down correctly? I have do declare and pass param?
May be there is a way like this? I'm looking for the way, where c# using just only for declaring EnumWindows function, and calling it from posh with correct params.

A: Couple of things needed to make this work:

*

*Define the EnumWindowsProc delegate

*Make EnumWindows() public (or write a public method to wrap the call to EnumWindows())

You can either implement the callback function in C# as well, or you can use a PowerShell script block.
Here's how I'd go about doing it with a script block:
$MemberDefinition = @'
// declare the EnumWindowsProc delegate type
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

// Notice EnumWindows() is now `public`
[DllImport("user32.dll")]
public static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
'@

Add-Type -MemberDefinition $MemberDefinition -Name EnumWindowsUtil -Namespace Win32Functions

# Create a list to act as a receptacle for all the window handles we're about to enumerate
$WindowHandles = [System.Collections.Generic.List[IntPtr]]::new()

# Define the callback function
$callback = {
  param([IntPtr]$handle, [IntPtr]$param)

  # Copy the window handle to our list
  $WindowHandles.Add($handle)

  # Continue (return $false from the callback to abort the enumeration)
  return $true
}

if([Win32Functions.EnumWindowsUtil]::EnumWindows($callback, [IntPtr]::Zero)){
  # $WindowHandles will contain all the window handles now
}


text:
Q: Highlight ping if the user is in the chatroom, Javascript I want it to highlight a ping (@test) only if the user is in the chatroom. If not, don't highlight. Right now I have:
function highlight(message){
    return message.replace(/@\b([A-Za-z0-9]+)\b/g, '@$1');
};

Project Source Code - line 150

A: What you can do, is keep a list of usernames on the clients and server (give to new clients connecting), and then check if that username is in that list, if so then highlight the ping.
The code I got was:
function highlight(message){
    if(message == "") {
        return message
    }
    let mentions = message.match(/@\b([A-Za-z0-9]+)\b/g)
    if (mentions === null) { return message }
    for (i = 0; i < mentions.length; i++) {
        let mention = mentions[i].substring(1)
        if(sesskx.has(mention)) {
            message = message.replace(mentions[i], `<span class="name-color">@${mention}</span>`)
        }
    }
    return message
 };

Explaination:

*

*It takes the message, and finds all mentions

*it loops over all mentions

*if the mention is in current users it highlights it

EDIT: repl link: https://repl.it/@Codemonkey51/Froggy-Chatroom


text:
Q: Cant embed twitter timeline into React 18 app I generated code from twitter publish.twitter and pasted in react( 18 ) app .
It just shows Tweets by blabla not the timeline
I find some packages which is react 16.8 - 17


text:
Q: Changing validation order in a rails model I have a link model that stores links to pages on the web. One of the fields is url - on that field I'm trying to perform a couple of validations, and also change it into a valid URL if its not formed right.
For example test.com would be changed to http://test.com. I also have built a custom validator to check if its a valid URL but the order is all wrong so its firing off before I get chance to add the http bit. However if the field is blank the http if firing off too soon instead of telling the user they need to input something.
Currently my validators look like:
before_validation :add_http
validates :url, :presence => true, :allow_nil => false, :allow_blank => false, :url => true

I'm sure there is a better way to achieve this. The ideal flow I think should be:

*

*Check if the field is present, blank or nil

*Check if its a valid URL

*Add http:// to the beginning of the url if its missing

*Check again if its now a valid url (not sure if this step is necessary depending on timing of steps 2 and 3)


text:
Q: Why do I get unknown printer error 0xFA on my EPSON Workforce WF-3540 under Ubuntu 12.10? I recently bought an EPSON Workforce WF-3540, which I'm using under Ubuntu 12.10 with the official driver provided by EPSON. I am often printing batches of about a hundred pages, duplex. When I'm doing this, after about 20 pages, I regularly get an error message on the printer screen, telling me the printer encountered unknown error 0xFA, forcing me to turn the printer off and back on.
I talked to EPSON about the problem, but they claim they're not supporting Linux and tell me to ask the Linux community about the problem (and possibly another driver?). So this is what I'm doing here... any ideas?
Unfortunately, the documentation does not contain any information pertaining to error code 0xFA and the support hotline wasn't able to give me further information, either.
BTW, the problem hasn't happened, so far, when I'm printing smaller batches or not using duplex. Whenever the problem happens, there's a page in the printer that's already been printed on one side, so I'm suspecting the problem's connected with the duplexer.

A: I, too had this error code come up when I was printing several 2-sided pages.  I opened up the back and sure enough, there was a paper jam.  Turned printer off, pulled out paper, and turned printer back on.  Problem fixed!  Too bad the screen didn't just read "paper jam."  That would have saved me a lot of time!

A: I just encountered the same error code and after letting the printer sit a few minutes while off, the screen said there was a paper jam once restarted. Restarting it quickly just gave me the same error code. I cleared the jam and the printer "adjusted itself" for about a minute. Seems to working fine after printing another 30+ duplex prints. -AL


text:
Q: Solving derivative of $x^x$ without logarithmic differentiation Been learning calculus, and was taken aback (in a good way) by the challenge of
$$\frac{d}{dx}x^x$$
because the rules I've learned so far (chain/product/quotient/implicit differentiation) can handle $x^a$ and $a^x$ and many other functions, but not this special boy, which just takes 2 characters to write!
Now I've learned how you can solve it with logarithmic differentiation.  But I'm curious.. is this a derivative you simply cannot solve without logarithmic differentiation?  Could you use other derivative rules to solve this?  If yes, which ones, and if no.. how do you identify equations that require logarithmic differentiation?
Note: I'm aware logarithmic differentiation utilizes implicit differentiation which I previously learned, but it also involves an extra step of logging both sides.


text:
Q: Adding JSON objects to existing JSON File So I've recently been tasked with creating a utility which will allow easy addition of JSON to a .json file via the gson library. I've coded this in Kotlin:
fun addObject(filePath: String, name: String, values: Array<Array<String>>) {
try {

    var writer: JsonWriter = JsonWriter(FileWriter(File(filePath)))
    writer.beginObject()
    writer.name(name)
    writer.beginObject()
    for(item in values){
        writer.name(item[0]).value(item[1])
    }
    writer.endObject()
    writer.endObject()

    writer.close()

    println("[JSONUtil] Wrote object successfully!")

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

I used a 2 Dimensional array to allow the user to add different objects with any number of values in said object. For instance, you would run it like so:
addObject("C:\\Users\\Test\\Desktop\\JsonUtility\\output.json", "GENERAL",
arrayOf(arrayOf("POS_X","2"), arrayOf("POS_Y","4")))

This creates the following JSON:
{"GENERAL":{"POS_X":"2","POS_Y":"4"}}

This is how it was intended and works, my issue is that upon running the function again it completely overwrites the previous JSON in the file, and this is obviously bad.
My questions are:

*

*How can I add new JSON objects inside the entire file, or at specific points, like "addObject("GENERAL", ...)" for this example?

*How can I make this better?
I'm fairly new to Kotlin and have been coding in Java mostly, so Java solutions are fine as I'm sure I'll be able to convert it.
Thanks in advance!
EDIT: New Code, no idea how to implement it:
fun UpdateJson(path: String, name: String, value: String){
    var gson = Gson()
    var reader: FileReader = FileReader(File(path))

    val type = object : TypeToken<Map<String, String>>() {}.type
    println("Type: " + type.toString())
    println("Existing Json: ${gson.fromJson<Map<String,String>>
    (JsonReader(reader), type)}")
    var existingJson: Map<String, String> =
    gson.fromJson<Map<String,String>>(JsonReader(reader), type)
    existingJson.put(name, value)
    FileWriter(File(path)).use({ writer ->
    writer.write(gson.toJson(existingJson)) })
}

A: The easiest way is to, as @KrisRoofe suggested, read the json, then add an element. I would do this by converting the existing json in the file to a Map. Since you don't actually care about the existing json, all you want to do is add a new entry to that Map. Once you do that, simply write the new Map to the File. You can do this like so:
public class UpdateJson {
    public static void main(String[] args) throws IOException {
        addObject("example.json", "GENERAL", arrayOf(arrayOf("POS_X","2"), arrayOf("POS_Y","4")));
    }

    private static void addObject(String fileName, String newObjName, String newObjValue) throws IOException {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> existingJson = gson.fromJson(new JsonReader(new FileReader(new File(fileName))), type);
        existingJson.put(newObjName, newObjValue);
        try (FileWriter writer = new FileWriter(new File(fileName))) {
            writer.write(gson.toJson(existingJson));
        }
    }

    private static String arrayOf(String s1, String s2) {
        return "[" + s1 + ", " + s2 + "]";
    }
}

EDIT:
The above solution is a Java solution. There seems to be an issue with the Type in Kotlin.

*

*This Stack Overflow question has a workaround by using object:

*Also, note that to use reflection with Kotlin, you need a separate jar, according to Kotlin documentation'

EDIT 2: Provided Kotlin Answer:
fun main(args: Array<String>) {
    addObject("example.json", "GENERAL", arrayOf(arrayOf("POS_X", "2"), arrayOf("POS_Y", "4")))
}

fun addObject(path: String, name: String, value: String) {
    val gson = Gson()
    val reader: FileReader = FileReader(File(path))
    val type = object : TypeToken<Map<String, String>>() {}.type
    System.out.println("Type: " + type.toString())
    val existingJson = gson.fromJson<Map<String, String>>(JsonReader(reader), type)
    System.out.println("Existing Json: ${existingJson}")
    val newJsonMap = existingJson.plus(Pair(name, value))
    FileWriter(File(path)).use(
        { writer -> writer.write(gson.toJson(newJsonMap)) }
    )
}

fun arrayOf(s1: String, s2: String): String {
    return "[$s1, $s2]"
}


text:
Q: How to save text within a textarea to localstorage I need to save text within an textarea with localStorage.
Here is the HTML code:

.textarea {
  background: none;
  color: lime;
  font-size: 1.25rem;
  border: 0px;
  width: 100%;
  height: 100vh;
  display: inline-block;
  outline: none;
  resize: none;
  text-align: center;
}
<textarea class="textarea" id="notes" value="Type something!">
Delete this and start typing!</textarea>

How can I save the text locally? Searches did not get me anywhere.

A: It sounds like localStorage is a better option for your use case.
That said, you can get your textarea value with:
document.getElementById("notes").value

After that, as you can see in this answer, you can use
function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

So to summarize, you can create your cookie with something like the following:
let value = document.getElementById("notes").value;
createCookie('textareaValue', value, 0);

UPDATE
Since you updated your question to only use localStorage, you can use this:
let value = document.getElementById("notes").value;
localStorage.setItem("textareaValue", value);

You can retrieve and display the value with:
let value = localStorage.getItem('textareaValue');
document.getElementById("notes").value = value;

A: I assume, you just want to modify document.cookie by hand:
document.cookie = "mytext=stuff"
// this will add "mytext" key to page cookies and assign "stuff"

document.cookie = "mytext=newstuff"
// this will modify your key, cookies works just like associative array

document.cookies = "mytext=;max-age=0"
// this will delete your cookie by setting its max age to 0, so cookie is being considered expired now

Stack Overflow has a nice thread on this topic: How to get and set cookies in JavaScript.
In order to grab the text from your <textarea> you might want to use my_html_element.value, where my_html_element is HTML node.
Also the following syntax might be useful:
let variable = "some text";
`string${variable}` // stringsome text

A: Assuming you are using Javascript with your html, here is already something that is available on stack overflow:
See here


text:
Q: Python socket check list of server to see if port open My function accepts a list of ldpa servers and checks if port 389 is listening on list of servers
Read and reviewed example on python socket but still not doing what i expect.
        def check_server_ldap_port_open(self, domain_controller: list):
        """ check if LDAP port 389 is listening on list of domain controller and returns the first DC listening in list """

        s = socket.socket()
        i = 0

        print('DC', domain_controller)
        while i < len(domain_controller):
            print(i)

            try:
                print('dc#',i ,domain_controller[i])
                s.settimeout(2)
                result_s = s.connect_ex((domain_controller[i], LDAP_PORT_NUMBER))
                print('result_s', result_s)

                if result_s == 0:
                    print('dc', domain_controller[i])
                    return domain_controller[i]
            except socket.error as err:
                raise err
            finally:
                i += 1
                s.close()

From testing my function on windows 10 desktop, if it checks a server where port 389 is not listening, it moves on to the next server in the list. But i get the following error below. I always get this error if the first server it receives to check the port is not listening. If I receive a different server where ldap 389 is listening, it works as expected.
I get this error only when the first server to be check is not listening on 389 and it goes to check next server but get WinError 10038. From my search online, its because i'm using windows, but would like confirmation and if theres a work around?
DC ['ProblemSRV.abc.domain.', 'GoodSRV1.abc.domain.', 'GoodSRV2.abc.domain.']
0
dc# 0 ProblemSRV.abc.domain.
result_s 10035
1
dc# 1 GoodSRV1.abc.domain.
[2019-08-14 13:25:53,755] ERROR in app: Exception on /v1/nas/app_share/UK/DATA-PRD/ABC\user1/ABC\user2/ [POST]
Traceback (most recent call last):
  File "C:\Miniconda3-Windows-x86_64\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Miniconda3-Windows-x86_64\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Miniconda3-Windows-x86_64\lib\site-packages\flask_restplus\api.py", line 313, in wrapper
    resp = resource(*args, **kwargs)
  File "C:\Miniconda3-Windows-x86_64\lib\site-packages\flask\views.py", line 84, in view
    return self.dispatch_request(*args, **kwargs)
  File "C:\Miniconda3-Windows-x86_64\lib\site-packages\flask_restplus\resource.py", line 44, in dispatch_request
    resp = meth(*args, **kwargs)
  File "D:\workspace\api\core\decorators.py", line 79, in wrapper
    return _function(*args, **kwargs)
  File "D:\workspace\api\nas\controllers\nas.py", line 93, in post
    my_nas_share = NasShare(country, share_name, primary_owner, secondary_owner, dept_mailbox, trigram)
  File "D:\workspace\api\nas\models\nas.py", line 82, in __init__
    if not self.check_dept_mailbox(dept_mailbox):
  File "D:\workspace\api\nas\models\nas.py", line 414, in check_dept_mailbox
    domain_controller = self.check_server_ldap_port_open(hermes_dc_list)
  File "D:\workspace\api\nas\models\nas.py", line 356, in check_server_ldap_port_open
    raise err
  File "D:\workspace\api\nas\models\nas.py", line 348, in check_server_ldap_port_open
    s.settimeout(2)
OSError: [WinError 10038] An operation was attempted on something that is not a socket

A: The issue is the fact that your socket, s, is created at the start of the function.  Later on in your code, you close the socket, and then in the next iteration try to change the timeout.  Python cannot do this because it is closed, so is no longer a socket.  Instead, put s = socket.socket() at the start of each loop, and then it is recreated.
The reason why the try … catch … finally doesn't work is because when you catch the exception, you re-raise it with raise err, so the error still occurs.  Instead you could use it to ignore the error, and move on to the next iteration.  Having said that, the error handling shouldn't be necessary with the new code, as it no longer causes any errors.
Some other changes I made are to change the while loop to a for loop so you don't have to increment i yourself, and I put s.close() as soon as you have your result, so that your socket isn't left open if you find a server that is listening. (It shouldn't matter as Python does have garbage collection, but it's good practice...)
Full listing:
def check_server_ldap_port_open(self, domain_controller: list):
    """ check if LDAP port 389 is listening on list of domain controller and returns the first DC listening in list """

    for i in range(len(domain_controller)):

        s = socket.socket()
        s.settimeout(2)

        result_s = s.connect_ex((domain_controller[i], LDAP_PORT_NUMBER))

        s.close()

        if result_s == 0:
            return domain_controller[i]


text:
Q: Pine Script: how could i add a short position to this script? ``//@version=4
strategy(title="Take profit (% of instrument price)", overlay=true, pyramiding=1)

// STEP 1:
// Make inputs that set the take profit % (optional)

FastPeriod = input(title="Fast MA Period", type=input.integer, defval=9, minval=1, group="Moving Average")
SlowPeriod = input(title="Slow MA Period", type=input.integer, defval=50, minval=1, group="Moving Average")

TP1Perc = input(title="Long Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=0.5, group="TP & SL")
TP2Perc = input(title="Long Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=1, group="TP & SL")
SLPerc = input(title="Long Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=0.5, group="TP & SL")

TP1_Ratio = input(title="Sell Postion Size % @ TP1", type=input.float, defval=50, step=1, group="TP & SL", tooltip="Example: 50 closing 50% of the position once TP1 is reached")/100

// Calculate moving averages
fastSMA = ema(close, FastPeriod)
slowSMA = ema(close, SlowPeriod)

// Calculate trading conditions
enterLong  = crossover(fastSMA, slowSMA)
enterShort  = crossunder(fastSMA, slowSMA)

// Plot moving averages
plot(series=fastSMA, color=color.green, title="Fase MA")
plot(series=slowSMA, color=color.red, title="Slow MA")

// STEP 2:
// Figure out take profit price
percentAsPoints(pcnt) =>
    strategy.position_size != 0 ? round(pcnt / 100.0 * strategy.position_avg_price / syminfo.mintick) : float(na)

percentAsPrice(pcnt) =>
    strategy.position_size != 0 ? ((pcnt / 100.0) + 1.0) * strategy.position_avg_price : float(na)

current_position_size = abs(strategy.position_size)
initial_position_size = abs(valuewhen(strategy.position_size[1] == 0.0, strategy.position_size, 0))

TP1  = strategy.position_avg_price + percentAsPoints(TP1Perc) * syminfo.mintick * strategy.position_size / abs(strategy.position_size)
TP2  = strategy.position_avg_price + percentAsPoints(TP2Perc) * syminfo.mintick * strategy.position_size / abs(strategy.position_size)
SL   = strategy.position_avg_price - percentAsPoints(SLPerc) * syminfo.mintick * strategy.position_size / abs(strategy.position_size)

// Submit entry orders
if (enterLong)
    strategy.entry(id="Long", long=true)

// STEP 3:
// Submit exit orders based on take profit price

if strategy.position_size > 0
    strategy.exit("TP1", from_entry="Long", qty = initial_position_size * TP1_Ratio, limit = TP1, stop = SL)
    strategy.exit("TP2", from_entry="Long", limit = TP2, stop = SL)

// Plot take profit values for confirmation
plot(series=(strategy.position_size > 0) ? TP1 : na, color=color.green, style=plot.style_circles, linewidth=1, title="Take Profit 1")
plot(series=(strategy.position_size > 0) ? TP2 : na, color=color.green, style=plot.style_circles, linewidth=1, title=" Take Profit 2")
plot(series=(strategy.position_size > 0) ? SL : na, color=color.red, style=plot.style_circles, linewidth=1, title="Stop Loss")
`
`

i tried to add a short postion but when ever i go to adjust the SL and TP of the short even if i did put if strategy.position_size < 0 nothing seems to happen or change. please help me out. i did the exact same for the short condition but changed TP1 to TP1_S and all of those parameters to identify when i edit.

A:
// Submit entry orders
if (enterLong)
    strategy.entry("Long", strategy.long)

if (enterShort)
    strategy.entry("Short", strategy.short)

// STEP 3:
// Submit exit orders based on take profit price

if strategy.position_size > 0
    strategy.exit("TP1_LONG", from_entry="Long", qty = initial_position_size * TP1_Ratio, limit = TP1, stop = SL)
    strategy.exit("TP2_LONG", from_entry="Long", limit = TP2, stop = SL)

if strategy.position_size < 0
    strategy.exit("TP1_SHORT", from_entry="Short", qty = initial_position_size * TP1_Ratio, limit = TP1, stop = SL)
    strategy.exit("TP2_SHORT", from_entry="Short", limit = TP2, stop = SL)


text:
Q: Python & Selenium: Find element by text in span class I'm trying to find an element, but it doesn't have any ID nor anything else. HTML looks basically like this:

   A

   B

I'm trying to find the B element on every page, but its position varies every time, so I can't use span[1] or n-th child(1). How can I do this?

A: Use this xpath selector, its the best way when selecting text
//span[@class='item_selection_number'][contains(text(),'B')]


text:
Q: How to convert complex xml to csv using python i need to convert xml into csv. i tried xmlutils library i couldn't get expected fields. actually my xml doesn't have common tags in the xml tree.
xml sample:
<service.className>
    <Id>3001</Id>
    <sId>12.*</sId>
    <qId>1</qId>
    <timeR>123</timeR>
    <pId>1/1/7</pId>
    <sMode/>
    <highipvalue>1</highipvalue>
    <highipvalue2>1</highipvalue2>
    <highipvalue3>1</highipvalue3>
</service.className>
<service.className>
    <Id>3001</Id>
    <sId>12.*</sId>
    <policy>2</policy>
    <timeR>123</timeR>
    <pId>1/1/7</pId>
    <sMode>mode1</sMode>
    <medipvalue>1</medipvalue>
    <medipvalue2>1</medipvalue2>
    <medipvalue3>1</medipvalue3>
</service.className>
<service.className>
    <Id>3001</Id>
    <sId>12.*</sId>
    <policy>3</policy>
    <timeR>123</timeR>
    <pId>1/1/7</pId>
    <sMode>mode2</sMode>
    <lowipvalue>1</lowipvalue>
    <lowipvalue2>1</lowipvalue2>
    <lowipvalue3>1</lowipvalue3>
</service.className>

and so on repeating.......
the expected csv output:
Id  sId qid policyid    timeR   pId sMode   highipvalue highipvalue2    highipvalue3    medipvalue  medipvalue2 medipvalue3 lowipvalue  lowipvalue2 lowipvalue3
3001    12.*    1   0   123 1/01/2007   0   1   1   1   0   0   0   0   0   0
3001    12.*    0   2   123 1/01/2007   mode1   0   0   0   1   1   1   0   0   0
3001    12.*    0   3   123 1/01/2007   mode2   0   0   0   0   0   0   1   1   1

but now i'm getting fields in csv only first element tree of xml like below
Id  sId qid policyid    timeR   pId sMode   highipvalue highipvalue2    highipvalue3
3001    12.*    1   0   123 1/01/2007       1   1   1
3001    12.*    0   2   123 1/01/2007   mode1   1   1   1
3001    12.*    0   3   123 1/01/2007   mode2   1   1   1

code i tried:
import xml.etree.ElementTree as et
from xmlutils.xml2csv import xml2csv
out_csv_path=csv path
in_xml_path=xml path
converter = xml2csv(in_xml_path, out_csv_path, encoding="utf-8")
converter.convert(tag="className",buffer_size=1000,quotes=False)

any help much appreciated.
Advance Thanks,
Mani


text:
Q: Pauli principle before big bang i understand that the Pauli exclusion principle states that two fermions cannot occupy the same quantum state.
This question is not about a black hole. It is more about the singularity at moment of the big bang, that had every mass in the universe in a single point, that had no spatial extension.
The uncertainty principle states that it gives a fundamental limit to the limit with which certain pairs of properties of particles can be known.
I understand that a singularity has no spatial extension.
Question:

*

*Does a singularity  (especially at the moment of big bang) violate the Pauli principle? So the principles were not in force before the Big Bang?

A: A singularity does not violate the Pauli principle, because the composition of a black hole is fundamentally untestable.  If two fermions fall into a black hole, maybe they annihilate, maybe they don't, but in the end you could never observe the inside of the black hole and see that it is made up of separate parts.  And as the saying goes: if it's not testable (in principle), it's not physics.
Black holes can have spin, and so it might be possible for the entire black hole to in fact be fermionic, but that's not the same as having multiple constituent parts that are fermionic.
Your question is a great gateway to the discussion of what exactly happens to all the information about these pieces that have fallen into a black hole.  See black hole complementarity and the "firewall" to read more about that.


text:
Q: How to check URL with IdHTTP? How can I check for the target URL for specific response code like 200 OK without Indy throwing all sorts of exceptions out. ConnectionTimeout,ConnectionClosedGracefully, etc...
For example if URL is not proper or its host cannot be found or cannot be reached. Indy will still rise exceptions even though i tried to ignore them.
So my question is how to properly ignore these exceptions.

A: A plain try/except should do the trick:
try
  IdHttp1.Get(...);
  Result:=IdHttp1.ResponseCode=200;
except on EIdException do
  Result:=false;
end;

A: 1. How to ignore all exceptions thrown by the TIdHTTP ?
To handle all exceptions and, as you say, ignore them, you may use the code that is almost identical to the code from @Stijn's answer:
procedure TForm1.Button1Click(Sender: TObject);
var
  IdHTTP: TIdHTTP;
begin
  IdHTTP := TIdHTTP.Create;
  try
    try
      IdHTTP.Get('http://www.example.com');
    except
      // do just nothing here, if you really want to completely ignore all
      // exceptions thrown from inside the try..except block execution and
      // if you don't want to indicate somehow, that the exception occured
    end;
  finally
    IdHTTP.Free;
  end;
end;

2. How to handle specific exceptions thrown by the TIdHTTP ?
Maybe one day you'll want to react somehow on certain types of exceptions thrown by TIdHTTP class, e.g. react only on HTTP protocol exceptions. And that's what I'll try to elaborate here.
Indy defines many exception classes for different occasions, that may occur when a certain action fails. Here is a list of exception classes, that you might be interested in when you're working with HTTP protocol:

*

*EIdException - it is the base exception class used by Indy library. It might be useful for you when you want to distinguish between exceptions raised by Indy and all other exceptions thrown by your application.

*EIdSocketError - from a HTTP protocol abstraction point of view it's a low level exception class, which covers all exceptions raised when a certain socket operation fails. This can be useful for you to detect, that there is something wrong at your network level.

*EIdConnClosedGracefully - exceptions raised by this class indicate, that the server side closed the connection with the client in a common way. This can be useful when you'd need to react to this situation, e.g. by reconnecting to the server.

*EIdHTTPProtocolException - this exception class is used for exceptions thrown, when an error occurs during processing of a HTTP response for a certain request. This generally happens, when an unexpected numeric HTTP response code is received from the HTTP response. It can be useful, when you want to handle HTTP protocol errors specifically. By this exception handling, you can e.g. react on certain HTTP status codes returned by a server response.
Here is the code skeleton showing handling of the exceptions listed above. Of course, you don't have to show messages, but do something more useful. And, you don't need to handle all of them; it's upon you which exceptions and how you will handle:
uses
  IdHTTP, IdException, IdStack;

procedure TForm1.Button1Click(Sender: TObject);
var
  IdHTTP: TIdHTTP;
begin
  IdHTTP := TIdHTTP.Create;
  try
    try
      IdHTTP.Get('http://www.example.com');
    except
      // this exception class covers the HTTP protocol errors; you may read the
      // response code using ErrorCode property of the exception object, or the
      // same you can read from the ResponseCode property of the TIdHTTP object
      on E: EIdHTTPProtocolException do
        ShowMessage('Indy raised a protocol error!' + sLineBreak +
          'HTTP status code: ' + IntToStr(E.ErrorCode) + sLineBreak +
          'Error message' + E.Message);
      // this exception class covers the cases when the server side closes the
      // connection with a client in a "peaceful" way
      on E: EIdConnClosedGracefully do
        ShowMessage('Indy reports, that connection was closed gracefully!');
      // this exception class covers all the low level socket exceptions
      on E: EIdSocketError do
        ShowMessage('Indy raised a socket error!' + sLineBreak +
          'Error code: ' + IntToStr(E.LastError) + sLineBreak +
          'Error message' + E.Message);
      // this exception class covers all exceptions thrown by Indy library
      on E: EIdException do
        ShowMessage('Indy raised an exception!' + sLineBreak +
          'Exception class: ' + E.ClassName + sLineBreak +
          'Error message: ' + E.Message);
      // this exception class is a base Delphi exception class and covers here
      // all exceptions different from those listed above
      on E: Exception do
        ShowMessage('A non-Indy related exception has been raised!');
    end;
  finally
    IdHTTP.Free;
  end;
end;


text:
Q: Pycharm displays an anomally when running a pygame code I am having a weird display when I run a simple Pygame. The game runs perfectly but the screen is weird.
Here's the code:
import pygame

pygame.init()

window = pygame.display.set_mode((500, 500))
pygame.display.set_caption('First Game')
pygame.display.update()

x = 50
y = 50
width = 40
height = 60
vel = 5

run = True

while run:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    pygame.draw.rect(window, (255, 0, 0), (x, y, width, height))
pygame.quit()

A: You need to update the screen every frame. Put pygame.display.update() inside your main_loop, and remove it from original positon:
while run:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    pygame.draw.rect(window, (255, 0, 0), (x, y, width, height))
    pygame.display.update()

This should work


text:
Q: Truth Table all possible combinations I am currently working on an assignment for school but I'm lost when it comes to implementing into code.
The idea of the assignment is to create multiple True and False tables of (p, q, r, Proposition). The values p, q, r, can be hard coded in meaning I can just create an array with the values and I do not have to worry about those. But when it comes to the last array proposition I have to create all possible combinations out of an array length 8 and print them out.
The thing is I been searching and I can't find something related to this. I'm not asking to do the assignment for me but I want know if someone can explain to me how is it done. This is so far the code I have made it's not much but you can actually tell I'm stuck, also when I asked they told me it's possible to do it in 8 nested loops so I'm currently working on this feedback is appreciated. Thanks
public class truthTables {

  public static void main(String[] args) {

    boolean t = true;

    boolean f = false;

    boolean[] p = {f, f, f, f, t, t, t, t};
    boolean[] q = {f, f, t, t, f, f, f, f};
    boolean[] r = {f, t, f, t, f, t, f, t};
    boolean[] proposition = new boolean[8];
    int tableNumber = 1;

    while (tableNumber <= 256) {

      System.out.println("Table " + tableNumber + " ");
      System.out.println("P " + " q " + " r " + " proposition ");
      System.out.println("________________");

      int i = 0;

      while (i <= 7) {
        i = i;

        if (proposition[i] = true) {

          System.out.println(p[i] + "  " + q[i] + "  " + r[i] + " " + proposition[i]);
        }

        if (proposition[i] = false) {
          System.out.println(p[i] + "  " + q[i] + "  " + r[i] + " " + proposition[i]);
        }

        i = i + 1;
      }

      tableNumber = tableNumber + 1;
    }
  }
}

A:
I have to create all possible combinations out of an array length 8

You can create the tableNumber-th table by checking its bits:
int b = 0;            // "Bit index", the element of proposition you are going to set.
int t = tableNumber;  // Copy of tableNumber that you can update.

while (t != 0) {
  proposition[b] = (t & 1) != 0;  // Is the least significant bit 1?

  b++;       // Increase the bit index.
  t >>>= 1;  // Right-shift by 1, chopping off the least significant bit.
}

You can write this as a for loop too:
for (int b = 0, t = tableNumber; t != 0; t >>>=1, b++) {
  proposition[b] = (t & 1) != 0;
}

A: I think the first part that you are getting stuck on is the fact that you aren't editing your proposition array with anything new. So within your while loop you need to have this
for (j = 0; j < 8; j++) {
    if (((tableNumber >> i) & 1) == 1) {
        proposition[i] = t;
    } else {
        proposition[i] = f;
    }
}

which I got from this post. It will give you an array of
table 0: f, f, f, f, f, f, f, f
table 1: f, f, f, f, f, f, f, t
table 2: f, f, f, f, f, f, t, f
table 3: f, f, f, f, f, f, t, t
.
.
.
table 255: t, t, t, t, t, t, t, t

Then you have to have a table number start at 0, then you can display them as this
public class truthTables {

  public static void main(String[] args) {

    boolean t = true;
    boolean f = false;

    boolean[] p = {f, f, f, f, t, t, t, t};
    boolean[] q = {f, f, t, t, f, f, f, f};
    boolean[] r = {f, t, f, t, f, t, f, t};
    boolean[] proposition = new boolean[8];
    int tableNumber = 0; // start at 0

    while (tableNumber < 256) {

      System.out.println("Table " + (tableNumber + 1) + " ");
      System.out.println("P " + " q " + " r " + " proposition");
      System.out.println("________________");

     /** add code here **/
      for (j = 0; j < 8; j++) {
        if (((tableNumber >> j) & 1) == 1) {
            proposition[j] = t;
        } else {
            proposition[j] = f;
        }
      }
      /** to here **/

      int i = 0;

      while (i <= 7) {
        System.out.println(p[i] + "  " + q[i] + "  " + r[i] + " " + proposition[i]);

        i = i + 1;
      }

      tableNumber = tableNumber + 1;
    }
  }
}

Basically what you are doing is taking the table number, breaking it down into its bit components of 0 - 255 which in bits is 00000000 - 11111111 which is every table combination you are looking for. There are other ways you can code this that will save space, but I tried following your coding style.
EDIT: one of which is avoid the for loop all together and calculating the correct value in your while loop.
      int i = 0;

      while (i <= 7) {
        boolean propositionBool = ((tableNumber >> i) & 1) == 1;
        System.out.println(p[i] + "  " + q[i] + "  " + r[i] + " " + propositionBool);

        i = i + 1;
      }


text:
Q: install custom middleware into hubot's express Is there a way to install my own custom middleware into the express object provided by hubot?
I wanted to use code like this, but I never see the messages "Added middleware" or "Initializing express". I was using code I found here as a model.
Can I override setupExpress somehow? Or, is there a way to subclass Robot to do this?
    # Setup our own express handler
    express = require 'express'
    robot.express = app = express()
    app.use require 'body-parser'

    app.use (req, res, next) ->
            robot.logger.info "Added middleware"
            req.rawData = ''
            req.on 'data', (chunk) ->
                    req.rawData += chunk

            req.on 'end', () ->
                    next()

    robot.logger.info "Setting up new express module"

    robot.emit 'express-loaded', @
    @loaded = true

    @init = (port, bindAddress) =>
            robot.logger.info "Initializing express"
            unless @initialized
                    try
                            @server = app.listen( port || process.env.PORT || 8080, bindAddress || process.env.BIND_ADDRESS || '0.0.0.0' )
                            @router = app
                            @initialized = true
                    catch err
                            robot.logger.error "Error trying to load"
                            process.exit 1
            @


text:
Q: Linux Shell Script For Each File in a Directory Grab the filename and execute a program Scenario :
A folder in Linux system. I want to loop through every .xls file in a folder.
This folder typically consists of various folders, various filetypes (.sh, .pl,.csv,...).
All I want to do is loop through all files in the root and execute a program only on .xls files.
Edit :
The problem is the program I have to execute is 'xls2csv' to convert from .xls to .csv format. So, for each .xls file I have to grab the filename and append it to .csv.
For instance, I have a test.xls file and the arguments fro xls2csv are : xls2csv test.xls test.csv
Did I make sense?

A: find . -type f -name "*.xls" -printf "xls2csv %p %p.csv\n" | bash

bash 4 (recursive)
shopt -s globstar
for xls in /path/**/*.xls
do
  xls2csv "$xls" "${xls%.xls}.csv"
done

A: bash:
for f in *.xls ; do xls2csv "$f" "${f%.xls}.csv" ; done

A: for i in *.xls ; do
  [[ -f "$i" ]] || continue
  xls2csv "$i" "${i%.xls}.csv"
done

The first line in the do checks if the "matching" file really exists, because in case nothing matches in your for, the do will be executed with "*.xls" as $i. This could be horrible for your xls2csv.

A: Look at the find command.
What you are looking for is something like
find . -name "*.xls" -type f -exec program

Post edit
find . -name "*.xls" -type f -exec xls2csv '{}' '{}'.csv;

will execute  xls2csv file.xls file.xls.csv
Closer to what you want.


text:
Q: Difficulties with SQL query and COUNT thanks in advnace for reading this. I'm not really good with SQL so please pardon any stupid mistake...
Here is the deal, I have four tables (i'm only going to give the basic fields, and dependencies between tables, for the sake of simplicity):

*

*Company: companyId, companyName

*User: userId, userName

*Project: projectId, projectUserId, projectCompanyId, projectDate

*Study: studyProjectId

The dependencies are like so:

*

*A project is for a client (projectUserId) and carried out by a company (projectCompanyId)

*There can be many studies for the same project, but each study is for one project (studyProjectId)

Here is the kind of request I'd like to write, but it doesn't work right now:
SELECT
    project.projectId,
    company.companyName,
    user.userName,
    COUNT( study.studyId ) AS numberStudies
FROM project, company, user, study
WHERE company.companyId = project.projectCompanyId,
AND user.userId = project.projectUserId,
AND study.studyProjectId = project.projectId
ORDER BY company.companyId, user.userId, project.projectDate;

It returns one record for which numberStudies equals the total number of studies. If I remove the COUNT from the SELECT, then I get the type of result I want, but without the column numberStudies (of course). Hoping you understand what I'm trying to get, what am I doing wrong here?
Thanks again in advance :)
EDIT: If possible, I'd like the request to show records even when numberStudies is 0.

A: As in the comments, you need a GROUP BY clause when you want to have aggregate results (like it seems you want: "Number of Studies per project, company and user"). So, the first thing to do is add:
GROUP BY project.projectId, company.companyName, user.userName

Notice that the three columns are exactly the three that you have (unaggregated) in the SELECT list.
SELECT
    project.projectId,
    company.companyName,
    user.userName,
    COUNT(study.studyId) AS numberStudies
FROM project, company, user, study
WHERE company.companyId = project.projectCompanyId,
  AND user.userId = project.projectUserId,
  AND study.studyProjectId = project.projectId
GROUP BY project.projectId, company.companyName, user.userName
ORDER BY company.companyId, user.userId, project.projectDate ;

This will show what you want but there are still a few issues:

*

*First, you are using the old (SQL-89) syntax of implicit joins with the conditions in the WHERE clause. This syntax is not deprecated but the new (well, 20 years old SQL-92) syntax with the JOIN keyword has several advantages.

*We can add aliases for the tables for readability.

*There may be two companies or users with same name so we should group by their IDs, not only their names.

*One advantage of explicit JOIN syntax is that it's easy to have results when there are no rows to join (as you want to show when there is no studies for a project). Just LEFT JOIN the study table.

So, the query becomes:
    SELECT
        p.projectId,
        c.companyName,
        u.userName,
        COUNT(s.studyId) AS numberStudies
    FROM
        project AS p
      JOIN
        company AS c  ON c.companyId = p.projectCompanyId
      JOIN
        user AS u     ON u.userId = p.projectUserId
      LEFT JOIN
        study AS s    ON s.studyProjectId = p.projectId
    GROUP BY
        c.companyId,
        u.userId,
        p.projectId,
        c.companyName,  u.userName
    ORDER BY
        c.companyId,
        u.userId,
        p.projectDate ;

A: you probably need a LEFT JOIN between study and project


text:
Q: Closed expression for $y^{(n)}$ when $y' = ay$ I'm interested in tidying up the calculation of arbitrarily high order derivatives of a function containing an exponential. Although any function can have it's derivative expressed as
$$\frac{\mathrm{d}y}{\mathrm{d}x} = y' = ay $$
for the functions I'm working with $a$ is simpler than the function as a whole. If we keep differentiating:
$$y'' = ay' + ya' = y (a^{2} + a') $$
$$y''' =  y (a^{3} + 3aa' + a'') $$
We always end up with the form $y^{(n)} = y f(a)$. We could also define the coefficient on $y$ recursively:
$$ y^{(n)} = b_{n}y$$
$$b_{0} = 1$$
$$b_{1} = a$$
$$b_{n+1} = b_{n} a + b'_{n}$$
Does a closed expression exist for $b_{n} = f(a)$?
I've evaluated the $b_{n}$ by hand up to $b_{5}$ by which point it starts getting messy and I can't see an obvious pattern.

A: Not an answer, but here is a possible way to attack this. From Leibnitz formula on $y' = ay$ we get
$$y^{(n+1)} = \sum_{k=0}^n{n\choose k} y^{(k)}a^{(n-k)}$$
giving us the following recursion formula
$$b_{n+1} = \sum_{k=0}^n{n\choose k} b_ka^{(n-k)}$$
for $b_n$ which avoids the derivative of $b_n$ in the recursion.
We can also guess (and then confirm using the formula above) a few of the terms in $b_n$:
$$b_n = a^n + {n\choose 2} a^{n-2}a' + \ldots+ a^{(n)}$$
Getting a general formula for the $\ldots$ in terms of all the possible $a^{(k)}$ combinations seems like a hard problem since $b_n$ will contain all possible terms on the form $a^{k_0} [a^{(k_1)}]^{r_1}[a^{(k_2)}]^{r_2}\ldots [a^{(k_i)}]^{r_i}$ where $k_0 + \sum (k_j+1)r_j = n$.


text:
Q: how to make app cannot quit without password? I need to write an apps for tutorial class company. The company would like an apps which force users stay in the apps. Users cannot quit the apps with any method like press "home" button or back button. In the apps, there will be a button in apps called "quit". Users press this button and enter password to quit the apps.
I know how to disable and override the back button but cannot do well with home button and the  switching apps button.
Therefore, is there any good example which can do force user stay in the apps?


text:
Q: How to clone project from the GitHub in Android studio Hello all I am trying to clone the project from github. Is downloading the zip folder and loading it into the android studio the same as cloning from Github ?

A: You can use this image :
File - > new -> Project from Version control -> GitHub

A: For cloning project from the terminal.
Step 1: Click this button:

Step 2: Copy the link.
Step 3: Open the terminal, make sure you are in the folder where you want to clone the project. If you are not then just type: cd theDesiredFolderLocation.
Next command: git clone copiedLinkPath.

A: On github web, go to the repo you want yo clone and click on the download button (code) then copy the url where it says clone with https.
In Android Studio 4.0, go to VCS (if you've added a github plugin) then click on Get From Version Control, it will load a window where you'll paste in the url you got from github.
That's it, AS will do the rest.

A: First go to the GitHub and to the repository you want to clone.
Click on the Code and copy the repository path
Next open your Android Studio. Make sure you have downloaded and installed git in your computer as well as set the git pathFile->Settings->Git->Test
Next Clone the project
File->New->Project From Version Control->Past the URL->Clone

A: In android studio 3.6.3
File > New > Project from Version Control > Git

Then go to GitHub.com
Click on clone or download button.
copy the url and paste it on the android studio.