text:
Q: I keep getting com.android.volley.RequestQueue.add on a null object reference error I need to display a a list of products from a JSON file, but I keep getting this error:
https://i.imgur.com/WEu4DzV.png
I tried moving everything in my code (so maybe I messed it up a little) and I can't get it to work. I'm a beginner, so errors like this are very hard to fix for me.
This is the fragment that produces the error:
package com.example.app;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class ListFragment extends Fragment {

private RecyclerView mRecyclerView;
private ListAdapter mListAdapter;
private ArrayList<Item> mList;
private RequestQueue mRequestQueue;
Context context;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_list, container, false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRecyclerView = view.findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mListAdapter);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        parseJSON();
        super.onActivityCreated(savedInstanceState);
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mList = new ArrayList<>();
        mListAdapter = new ListAdapter(context, mList);
}

private void parseJSON() {

        String url = "http://my_ip_adress/sestavsisvujsvetweb/api/seznammagnetek";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                int number = 0;
                try {
                    number = response.getInt("monumentid1");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String name = null;
                try {
                    name = response.getString("name1");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String region = null;
                try {
                    region = response.getString("region1");
                } catch (JSONException e) {
                e.printStackTrace();
                }

                mRequestQueue = Volley.newRequestQueue(context);
                mList.add(new Item(number, name, region));

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
        mRequestQueue.add(request); //this causes the problem, why? :(

}

}

A: The problem occurs because you are trying to add request into the requestQueue before knowing that it successfully retrieved your information. First, check if JsonObjectRequest has a onSuccess function, if not, then you need to add to requestQueue inside of the onResponse. Otherwise, android is synchronous so it will execute your line before actually retrieving the Json.
So the quick fix will be this:
if(request != null) {
   mRequestQueue.add(request);
}

This will make sure to not add if its null. Add this in your onCreate:
mRequestQueue = Volley.newRequestQueue(context);


text:
Q: What does '&' do in C/C++ and what is its equivalent operator in perl? I'm writing a perl implementation of a protocol whose specification is given for C/C++ but I don't know much C.
What does the condition if ((flags & 0x400) != 0) mean? How do I do that in perl?
Is if ($flags == "\x400") correct?

A: & is a bitwise AND. See Bitwise operators.
So flags is being treated as a series of bits, and then you AND it with something which has exactly the bit set that you want to check. If the result is non-zero, then the bit is set, otherwise the bit you were looking at isn't set. In particular, in your example 0x400 = 0100 0000 0000 is being used to check if the 11th bit is set (to 1) in flags.
Typically, you wouldn't use 0x400 but a named constant, so it is clear what that bit represents.
So if ($flags == "\x400") isn't correct. See Working with bits in Perl.
A common example of bit-masking can be seen in Linux file permissions.

A: It's the bitwise AND operator in C\C++ and Perl.

*

*Perl

*C\C++

A: The & operator performs a bitwise AND. In your case, if ((flags & 0x400) != 0) checks whether the eleventh bit of the flags variable is not set to 0. You can do bitwise operations in Perl, too.

A: It's the bitwise AND. In Perl, the operator is "&" as well.

A: & is the bitwise and operator, basically this is a test to see if a specific bit is set in the flags. See the perl equivalents here: http://perldoc.perl.org/perlop.html#Bitwise-And

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to load category names in drop down list I want to load only main categories(not sub-categories) name in drop down list. i have tried enough but could not succeed. There are numbers of answer on this site and I tried to solve my problem in that way but can't. The category table is given below, it is same as on cakephp docs in Tree.
categories table attribute
id | parent_id | lft| rght |name |
i tried these techniques given on following links
How to populate drop-down list with database values in CakePHP
full code of controller to create category is given below.
 if ($this->request->is('post')) {
            $this->Category->create();
            if ($this->Category->save($this->request->data)) {
                $this->Session->setFlash(__('Category has been saved.'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash(__('Unable to add Category.'));
        }
        else
          $categories = $this->Category->find('list');
          $this->set(compact('categories'));
           return $this;
      }

code of category.ctp is
  <?php echo $this->Form->create('Category'); ?>
        <fieldset>
        <legend><?php echo __('Add Category'); ?>
        </legend>
        <?php
                $form->input('id');
        //      echo $this->Form->input('id');
                echo $this->Form->input('name');

        ?>
        </fieldset>
        <?php echo $this->Form->end(__('Submit')); ?>
        </div>

now please suggest me solution to load data in drop down list.

A: you can put in controller
       $this->loadModel('Category');
       $categories = $this->Category->find('list');
       $this->set('categories',$categories));
put code of category.ctp is
           <?php if(isset($categories )){
             foreach ($categories as $key => $value) {
                  $id= $value['Category']['id'];
                  $options[$id]=$value['Category']['name'];
              }
           }
           echo $this->Form->select('Category.id', $options,array('class'=>'select2','data-  placeholder'=>'Choose a category','empty'=>''));
             ?>

It will work.

A: Stick to the conventions and everything's going to be ok. I assume you need the list in your add form to select the parent category (your intent btw is something that you should clarify in your question).
With trees you want to order by lft, so if you use find('list') you'll have to pass that in the order option, and in order to retrieve only the top-level categories you'll have to pass in a condition that matches all categories where parent_id is null (or the ID of a parent category whichs sub-categories are your "main" categories).
Controller
$parents = $this->Category->find('list', array(
    'conditions' => array(
        'Category.parent_id' => null
    ),
    'order' => array(
        'Category.lft' => 'asc'
    )
));
$this->set('parents', $parents);

View
echo $this->Form->input('parent_id');

For more information see

*

*http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html

*http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elements


text:
Q: How to insert csv file data into mysql database I want to insert data into mysql table from csv file. Import data from region_codes.csv file. In region_codes.csv file having 3 columns in 3rd columns it had , separated data, include those commas how to insert in mysql.
DROP TABLE IF EXISTS `region_codes`;
CREATE TABLE `region_codes` (
    `country_code` CHAR(2) NULL,
    `region_no` varchar(5) NOT NULL,
    `region` VARCHAR(45) NULL,
    INDEX `idx_country_code` (`country_code`)
) COLLATE='utf8_bin' ENGINE = MyISAM;

Using LOAD DATA LOCAL INFILE I import the data but only 1000 rows are imported outof 4066 rows.
LOAD DATA LOCAL INFILE 'C:/region_codes.csv' INTO TABLE `region_codes` FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

How to insert huge amount of data into mysql region_codes table from csv file.
Screenshot:

A: You can try below syntax if it works for you otherwise provide csv data:
LOAD DATA LOCAL INFILE 'C:/region_codes.csv' INTO TABLE `region_codes` FIELDS ESCAPED BY '\\' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n';

If above syntax does not work then export data by below command again and import by below given command.
select * into outfile 'C:/region_codes.csv' fields terminated by ',' optionally enclosed by '"' lines terminated by '\n' from `region_codes`;

Now use below command (to ignore column heading line)
LOAD DATA LOCAL INFILE 'C:/region_codes.csv' INTO TABLE `region_codes` FIELDS ESCAPED BY '\\' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES;

Note: If data is prepared manually then need to correct it manually.
If still not work then attach your csv data to check exact problem.

A: You can use mysqlimport tool this way:
mysqlimport  --ignore-lines=1 --fields-terminated-by=,
--columns='ID,Name,Phone,Address' --local -u root -p
Database /path/to/csvfile/TableName.csv

Here is a full explanation: http://chriseiffel.com/everything-linux/how-to-import-a-large-csv-file-to-mysql/


text:
Q: What does an exclamation mark in a property in Swift language? There are three way to declare a property in Swift:
var optStr: String?
var normStr: String = "normStr"
var exactStr: String!

The first one is property with an optional type, a type that can contain either nil or the String in our case. The second one is a property that always contain the String. It should be initialized in init or in the declaration.
But what about the third way?
var exactStr: String!

I made some experiments in the playground, and it turned out that a function that takes type? can take both type, type? and type! variables as an argument:
var optStr: String?
var normStr: String
var forcedStr: String!

func printStr(str: String?) {
    println("str: \(str)")
}

printStr(optStr) //prints: "str: nil"
//printStr(normStr) //doesn't compile as not initialized
printStr(forcedStr) //prints: "str: nil"

optStr = "optStr"; normStr = "normStr"; forcedStr = "forcedStr"

printStr(optStr) //prints "str: optStr"
printStr(normStr) //prints "str: normStr"
printStr(forcedStr) //prints "str: forcedStr"

So why and when should I use type!?
Update: this is not a duplicate of What does an exclamation mark mean in the Swift language?. I'm not asking about unwrapping a variable: I'm asking about declaring a property with an exclamation point (Type!).

A: It's a variable of type "implicitly-unwrapped optional String". Essentially, every access of implicitStr is treated as if it were written implicitStr! (thus unwrapping the value).
This, of course, will cause a crash if the value is nil. You can still test the implicit optional via if implicitStr != nil, or use it in optional chaining as var foo = implicitStr?.uppercaseString. So you can still use it just as safely as a normal optional; it's just biased toward the case where the value is not nil.
Implicitly-unwrapped optionals are quite useful in cases where the value may not be present at initialization, but are set early and unlikely to become nil again. (For example, a variable you set in -awakeFromNib might reasonably be an implicitly-unwrapped optional.)
Further, since Objective-C methods can return both nil and object types, their return values cannot be modeled as non-optional. To avoid requiring liberal use of forced unwrapping whenever dealing with Cocoa APIs, though, the parameters and return types of Cocoa APIs are usually represented as implicitly-unwrapped optionals.


text:
Q: Centering block in CSS I'm attempting to center the blue box (c_container) in the middle of the page such that it always remains there (while retaining it's horizontal length) regardless of browser stretching. It seems to default to the left regardless of any attributes I throw at it.
The c_container will be used to display content, while the header will leverage a dynamic menu to transition from page to page. The final challenge is getting the box to stay put in the center vertically and horizontally.
HTML (clip)
<!DOCTYPE html>

     <meta http-equiv="content-type" content="text/html; charset=utf-8">
     <link rel="stylesheet" type="text/css" href="css/style.css">
     <title>Page Title</title>
     <meta name="description" content="Write some words to describe your html page">

blah

blah

blah

CSS (clip)
p {
  align-content: center;
}

*{
  padding: 0;
  margin: 0;
  border: 0;
}

body{
  background-image: url('');
  background-repeat: repeat;
  background-color: #fff;
  height: 50px;
}

.blended_grid {
  display: block;
  width: 100%;
  overflow: auto;
  margin: 0px auto 0 auto;
}
.s_header{
  background-color : rgb(180, 71, 71);
  float: left;
  clear: none;
  height: 50px;
  width: 100%;

}

.c_container{
  position: absolute;
  /* box-align: center;  */
  background-color: rgb(99, 235, 240);
  margin: auto;
  width: 960px;
  top:20%;
  bottom:20%;
  /* height: 1050px; */
}

.f_body {
  background-color: rgb(35, 41, 36);
  position: fixed;
  left: 0;
  bottom: 0;
  float: left;
  clear: none;
  height: 50px;
  width: 100%;
}

.f_trim {
  position: absolute;
  height: 3px;
  width: 100%;
  background-color: rgb(39, 240, 73);
}

A: Like this? CLAC calculation left-width

*{
  padding: 0;
  margin: 0;
  border: 0;
}

body{
  background-image: url('');
  background-repeat: repeat;
  background-color: #fff;
  height: 50px;
}

.blended_grid {
  display: block;
  width: 100%;
  overflow: auto;
  margin: 0px auto 0 auto;
}
.s_header{
  background-color : rgb(180, 71, 71);
  float: left;
  clear: none;
  height: 50px;
  width: 100%;

}

.c_container{
  position: absolute;
  /* box-align: center;  */
  background-color: rgb(99, 235, 240);
  margin:auto;
  width: 960px;
  top:20%;
  bottom:20%;
  /* height: 1050px; */
    left:calc(50% - 480px); add this line
}

.f_body {
  background-color: rgb(35, 41, 36);
  position: fixed;
  left: 0;
  bottom: 0;
  float: left;
  clear: none;
  height: 50px;
  width: 100%;
}

.f_trim {
  position: absolute;
  height: 3px;
  width: 100%;
  background-color: rgb(39, 240, 73);
}

blah

blah

meathead

A:

p {
  align-content: center;
}

*{
  padding: 0;
  margin: 0;
  border: 0;
}

body{
  background-image: url('');
  background-repeat: repeat;
  background-color: #fff;
  height: 50px;
}

.blended_grid {
  display: block;
  width: 100%;
  overflow: auto;
  margin: 0px auto 0 auto;
}
.s_header{
  background-color : rgb(180, 71, 71);
  float: left;
  clear: none;
  height: 50px;
  width: 100%;

}

.c_container{
  position: absolute;
  /* box-align: center;  */
  background-color: rgb(99, 235, 240);
  margin: auto;
  width: 960px;
  top: 50%;
  left:50%;
  transform: translate(-50%,-50%);
  text-align: center;
  height: 50%;
  width: 100%;
  align-items: center;
  justify-content: center;
  display: flex;
  /*   top:20%;
  bottom:20%; */
/*   height: 1050px; */
}

.f_body {
  background-color: rgb(35, 41, 36);
  position: fixed;
  left: 0;
  bottom: 0;
  float: left;
  clear: none;
  height: 50px;
  width: 100%;
}

.f_trim {
  position: absolute;
  height: 3px;
  width: 100%;
  background-color: rgb(39, 240, 73);
}

blah

blah

blah


text:
Q: Stop Cursor Jumping in Input for LWC Resolution/Answer Below at bottom
Original Question
I have a LWC that end users use to complete a custom Search within Salesforce. We format the Search Bar to make reading the input clearer to the user. Unfortunately when users make a mistake in the middle of the search term and they click backspace or make an edit the cursor then jumps to the end of the search term. See the following Images:
Cursor is at the end:

Cursor is in the Middle ready to make an edit:

After edit is made (in this case - backspace) the cursor jumps to the End:

LWC - HTML:

                        <lightning-layout multiple-rows="false" vertical-align="end">
                            <lightning-layout-item flexibility="auto" padding="around-small">

                                        <lightning-input type="search" label="Account Number" onchange={handleCardSearchTerm}
                                            data-id="ANS" value={cardNumberFormating} max-length="19">
                                        </lightning-input>

                            </lightning-layout-item>
                            <lightning-layout-item flexibility="auto" padding="around-small">
                                <lightning-button label="Search" variant="brand" onclick={handleCMSearch}>
                                </lightning-button>
                            </lightning-layout-item>
                        </lightning-layout>

LWC - JS:
    handleCardSearchTerm(event) {

        event.preventDefault();

        console.log('Handling Search Term Update...');
        this.cardSearchTerm = event.detail.value;
        console.log('Search Term: ', event.detail.value);

        this.reformat(event.detail.value);

    }

    // Reformating Functionality
    reformat(value){

        // Goal to reformat card search func to look like CC format xxxx-xxxx-xxxx-xxxx
        console.log(value);

        var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
        var matches = v.match(/\d{4,16}/g);
        var match = matches && matches[0] || '';
        var parts = [];
        var i;
        for (i=0; i<match.length; i+=4) {
            parts.push(match.substring(i, i+4))
        }

        if(parts.length) {
            this.cardNumberFormating = parts.join('-');
        } else {
            this.cardNumberFormating = value;
        }

        console.log('Formatted Card Number: ', this.cardNumberFormating);

    }

Ideally after a user makes an update to the search term I would like the cursor to maintain its location rather than going to the end as it currently does.
Any suggestions on how this can be completed/Resolved?
ANSWER // RESOLUTION
So Salesforce/Lightning Web Components do not provide access to the selectionStart (or SelectionEnd) Property - at least not for <lightning-input>. So in order to make the property accessible the <lightning-input> had to be created via standard HTML. See Below:

    Account Number

        <svg class="slds-icon slds-input__icon slds-input__icon_left slds-icon-text-default"
            aria-hidden="true">
            <use
                xlink:href="/_slds/icons/utility-sprite/svg/symbols.svg?cache=9.37.1#search">
            </use>
        </svg>
        <input type="text" id="form-element-01"
            class="slds-input" maxlength="19" data-id="ANS"
            onkeyup={formatSearchTerm}/>

Once this was done I was able to access the property and update it via JS as described by sfdcfox below. I did so with the following:
    formatSearchTerm(event){

        event.preventDefault();
        console.log('Formatting Input');

        this.cardSearchTerm = event.target.value;
        console.log('Search Term: ', this.cardSearchTerm);

        // Goal to reformat card search func to look like CC format xxxx-xxxx-xxxx-xxxx
        let value = event.target.value;
        let oldLength = value.length;
        value = value.replace(/\D/g, "");
        let selectionStart = event.target.selectionStart;

        var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
        var matches = v.match(/\d{4,16}/g);
        var match = matches && matches[0] || '';
        var parts = [];
        var i;
        for (i=0; i<match.length; i+=4) {
            parts.push(match.substring(i, i+4))
        }

        if(parts.length) {
            value = parts.join('-');
        } else {
            value = value;
        }

        this.cardNumberFormating = value;

        if (oldLength == selectionStart) {
          selectionStart = value.length;
        }
        event.target.value = value;
        event.target.selectionStart = selectionStart;
        event.target.selectionEnd = selectionStart;
    }

Side Note: In my original code I used the 'value' attribute in the lightning-input and tried in the new recreated input element. This was causing issues for me accounting for the cursor jumping - this had to be removed.
Salesforce why would you move to standard HTML/JS development (LWC) but not make certain properties accessible? Doesn't make sense... Not that I don't love that you made the move, I do.

A: Before tinkering with the value, you need to keep track of selectionStart and selectionEnd, and then restore those values afterwards. What this means specifically depends on your needs, but here is a very basic demo. As you type it will add hyphens, and deleting will (mostly) navigate correctly. Note that I made this only as a quick demo. It has significant limitations, but hopefully it will help you.

import { LightningElement } from "lwc";

export default class App extends LightningElement {
  updateFormat(event) {
    let value = event.target.value;
    let oldLength = value.length;
    value = value.replace(/\D/g, "");
    let selectionStart = event.target.selectionStart;
    if (value.length > 5) {
      value =
        value.substr(0, 3) +
        "-" +
        value.substr(3, 2) +
        "-" +
        value.substr(5, 4);
    } else if (value.length > 2) {
      value = value.substr(0, 3) + "-" + value.substr(3, 2);
    }
    if (oldLength == selectionStart) {
      selectionStart = value.length;
    }
    event.target.value = value;
    event.target.selectionStart = selectionStart;
    event.target.selectionEnd = selectionStart;
  }
}

<template>
    <lightning-input onkeyup={updateFormat} label="SSN">
    </lightning-input>
</template>

A: ANSWER // RESOLUTION
So Salesforce/Lightning Web Components do not provide access to the selectionStart (or SelectionEnd) Property - at least not for <lightning-input>. So in order to make the property accessible the <lightning-input> had to be created via standard HTML. See Below:

    Account Number

        <svg class="slds-icon slds-input__icon slds-input__icon_left slds-icon-text-default"
            aria-hidden="true">
            <use
                xlink:href="/_slds/icons/utility-sprite/svg/symbols.svg?cache=9.37.1#search">
            </use>
        </svg>
        <input type="text" id="form-element-01"
            class="slds-input" maxlength="19" data-id="ANS"
            onkeyup={formatSearchTerm}/>

Once this was done I was able to access the property and update it via JS as described by sfdcfox. I did so with the following:
    formatSearchTerm(event){

        event.preventDefault();
        console.log('Formatting Input');

        this.cardSearchTerm = event.target.value;
        console.log('Search Term: ', this.cardSearchTerm);

        // Goal to reformat card search func to look like CC format xxxx-xxxx-xxxx-xxxx
        let value = event.target.value;
        let oldLength = value.length;
        value = value.replace(/\D/g, "");
        let selectionStart = event.target.selectionStart;

        var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
        var matches = v.match(/\d{4,16}/g);
        var match = matches && matches[0] || '';
        var parts = [];
        var i;
        for (i=0; i<match.length; i+=4) {
            parts.push(match.substring(i, i+4))
        }

        if(parts.length) {
            value = parts.join('-');
        } else {
            value = value;
        }

        this.cardNumberFormating = value;

        if (oldLength == selectionStart) {
          selectionStart = value.length;
        }
        event.target.value = value;
        event.target.selectionStart = selectionStart;
        event.target.selectionEnd = selectionStart;
    }

Side Note: In my original code I used the 'value' attribute in the lightning-input and tried in the new recreated input element. This was causing issues for me accounting for the cursor jumping - this had to be removed.


text:
Q: getUserMedia() : get environment camera with wide enough field of view I'm using rear smartphone camera using:
navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" }, audio: false })
   .then((stream) => {...})

However, when using those constraints on a Huawei P30 (having 3 rear camera sensors),
the retrieved video stream has a very narrow field of view ; maybe the "zoom" sensor is used to retrieve the stream. For my app, I need a more "all purpose" field of view, not too narrow like that.
I found that I can get the stream from another sensor by using the constraint deviceId (value found using navigator.mediaDevices.enumerateDevices()), but I have to support as many smartphones as possible, so relying only on deviceId does not seems a viable option (deviceId even changes for each origin & browsing session).
Does any getUserMedia() constraint exists, allowing to get a camera stream with specific field of view angle (or any related characteristic such as focal length, zoom level...)?


text:
Q: Using pandas functions with Pyspark I'm trying to rewrite my Python script (Pandas) with Pyspark, but I can't find a way to apply my Pandas functions in a way to be more efficient with Pyspark functions:
my functions are the following:
def decompose_id(id_flight):

    my_id=id_flight.split("_")
    Esn=my_id[0]
    Year=my_id[3][0:4]
    Month=my_id[3][4:6]

return Esn, Year, Month

def reverse_string(string):
  stringlength=len(string) # calculate length of the list
  slicedString=string[stringlength::-1] # slicing
  return slicedString

I would like to apply the first function to a column of a dataframe (in Pandas I get a row of three elements)
The second functions is used when a condition of a column of a DataFrame is verified
is there a method to apply them using Pyspark dataframes?

A: You could apply these functions as UDF to a Spark column, but it is not very efficient.
Here are the functions you need to perform your task :

*

*reverse : use it to replace your function reverse_string

*split : Use is to replace my_id=id_flight.split("_")

*getItem : use it to get the item in splitted list my_id[3]

*substr : to replace the slicing in python [0:4]
Just combine these spark functions to recreate the same behavior.

A: IF you want to leverage pandas functionality one way would be to use - Pandas API along with groupBy
It provides you a way to treat each of your groupBy sets as pandas dataframe on which you can implement your functions.
However since its Spark , schema enforcement is pretty man necessary as you will go through the examples provided in the link as well
An implementation example can be found here
For Trivial Tasks , like reversing the string opt for inbuilt Spark Functions , else UDF's


text:
Q: Api Platform Mercure Private Updates Use same JWT for subscribing to Mercure as for User authentication So I have an Api Platform application with JWT authentication using LexikJWTAuthenticatorBundle. So my users already have a JWT used to authenticate.
Can I somehow use this same JWT to authenticate them for private updates on the Mercure hub?
I am not sure how to configure Mercure to use the private/public keys that are using by Lexik:
mercure:
                image: dunglas/mercure
                environment:
                    - ALLOW_ANONYMOUS=1
                    - CORS_ALLOWED_ORIGINS=http://localhost:8080
                    - DEMO=1
                    - JWT_KEY=???
                    - JWT_ALGORITHM=RS256
                    - PUBLISH_ALLOWED_ORIGINS=http://localhost:180

A: you can do that JWT_KEY=`cat filename.pub`:
https://mercure.rocks/docs/hub/config
for windows it's works, for cent os - i have some error with key reading ((


text:
Q: Cannot implicity convert type 'System.Collection.Generic.IEnumberable to double" Been posting alot recently. I've been trying to work out this problem.
I'm sending in a double[] and a double in a method in order to work out the files who are
bigger than the second value.
private static double medelvärdetBeräkning(double[] temp, double eftersökt)
{
    double störreÄn = temp.Where(o => o > eftersökt);
    return störreÄn;
}

But all I get is "Cannot implicity convert type 'System.Collection.Generic.IEnumberable to double""
Would really appreciate if someone could teach me the thinking and provide insight rather than a plain solution. Appreciate it
Edit:
This is obviously not all of the code. But I'm asking a user for an input (eftersökt) and then I want the method to work through the textfile and return all the values bigger than the userInput and return them in a list (this all works, it's just this method that is faulty)

A: based on your edit stating return all the values, you want:
private static List<double> medelvärdetBeräkning(double[] temp, double eftersökt)
{
        var störreÄn = temp.Where(o => o > eftersökt).ToList();
        return störreÄn;
}

That error message means what your returning is not what you said you'd be returning.  There's a type mismatch.  Check your return type vs. your method signature to identify the problem in the future.

A: Enumerable.Where will return another IEnumerable<T> - So I assume you wanted to either

*

*Return all items greater than, or;

*Return a specific item (The first, the last, the maximum etc)

If (1) is accurate change your method signature:
private static IEnumerable<double> medelvärdetBeräkning ....

If (2) is accurate change your method body, for example:
private static double medelvärdetBeräkning(double[] temp, double eftersökt)
{
    double störreÄn = temp.First(o => o > eftersökt);
    return störreÄn;
}

(In this example, you can use Min, Max, Last or Average etc in place of First depending on which specific item you want.)


text:
Q: What is the command to know the Kubernetes Pod running status? I am trying to create the containers, when i am trying to build it, it is going into failed state so how can i see the kube pod status in running status and would like to know the root cause of it. Why is it not getting success

A: Get the logs for the pod
kubectl logs -f <pod_name> -n <namespace>

Get the list of events and other information for the pod
kubectl describe po <pod_name> -n <namespace>


text:
Q: how to disable ANR dialog on android achartengine layout zoom with 15000 points In my program, i put achartengine lineplot in a layout.
I got an ANR dialog when i want to zoom in from 15000 points display. I know it will work, i have to wait and choose wait if ANR pop out. But im getting sick of clicking wait button everytime i wanna zoom. Anyone know how to disable this ANR dialog?

A: With achart engine, the zoom pinch is not so responsive when you have a lot of points displayed , i improve my plotting by reducing the number of number plotted (fixed to 500 points per display) by taking only the maximum of certain number of points. I add a zoom listener so everytime the user zoom in, i replot it with more points in the zoomed area.


text:
Q: How do I show a fragment from an Android custom component? I've got a custom component declared using merge tags that is used in several locations in my application. Is it possible to call getFragmentManager() or getSupportFragmentManager() from this class? This class extends the LinearLayout instead of an activity. What I'm trying to do is show a new fragment from this custom component, but neither of these functions can be accessed. How do I show the new fragment from this custom component?
Here are the basics of my code:
public class SpecialTextBox extends LinearLayout implements View.OnClickListener {

    //......constructors

    public void initialize(final Context context, AttributeSet attrs) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.special_box, this);
    }

    @Override
    public void onClick(View view) {
        super.callOnClick();

        switch (view.getId()) {
            case R.id.searchButton:
                SearchFragment searchFragment = new SearchFragment(new DialogFragmentDismissHandler(), specialBox.getEditText().getText().toString());
                searchFragment.show(dashboardActivity.getFragmentManager(), SearchFragment.class.toString());
        }
    }
}

XML:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:customAttribute="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="0dp"
        android:layout_marginBottom="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="0dp"
            android:layout_gravity="left">

            <com.mobile.layout.SpecialEditText
                android:id="@+id/specialBox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:text=""
                style="@style/value"
                android:layout_gravity="left"/>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginLeft="0dp"
                android:layout_marginRight="0dp"
                android:layout_marginBottom="3dp"
                android:layout_gravity="bottom">

                <ImageButton
                    android:id="@+id/searchButton"
                    style="@style/searchImageButton"
                    android:clickable="true"
                    android:longClickable="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <ImageButton
                    android:id="@+id/myButton"
                    style="@style/reportButton"
                    android:clickable="true"
                    android:longClickable="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="0dp"
            android:layout_gravity="left">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/nameTextView"
                android:text=""
                android:textColor="@color/black"
                android:layout_marginLeft="1dp"
                style="@style/value"
                android:layout_gravity="bottom|left" />

        </LinearLayout>

    </LinearLayout>

</merge>

A: You can call getFragmentManager() or getSupportFragmentManager() only from FragmentActivity. If your custom view is inside FragmentActivity, you can this
FragmentActivity a = (FragmentActivity) getContext();
a.getFragmentManager()

A: I was able to access getFragmentManager() by the following:
Activity a = (Activity)(((ContextWrapper) getContext()).getBaseContext());
a.getFragmentManager();


text:
Q: Yii: Calling $model->save() makes call to $model->update() Here is a code, I'm trying to save new record.
...
if(!Favorites::model()->isFavorite($user_id)){
    $model = new Favorites; //::model();
    $model->credential = Yii::app()->user->id;
    $model->favorite = $user_id;
    if($model->save(false))
      echo 1;
    else
      echo 0;
}
....

It prints out 1 that means query was okay but when I look at table there is no new record. When I check this in the log it is calling update() rather than save(). Here is a application log photo.


text:
Q: magento2 how to override or custom input checkout I have problem to edit checkout page
I can't find path to edit
I want edit input and add custom css to filed in
checkout page magento2
Can help me to edit or override checkout page?


text:
Q: How do I fit labels into a Tkinter frame and canvas with scrollbar functionality? I am trying to create a list of letters that can be checked, but when the list goes off the window I don't know how to get the scrollbar to work. I have read that you need to put the labels into a frame and then into a canvas, but that is not working for me.
Here is my code:
import Tkinter as tk

LARGE_FONT = ("Verdana", 12)
NORMAL_FONT = ("Verdana", 10)
SMALL_FONT = ("Verdana", 8)

number_of_rows = 20

def popupmsg(msg):
    popup = tk.Tk()
    popup.wm_title("!")
    label = tk.Label(popup, text=msg, font=NORMAL_FONT)
    label.pack(side="top", fill="x", pady=10)
    B1 = tk.Button(popup, text="Okay", command=popup.destroy)
    B1.pack()
    popup.mainloop()

class Window(tk.Tk):

    def __init__(self, *args, **kwargs):
    tk.Tk.__init__(self, *args, **kwargs)
    master_frame = tk.Frame(self)
    container = tk.Canvas(master_frame, height=300, width=720, scrollregion=(0,0,300,720))

    master_frame.pack(side="top", fill="both", expand=True)

    vbar = tk.Scrollbar(container,orient="vertical")
    vbar.grid(column=1, sticky="ns")
    vbar.config(command=container.yview)

    container.grid_rowconfigure(-0, weight=1)
    container.grid_columnconfigure(-0, weight=1)

    container.config(yscrollcommand=vbar.set)
    container.pack(side="top", fill="both", expand=True)
    #container.create_window(0,0,window=master_frame, anchor='nw')

    child_to_container_frame = tk.Frame(container)
    child_to_container_frame.grid_rowconfigure(-0, weight=1)
    child_to_container_frame.grid_columnconfigure(-0, weight=1)

    self.frames = {}

    menubar = tk.Menu(master_frame)
    filemenu = tk.Menu(menubar, tearoff=0)
    filemenu.add_command(label="Help", command = lambda: popupmsg("Not supported yet"))
    filemenu.add_separator()
    filemenu.add_command(label="Exit", command=quit)
    menubar.add_cascade(label="File", menu=filemenu)
    optionmenu = tk.Menu(menubar, tearoff=0)
    optionmenu.add_command(label="Option #1", command = lambda: popupmsg("You clicked option #1"))
    optionmenu.add_command(label="Option #2", command = lambda: popupmsg("You clicked option #2"))
    optionmenu.add_command(label="Option #3", command = lambda: popupmsg("You clicked option #3"))
    menubar.add_cascade(label="Options", menu=optionmenu)
    menubar.add_command(label="Start", command = lambda: popupmsg("Starting Scan"))

    tk.Tk.config(self, menu=menubar)

    frame = StartPage(child_to_container_frame, self)
    self.frames[StartPage] = frame
    frame.grid(row=0, column=0, sticky="nsew")
    self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.PlaceLabels()

    def PlaceLabels(self):
        self.row = []
        self.checkboxrow = []
        self.text_in_row = []
        self.states = []
        letter = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T"]
        for i in range(number_of_rows):
            self.states.append(tk.IntVar())
            self.row.append(tk.Label(self, bg="white", pady=5, font=(None, 1), height=20, width=720))
            self.row[i].grid(row=i, column=0, sticky="ew", padx=3, pady=5)
            self.checkboxrow.append(tk.Checkbutton(self, bg="white", variable=self.states[i], command= lambda: self.DarkenLabel()))
            self.checkboxrow[i].grid(row=i, column=0, sticky="w", padx=10)
            self.text_in_row.append(tk.Label(self, bg="white", text=letter[i]))
            self.text_in_row[i].grid(row=i, column=0)

    def DarkenLabel(self):
        for i in range(len(self.checkboxrow)):
            if self.states[i].get() == 1:
                self.row[i].config(bg="gray")
                self.checkboxrow[i].config(bg="gray")
                self.text_in_row[i].config(bg="gray")
            else:
                self.row[i].config(bg="white")
                self.checkboxrow[i].config(bg="white")
                self.text_in_row[i].config(bg="white")

app = Window()
app.geometry('733x500')
app.mainloop()

I think the problem is somewhere in the beginning of the Windows class, but I don't know.
I have tried:
container.pack(side="top", fill="both", expand=True)
and
container.create_window(0,0,window=master_frame, anchor='nw')
but both didn't work for me.
Any advice?
And thank you for your help

A: I followed Bryan Oakley's advice from his comment and it really helped me solve this problem. Here is the code I have, with just the bare bones:
import Tkinter as tk

class Window(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        master_frame = tk.Frame(self)
        master_frame.pack(side="top", fill="both", expand=True)

        vbar = tk.Scrollbar(master_frame)
        vbar.pack(side='right',fill="y")

        container = tk.Canvas(master_frame, height=300, width=720, scrollregion=(0,0,300,720))
        container.pack(side="top", fill="both", expand=True)

        child_to_container_frame = tk.Frame(container)
        container.create_window(0,0,window=child_to_container_frame, anchor='nw')

        vbar.config(command=container.yview)
        container.config(yscrollcommand=vbar.set, scrollregion=(0,0,1000,1500))

        self.frames = {}
        frame = StartPage(child_to_container_frame, self)
        self.frames[StartPage] = frame
        frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.row = []
        self.row.append(tk.Label(self, bg="white", pady=5, font=(None, 1), height=20, width=720))
        self.row[0].grid(row=0, column=0, sticky="ew", padx=3, pady=5)

app = Window()
app.geometry('733x500')
app.mainloop()


text:
Q: How to search a model by date with Flask-Restless According to the documentation, a search query should look like:
GET /api/person?q={"filters":[{"name":"age","op":"ge","val":10}]}

How do I compare a date?  I tried:
GET /api/person?q={"filters":[{"name":"date","op":"<=","val":"1/20/2015"}]}

That gets no results, even though there are some which have dates prior to 1/20/2015.  I tried:
GET /api/person?q={"filters":[{"name":"date","op":">=","val":"1/20/2015"}]}

That gets all results back, even ones that are from before 1/20/2015.
This is the User model:
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime)
    type =db.Column(db.String(255))
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    active= db.Column(db.Boolean())
    activated_at = db.Column(db.DateTime())
    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

What is the correct way to query a date?

A: Davidism is absolutely right, I shouldn't have said JSON datetime-- JSON doesn't itself have a way of representing a date/datetime format— it's on the sender/reciever ends of the communication to recognise "Hey, I'm expecting a date here, this looks like a date, I'll try and treat it like one".
Generally, most people use ISO 8601 as their datetime representations in JSON (2014-10-23T18:25:43.511Z), and Flask-Restless seems to use dateutil.parse to parse some incoming values back into datetime fields-- but oddly, not GET ones.
So it looks as though the string representing your datetime value needs to match what your database expects-- which on average is going to be an ISO 8601 format.


text:
Q: Xcode : adding very large files to Xcode / number of (image) resources to project results in freeze I'm working on a computer vision project that requires I package a very large number of jpg images at 640*480 resolution for testing the precision of the application.
In total these 5000 files require around 6GB of space. If I attempt to add all these files to the project, then Xcode will stop responding (and if source control is enabled git will be called recursively until my system crashes).
I've explored the possibility of using an image catalogue but this is problematic as the required format is JPG and considered zipping files (but the same problem occurs).
Is there a 'best' or efficient way to add either very large resources or a very large number of assets to an Xcode project, and re bundles/catalogues necessarily a 'better' solution in terms of performance etc?
Regards,
P.L.G.

A: Fwiw, I just imported thousands of photos into Xcode and was coming up against the same problems outlined above.  The best solution I found was to utilize the Images.xcassets resource (it is an asset catalog).  While my computer was working pretty hard, the images have been loaded into the project.
Under Images.xcassets, at the bottom click the '+' sign, then "Import".  That will allow you to bring images in much more easily.  The program is now working very slowly for me, but this has been the best solution I can find yet for such large amounts of images


text:
Q: InstanceOf method use in generics? Because generic type information is erased at runtime, it is illegal to use the instanceof
operator on parameterized types other than unbounded wildcard types.
I extract this statement from effective java edition 2. And it says that preferred way to use instanceOf is :
// Legitimate use of raw type - instanceof operator
if (o instanceof Set) { // Raw type
Set<?> m = (Set<?>) o; // Wildcard type
...
}

Can some body please explain the concept ?(I understood the reified and erasure concepts)

A: If you understood how erasure works, you know that instanceof has no way to check for the erased type, so it can only be used with the raw type.
Along the same lines, after you have established that the object is some sort of Set, you cannot be sure what kind of type the Set has. So you can only (safely) use Set<?> (which means that everything you pull out from the Set cannot be narrowed down to more than Object, and you cannot put in anything at all).


text:
Q: Sabre dev studio soapUI tests authentication SOAP Basics - environments section on the Sabre Dev Studio (https://developer.sabre.com/docs/read/soap_basics/environments) says "After you register with Sabre® , you receive test authentication credentials and authorization to use the APIs you selected."
Does this apply to using the soapUI Test Client? I downloaded the test client and the project properties in soapUI is asking for a different set of authentication parameters (username, password, organization) than what was given to me after registration (client id, client secret).
Also, the default endpoint I see inside soapUI tests is https://webservices.sabre.com/websvc , and the web documentation show a different endpoint for customer acceptance testing and nothing for the client development environment.
Any thoughts?

A: The client id and secret are just test credentials meant for testing some REST services, specifically the ones found here: https://developer.sabre.com/io-docs
The credentials you mentioned there are the ones that you will get when you sign a contract with Sabre. Those credentials will look a lot more to what seek. Should you want more information on that, you should go to: https://developer.sabre.com/contact, and select the subject: "I want to become a Sabre customer".
Lastly, the URL you reference there is one that still works, but eventually will not. Because the new one works with TLS 1.2 and forward, so it does not work with TLS 1.0, 1.1 nor SSL, for security reasons.
Should you want to know more, please check this: https://developer.sabre.com/docs/read/security/pci_mandate


text:
Q: Time dependent actions for approval process? I can't seem to find anything on this, but do I have any time-based abilities with approval processes?
For instance, the object is submitted for approval and assigned to an approver.  No approval/rejection has occurred in 24 hours so I need to update a custom field.
Is anything like this possible?  If not, would I be able to accomplish something similar with workflow rules?
Your knowledge on this subject would help me tremendously.

A: A Workflow Rule, Process Builder, or Record-Triggered Flow could all be used for your purpose. You simply need to include a Field Update to kick off the delay mechanism.


text:
Q: Improved AFK command for discord.js v12 I have recently viewed a AFK command from a different thread. Here is the code:
client.on('message', (message) => {
 // checks if the message author is afk
 if (db.has(message.author.id + '.afk')) {
  message.channel.send(`Welcome back ${message.author} I removed your AFK.`);
  db.delete(message.author.id + '.afk');
  db.delete(message.author.id + '.messageafk');
 }
 if (message.content.startsWith('+afk')) {
  message.channel.send(
   'Aight, I have set your AFK. I will send a message to the users who mention you..'
  );
  // then here you use the database :
  db.set(message.author.id + '.afk', 'true');
  db.set(
   message.author.id + '.messageafk',
   message.content.split(' ').slice(2)
  );
 }
 if (message.content.includes('+afk off')) {
  db.delete(message.author.id + '.afk');
  db.delete(message.author.id + '.messageafk');
 }
});

When user pinged:
client.on('message', (message) => {
 // If one of the mentions is the user
 message.mentions.users.forEach((user) => {
  if (message.author.bot) return false;

  if (
   message.content.includes('@here') ||
   message.content.includes('@everyone')
  )
   return false;
  if (db.has(user.id + '.afk'))
   message.channel.send(
    `${message.author}, the user you mentioned is currently AFK.. Leave a message if urgent by DMing him`
   );
 });
});

I want to add an AFK reason to be shown instead of that message when the user is mentioned
Expected output:
User: +afk <reason>
BOT: Aight, I have set your AFK. I will send a message to the users who mention you..
User2: @User
BOT: @User2, the user you mentioned is currently AFK: <reason>

A: The first and maybe the easiest way of getting this info: using Array.prototype.splice()
const reason = [...message.content].splice(5).join('')

const message = '+afk doing homework';
const reason = [...message].splice(5).join('');
console.log(reason);

Second method: use String.prototype.split():
const reason = message.content.split(/ +/).splice(1).join(' ');

const message = '+afk doing homework';
const reason = message.split(/ +/).splice(1).join(' ');
console.log(reason);

Lastly, also using String.prototype.split():
const reason = message.content.split('+afk ')[1]

const message = '+afk doing homework';
const reason = message.split('+afk ')[1];
console.log(reason);

Once you have the reason, you can add it to the database, and fetch it whenever

A: here :
    if (message.content.startsWith('+afk')) {
      message.channel.send('Aight, I have set your AFK. I will send a message to the users who mention you..')
// then here you use the database :
db.set(message.author.id + '.afk','true')
db.set(message.author.id + '.messageafk', message.content.split(' ').slice(2))
    }
    if (message.content.includes('+afk off')) {
db.delete(message.author.id + '.afk')
db.delete(message.author.id + '.messageafk')
    }
});

there is this line :
db.set(message.author.id + '.messageafk', 'THE MESSAGE TO BE SENT')

There you will set the ask reason,and you will display it when the user is mentionned
client.on('message', message =>{
if(message.author.bot) return;
if(message.channel.type === 'dm') return;
// if the message author was afk
if(db.get('afkusers').includes(message.author.id){
message.channel.send('Oh you're back ! Removed your afk')
db.delete('afkusers[afkusers.indexoF(message.author.id)]')
}
// if one of the mentions is a afk user
// Oh and you need to use 'if(user.bot) return;' because a bot can't use your commands ^^'
// if there is afk users (don't delete it's important so we are such that the variable will work and we can use normal js to manipulate the variable like .includes())
if(db.has('afkusers')){
// If one of the mentions is afk
if(message.mentions.users.find(u => db.get('afkusers').includes(u.id)) message.channel.send(`${message.author}, the user you mentioned is currently AFK.. Leave a message if urgent by DMing him`)

}
})


text:
Q: Is the moduli stack of stable maps functorial? Let $f:X\rightarrow Y$ be a morphism where $X$ and $Y$ are smooth projective varieties over $\mathbb{C}$. Does $f$ induce a well-defined "pushforward" morphism $\overline{\mathcal{M}}_{g,n}(X,\beta)\rightarrow \overline{\mathcal{M}}_{g,n}(Y,f_*\beta)$ in the category of DM stacks?
I know the answer is yes if $Y$ is a point. In this case, it is called the stablization morphism. I also know the tricky step for defining it is to contract all bubbles which are no longer stable after forgetting the target of a given stable map.
By the same argument, I am thus convinced that the "pushforward" morphism does exist set-theoretically. But how do we prove that it is a morphism in the category of DM stacks?


text:
Q: Is there any possibility for one rserve's client to share workspace with another? I'd like replace RExcel with the Excelsi-R. Excelsi-R talks R via RServe, and RServe has this feature, that makes each client work in independent workspaces.
What I want is to actually share a single workspace between at least 2 simultaneously connected clients. One client would be run by Excelsi-R, and another by manually launched interactive R Session. That would allow me to interface with the Excelsi-R session in traditional way (say, in RStudio).
I don't need asynchronous computation; I'm perfectly happy if Excelsi-R would have to wait, until a command issued by the other connection finishes, and vice versa; just like in the RExcel "foreground mode".
Is it possible?

A: Not currently, since each process has exactly one connection. There are a few hacks - such as you can "switch" sessions by starting a listener for another connection in an existing session - but that may be a bit too limited.
That said, it is technically possible (Rserve support looping over multiple connections - it is used in RCloud to support two separate processes on one connection) - the challenge is how to link two independent connections to a single process. The rsio communication was added in Rserve 1.8 specifically to allow the passing of descriptors between Rserve instances, but it was not used so far. If there is interest in that kind of functionality, I can see how it could be added.


text:
Q: pipeline processing using cat original:
./A_process.py _ < input.dict > output.dict.tmp
./B_process.py _ < output.dict.tmp > output.dict
rm output.dict.tmp

I am trying to make it into a pipeline, so
cat input.dict | A_process.py _ | B_process.py _ > output.dict

however it shows "A_process.py command not found"...
I guess something wrong with the environment, but not sure what to do.

A: As @steeldriver wrote in his comment, the problem you are facing is that the script you are executing is not in your PATH
The simple solution will be to add the prefix ./ to the script-name, assuming that you are running the command in the same folder the script is located:
cat input.dict | ./A_process.py _ | ./B_process.py _ > output.dict

Other options might be:

*

*Add the path of the script location into the PATH variable.

*Instead of ./script_name use full-path of the script /full/path/to/script/directory/A_process.py


text:
Q: How to vacuum an sqlite database within R? I have created and filled a sqlite database within R using packages DBI and RSQLite. E.g. like that:
con_sqlite <- DBI::dbConnect(RSQLite::SQLite(), "../mydatabase.sqlite")
DBI::dbWriteTable(con_sqlite, "mytable", d_table, overwrite = TRUE)
...

Now the sqlite file got too big and I reduced the tables. However, the size does not decrease and I found out that I have to use command vaccum. Is there a possibility to use this command within R?

A: I think this should do the trick:
DBI::dbExecute(con, "VACUUM;")


text:
Q: PostgreSQL trigger doesn't insert all records I'm working with PostgreSQL 10. I'm updating another table when a record is inserted into the original table.  The trigger doesn't insert the last record if there are more than one. If it's just one record it won't get inserted at all. Any ideas why it's doing this?
create table employee
(
   empID SERIAL unique PRIMARY KEY NOT NULL,
   first_name text not null,
   mi text not null,
   last_name text not null,
   full_name character varying (150) UNIQUE NOT NULL,
   employee_email character varying(150) UNIQUE
);

CREATE TABLE empmerge
(
  empid integer NOT NULL REFERENCES employee(empID) MATCH FULL
      ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY IMMEDIATE,
  full_name character varying NOT NULL REFERENCES employee(full_name) MATCH FULL ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY IMMEDIATE,
  org_section text,
  date_of_xfer date

);

The employee trigger:
create or replace function concat_full_name() returns trigger as $$
begin
    if NEW.full_name is null
      then NEW.full_name := concat(new.first_name, ' ',new.mi,'.', ' ', new.last_name);
    end if;
    return new;
end;
$$ language plpgsql;

create trigger trig_concat_full_name
before insert
on employee
for each row
execute procedure concat_full_name();

The merge trigger
create or replace function insert_empMerge()
  returns trigger as $$
begin
  INSERT INTO empMerge(empID, full_name)
  SELECT employee.empID, employee.full_name
  FROM employee
  WHERE NOT EXISTS (SELECT 1
                    FROM empMerge
                    WHERE employee.empID = empMerge.empID
                     and  employee.full_name = empMerge.full_name);
    return new;
end;
$$ language plpgsql;

create trigger trig_insert_empMerge
before insert
on employee
for each row
execute procedure insert_empMerge();

The insert statement:
insert into employee(first_name, mi, last_name)
values
 ('dora','l', 'explorer'),
 ('atticus','m', 'finch'),
 ('nancy','s', 'drew');

select * from empMerge;

A: The select from employee table won't work as it is a before trigger and thus the new rows are not yet in the employees table.
You can use the new record directly.
create or replace function insert_empMerge()
  returns trigger as $$
begin
  INSERT INTO empMerge(empID, full_name)
  SELECT new.empID, new.full_name
  WHERE NOT EXISTS (SELECT 1
                    FROM empMerge
                    WHERE new.empID = empMerge.empID
                     and  new.full_name = empMerge.full_name);
  return new;
end;
$$ language plpgsql;

You could make that a bit shorter (and faster) if you declare a unique constraint on empmerge(empid, full_name) and then use insert on conflict:
alter table empmerge
   add constraint unique_employee
   unique (empid, full_name);

Then change the trigger function:
create or replace function insert_empMerge()
  returns trigger as $$
begin
  INSERT INTO empMerge(empID, full_name)
  values (new.empID, new.full_name)
  on conflict on constraint unique_employee do nothing;
  return new;
end;
$$ language plpgsql;

Another option would be to make the existing trigger an AFTER trigger. In that case the new row is already inserted into the employee table and it would be visible for the trigger.

A: Your trigger deals with all employee records (???) and since you call it "before insert", the new record is not there yet.


text:
Q: Compute a list of files in folder except for certain ones in bash I have a bash script running an executable against a bunch of test files in a folder. Some of the test files should pass, and some should fail. What I want to do is make a list of files that should fail, and then treat the rest of the tests in the folder as positive tests. Then, I can iterate over each list separately and handle the result accordingly.
This is what I had, which works when there is only 1 failure test, but doesn't work for more:
negative_tests() {
    echo "../testcases/test3.txt"
    echo "../testcases/test4.txt"
}
negative_tests=$(negative_tests)

positive_tests=$(comm -23 <(ls ../testcases/*) <(negative_tests))

log "Running tests.."
for testfile in $positive_tests; do
    ./a.out $testfile >> output.txt || { echo "Failed on $testfile." ; exit 1; }
done

for testfile in $negative_tests; do
    ./a.out $testfile >> output.txt && { echo "Succeeded on $testfile succeeded when failure was expected."; exit 1; }
done

I have a feeling I'm just missing something with how bash's data model works. Any ideas or better ways to do this?

A: It looks like this approach works, but the way comm works is that it expects the lines it diffs to be in order. So, I needed to pipe the negative cases into sort so they'd match the order of files in ls:
positive_tests=$(comm -23 <(ls ../testcases/*) <(negative_tests | sort))

Then, everything works as expected. Though I'd be interested in seeing any other solutions people might have.


text:
Q: Java - parse string to Json and convert all number values to int When I parse string:
{"action":"duelInvite","id":"1","matchType":"3"}

to JsonObject in this case all values are strings, but how to create JsonObject, that maps id and matchType  to int? Do I have to do it manually, when getting those values? It's easier to .getInt("id") rather than Integer.parseInt(.getString("id"))

A: When you create a JSON Object from a string, all values become strings within the JSON Object. So you're right, you'll have to do it manually. But instead of parsing every time you want to get the values, just do it once when you create the object.
//create your object from the string
jsonObject = new JSONObject(string);
//set the key "id" to the integer value of the String at key "id"
jsonObject.put("id", Integer.parseInt(jsonObject.get("id")));
//set the key "matchType" to the integer  value of the String at key "matchType"
jsonObject.put("matchType", Integer.parseInt(jsonObject.get("matchType")));


text:
Q: SQL full-text index on a VIEW locking the main TABLE I have an interesting (read frustrating) problem with running a Full Text index on an SQL View.

*

*In the SQL VIEW I create the unique clustered index.

*The Full Text Index populates fine (100K records)

*However, the main table that is used to populate the VIEW is locked from making any UPDATES while I have the Full Text Index active on the VIEW.

Once I delete or disable the Full Text index on the VIEW I am once again able to make UPDATES to the main TABLE.
Can you offer any ideas as to how I can have the Full Text Index on the view whilst being able to make updated to the main table?
Thanks,
Conan


text:
Q: grouping numbers up to 5 groups and the total size of each group should be as small as possible I have a list of numbers. I want to group this up to 5 groups and the total size of each group should be as small as possible. What would be a good approach to this?
Sample data
numbers = [52, 86, 102, 122, 964, 1075, 1420]

Possible result
result = [[1420],[1075],[964],[122, 52],[102, 86]]

A: I had a similar situation to you in the past. What I did was implement:
def lazy_split(iter_: Iterable, split_num: int) -> list[Iterable]:
    k, m = divmod(len(iter_), split_num)
    return [iter_[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(split_num)]

numbers = [52, 86, 102, 122, 964, 1075, 1420]
print(lazy_split(numbers, 5))
# Output: [[52, 86], [102, 122], [964], [1075], [1420]]

It is a slightly modified version of tixxit's answer to a similar question: https://stackoverflow.com/a/2135920
I called it lazy_split as it attempts to slice the iterable instead of iterating through it.


text:
Q: Git SSH Error Bad File Number I'm setting up a git server with the git guide for it (http://git-scm.com/book/en/v2).
So I made a user git on the Ubuntu server, and i put the ssh key of my pc in the authorized_keys file.
I made a repo on the git account in /repos/test/test.git
When i try to clone from the windows pc with
git clone git@196.168.0.114:/repos/test/test.git

it gives me this:
Cloning into 'test'...
ssh: connect to host 196.168.0.114 port 22: Bad file number
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Also i have a password on the git account
.ssh chmod 700 by the git account
authorized_keys chmod 600 by the git account

A: From the GitHub documentation:

This error usually means you were unable to connect to the server. Often this is caused by firewalls and proxy servers.

Please check your firewall settings on Windows and on the Linux client.
Try ssh -vvv git@196.168.0.114
If you see this in the output:
 [196.168.0.114] port 22. debug1: connect to address 196.168.0.114 port 22: Attempt to connect timed out without establishing a connection

then there is a firewall inside or between your two computers which swallows packets.


text:
Q: Net7 C# Kestrel UseHttps() throws System.ArgumentNullException:Value cannot be null. (Parameter 'provider') when attempting to enable QUIC/Http3 Calling the constructor of below NanoKestrel class throws

ERROR System.ArgumentNullException: Value cannot be null. (Parameter
'provider')
at System.ThrowHelper.Throw(String paramName)
at
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider
provider)
at
Microsoft.AspNetCore.Hosting.ListenOptionsHttpsExtensions.UseHttps(ListenOptions
listenOptions, HttpsConnectionAdapterOptions httpsOptions)
at
NanoKestrel.<>c__DisplayClass16_0.<.ctor>b__2(ListenOptions
listenOptions)

public class NanoKestrel
    {
        public IServer Server { get; set; }
        private HostingApplication _application { get; set; }
        private X509Certificate2 _serverCertificate { get; set; }

        public NanoKestrel(IPEndPoint endPoint, X509Certificate2 certificate = null)
        {
            _serverCertificate = certificate;
            var services = new ServiceCollection();
            services.AddLogging(b =>
            {
                b.AddFilter("Microsoft.AspNetCore.Server.Kestrel", LogLevel.Warning);
            });

            services.Configure<KestrelServerOptions>(options =>
            {
                options.Listen(endPoint, listenOptions =>
                {
                    listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
                    if (_serverCertificate != null) listenOptions.UseHttps(new HttpsConnectionAdapterOptions() { ServerCertificate = _serverCertificate });           // <--exception thrown at this line in stacktrace
                });

            });

            services.AddSingleton<IServer, KestrelServer>();

            services.AddSingleton<IConnectionListenerFactory, SocketTransportFactory>();
            services.AddSingleton<IHostApplicationLifetime, ApplicationLifetime>();
            services.AddTransient<IHttpContextFactory, DefaultHttpContextFactory>();

            services.AddTransient<HostingApplication>();

            var serviceProvider = services.BuildServiceProvider();
            Server = serviceProvider.GetRequiredService<IServer>();
            _application = serviceProvider.GetRequiredService<HostingApplication>();
        }

        public async void StartAsync()
        {
            await Server.StartAsync(_application, default).ConfigureAwait(false);
        }
}

i tried to serve a certificate to the listenOptions.UseHttps();   but throws the same exception.
I intend to enable QUIC/Http3 on Kestrel, following guidance from https://www.meziantou.net/using-http-3-quic-in-dotnet.htm
Package References:

Microsoft.Extensions.Features 7.0.2

FrameworkReference:

Include="Microsoft.AspNetCore.App"

A: I solved the problem myself by adding a line marked as below:
 services.Configure<KestrelServerOptions>(options =>
            {
                options.ApplicationServices ??= _serviceProvier;  //<=
    //this line above is needed to solve the issue, otherwise Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions.EnsureDefaultCert() throws the "Value cannot be null. (Parameter 'provider') " exception.
                options.Listen(endPoint, listenOptions =>
                {
                    listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
                    if (_serverCertificate != null) listenOptions.UseHttps();
                });
            });


text:
Q: Android - Layout -> Textview Prototype On my Android application I make an interface with about 10 Textview with the same properties except for their id.
So is it possible to make a TextView prototype which make me able to create 10 textview child's ?
My questions deals of Textview, but it's the same interogation as LinearLayout, EditView, etc
Thank's

A: You can create a layout with textview prototype and use an LayoutInflater to inflate the prototype. For instance you can try something like this:
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
textView = (TextView) inflater.inflate(R.layout.textview_prototype, null);
textView.setId();

You can place this in a loop to fill all the 10 textviews :)
and the textview_prototype could look like:
<TextView
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content">
</TextView>

A: You should be able to set a common attributes as a  style or theme for the textviews
<style name="CustomTheme">
    <item name="android:textColor">#ff0000</item>
</style>

And you can set this style to your activity like
<textview android:theme="@style/CustomTheme">

The docs from google will give moe idea and examples
    http://developer.android.com/guide/topics/ui/themes.html

A: Another approach, if you want it all in XML is to provide the layout for the TextView (my_textview.xml)
<TextView
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:id="@+id/textview" >
</TextView>

And then in the layout you want to use it in you use the include tag like this:
<LinearLayout>
  <include layout="my_textview.xml" android:id="@+id/firstTextView" />
  <include layout="my_textview.xml" android:id="@+id/secondTextView" />
  <include layout="my_textview.xml" android:id="@+id/thirdTextView" />
  ... Add as many as you want with different ID's ...

</LinearLayout>

Providing the id attribute in the include tag will override the id of the primary layout/widget in the layout you want to include.


text:
Q: How to set a custom time zone for Lightweight Charts? I've got a lightweight chart setup that looks like this. I  want to add some kind of configuration so that the chart can show me the local time as opposed to the universal time being passed by a Unix timestamp, which is a couple hours offset from mine for example. Another possibility is to modify the Unix timestamps.
var chart = LightweightCharts.createChart(document.getElementById("charts"), {
  width: 1060,
  height: 537,
  layout: {
    backgroundColor: "#161616",
    textColor: "rgba(255, 255, 255, 0.9)",
    fontSize: 15,
    fontFamily: "Ubuntu",
  },
  grid: {
    vertLines: {
      color: "#424242",
      width: 0.3,
    },
    horzLines: {
      color: "#424242",
      width: 0.3,
    },
  },
  crosshair: {
    mode: LightweightCharts.CrosshairMode.Normal,
  },
  priceScale: {
    borderColor: "rgba(197, 203, 206, 0.8)",
    size: 5,
  },
  timeScale: {
    borderColor: "rgba(197, 203, 206, 0.8)",
    timeVisible: true,
    secondsVisible: false,
    rightBarStaysOnScroll: true,
  },
});

A: I've posted the similar question here, but didn't post an answer so far.
I see 2 approaches which might help you to solve this issue:

*

*You can modify source time of the bar by adding TZ offset to the time (which I think is preferred way - see below)

*You can override tickMarkFormatter, dateFormat and timeFormatter to format dates properly with desired TZ offset.

I think that the first way (with adding offset) is preferred because it'll also affect tick marks generation and their weight, so your timescale will look much better without issues (e.g. you can see 23:00 for time instead of 30 for day because you add an offset 60 min and it shifts timescale a bit).
EDIT (03.11.2021): Please this doc to get more information related to how to support time zones.

A: There is one another way too.
Lightweight chart treats the unix timestamp as GMT time.
Example:
To display the time as per IST (GMT+5:30), just add that number of seconds to the present time. (19800 seconds)


text:
Q: To check if a user has a role (admin or any other custom role) in a server, from the user's DM When a user DM's the bot and uses a command, like let's say -server <server id>, the bot should check if the user is:

*

*A member of the guild

*Has administrator role(or a custom role) within that particular guild.

   def dm_server(self, msg):

        guildid=msg.content.split(" ",1)     #splitting the `-server <servid>`
        guildid=int(guildid[1])              #storing guild id

        guild=self.bot.get_guild(guildid)

        member=msg.author

        #<check here if member has admin or custom role within the guild>

I tried using if member.guild_permissions.administrator: but got the error AttributeError: 'User' object has no attribute 'guild_permissions'.

A: You'll need the Member object if you want to use guild_permissions.
In the context of a DM, it will give you a discord.User, so you'll need to get the proper permissions by getting the member for the corresponding guild.
guild = self.bot.get_guild(guildid)
member = guild.get_member(msg.author.id)
# member.guild_permissions


text:
Q: Process X number of records from DataTable in a loop I have a datatable which contains a X number of records.
I am sending these records into a remote database using SqlBulkCopy. Each record contains a big blob so the transfer is very slow, therefore, I'm want to send each bulk containing only 10 records.
What I have at the moment uploads the first record, then uploads in sets of 10 but omits the remaing records. The problem is that my loop is wrong. It should process the records from 0-10, 11-20, etc.
Any ideas?
For Each iRow As DataRow In dtSortedDataTable.Rows
dtToUpload.ImportRow(dtSortedDataTable.Rows(dtSortedDataTable.Rows.IndexOf(iRow)))
If iCurrent Mod 10 = 0 Then
    'Call function SqlBulkCopy to upload 10 records existing in the dtToUpload
End If
iCurrent += 1
Next

A: A few issues here:

*

*Assuming iCurrent starts at 0, to get the behavior you want you need to add one to iCurrent:
If (iCurrent + 1) Mod 10 = 0 Then

*Your stated ranges are incorrect based on the logic you are trying to implement. You want to process 0-9, 10-19, etc.

*Don't forget to add a bulk copy upload after the loop or check to see if iCurrent is the last item you are processing:
If (iCurrent + 1) Mod 10 = 0 OrElse (iCurrent = dtSortedDataTable.Rows.Count - 1) Then


text:
Q: Auto Completion Closing tags in html notepad++ I have just started using notepad++. I wanted to know if there is a way to create a closing tag automatically in HTML, For example:
If I type:
     <body>
It will close the tag automatically:
    </body>
I tried to adjust the Settings/Preferences/Auto-Completion, And I enabled the HTML/XML close tags, but that didn't work, Does anyone have a solution?
Thanks.

A: I thing that You looking for plugin TextFX Settings. To enable it go into menu:
 TextFX  -> TextFX Settings -> chek option 'auto close XHTML tags'

If You don't have installed this plugin, do this:
 Click Plugins -> Plugin Manager -> Show Plugin Manager
 On the 'available' find and select 'TextFX Characters'
 Click Install and restart Notepad++
 Enable the 'auto close XHTM tags' as described above.

And do not forget to set the type of document to HTML.

A: If you have done everything listed, and it still doesn't work. Try going to the "Language" (next to the settings part) and turn html on. This was the problem for me. Now it works fine for my with the autocomplete.

A: As fas as I remember (when I used windows machine), there was common problem with html tags.
Try to uncheck all checkboxes in Preferences when on the list (on the left side).
Next, hit close.
Then open it again and check only html/xml close tag checkbox.
In my case it helps.

A: This question is exactly answered by Noha Kareem, here:
Auto close of html tags and php tags in notepad++ and a semicolon at the end of php lines.
I hope this helps


text:
Q: How can I compare System Strings while creating forms using CLR/CLI (.NET Framework)(C++)? I am trying to create a visualization of Priority Queue using WindowsForms (CLR/CLI, C++, .NET Framework). I am done with the enqueue part but when I try to visualize the dequeue function, the values are dequeued in the conventional manner of FIFO. How can I Visualize the dequeue-ing of the values according to their priority?
While inserting the values through enqueue function, the priority of every element is stored in the priority array. And while deleting the values in dequeue function, I simply try to compare the values stored in priority array with the values in the priority label through a loop, and if the value is matched, the element is shown to be dequeued on the form. According to my analysis, the strings of Labels and those stored in the Priority Queue are not being compared correctly, if that is the issue, kindly suggest the correct method.
Is there a mistake in my logic, or if there is any other issue? The code of Delete (Dequeue) function is given below:
array<String^>^ priority = gcnew array<String^>(6);

void Delete(){
  if (front == -1 || front > rear)
  {
    MessageBox::Show("Queue UnderFlow");
    return;
  }
  else
  {
    count++;

    for (int i = 0; i < 6; i++)
    {
      if (priority[i] == label1->Text)
      {
        label1->Text = String::Empty;
        label12->Text = String::Empty;
        return;
      }
      if (priority[i] == label2->Text)
      {
        label2->Text = String::Empty;
        label11->Text = String::Empty;
        return;
      }
      if (priority[i] == label3->Text)
      {
        label3->Text = String::Empty;
        label10->Text = String::Empty;
        return;
      }
      if (priority[i] == label4->Text)
      {
        label4->Text = String::Empty;
        label7->Text = String::Empty;
        return;
      }
      if (priority[i] == label5->Text)
      {
        label5->Text = String::Empty;
        label8->Text = String::Empty;
        return;
      }
      if (priority[i] == label6->Text)
      {
        label6->Text = String::Empty;
        label9->Text = String::Empty;
        return;
      }
    }

A: return will exit the function early, try to delete return.
A little suggestion:
You should use front and rear more, your upload code is more like an array than a queue. Queues can prevent traversing the entire array under certain circumstances. I suggest changing the code to:
             for (front = 0; front != rear; front++)
             {
                 if (priority[front] == label1->Text)
                 {
                     label1->Text = String::Empty;
                     label12->Text = String::Empty;
                 }


text:
Q: SceneBuilder 2.0 Dynamic shape generation I have an FXML file that does some certain animations with some right now static(so to speak) shapes that are hard-coded into the fxml.  What I am trying to do is dynamically create shapes from Java Objects that have certain properties such as color which these objects will be pulling from a database and populate the fxml with these object based shapes, I am not sure how to go about doing this.  Below is the code for the main class, I know why the error is happening but not sure how to do it any other way.
public class TestConveyorView extends GuiceApplication {

  @Inject
  private GuiceFXMLLoader fxmlLoader;

  public Injector createInjector() {
      return Guice.createInjector(new AbstractModule() {
          @Override
          protected void configure() {
          }
      });
  }

public static void main(String[] args) {
    Application.launch(args);
}

@Override
public void init(List<Module> modules) throws Exception {
}

  @Override
  public void start(Stage stage) throws Exception {
      //GridPane root = new GridPane();
     Parent root = fxmlLoader.load(getClass().getClassLoader().getResource("fxml/TestConveyorView.fxml")).getRoot();

     Box box = new Box(1, red);
     Rectangle rectangle = new Rectangle(50,50,box.getColor());
     // Can't seem to add it to the scene, problem occurs here.
     root.getChildren().add(rectangle);

     Scene scene = new Scene(root);

    // BackgroundImage background = new BackgroundImage(null, BackgroundRepeat.REPEAT, BackgroundRepeat.REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT);
    stage.setScene(scene);
    stage.show();
  }

}

A: Ok I fixed the problem by changing
Parent root = ...

To
AnchorPane root = ...

Simple fix that I overlooked I guess.


text:
Q: How to pass only 1 element to ArrayAdapter and make sure it only displays unique items Working on a project and have hit a mental wall trying to use a custom ArrayAdapter to display only unique elements from a class. I have a Class I've created that is simply made up of 3 strings. SongName, Category and Artist.
With that class I have created an ArrayList in my MainActivity. I would like to use that ArrayList in a few different activities. I've been able to use it in an ArrayAdapter that I created that displays all 3 fields in TextViews but I would like to create another ArrayAdapter for a different activity that only displays 1 of those fields and doesn't show the repeating items. So, for example, an ArrayAdapter  that is only provided Category element and only displays the unique ones.
I'm having a hard time wrapping my head around how to only pass 1 element from the ArrayList to ArrayAdapter and make sure it doesn't display duplicates.
Fairly new to the android development and haven't been able to find an answer to this, so would appreciate it if you could help me or point me in the right direction, I would greatly appreciate it.
Edit Answer: was able to get it to work by adding this:
        ArrayList<Music> Library = MainActivity.music;

        ArrayList<String> artists = new ArrayList<String>();

        Log.i("MainActivity", String.valueOf(Library.size()));
        for (int i = 0; i<Library.size(); i++){
            String artist = Library.get(i).getArtist();
            if (!artists.contains(artist))
            artists.add(artist);

            Log.i("MainActivity", "artist");
        }

Edit: including screenshot of the original ArrayList below. As you can see in my idea some of the categories and artists would repeat. I would like to create an activity that only displays the artists and another that only displays the categories. With the caveat being I only want the unique values to be displayed not duplicates & including github link.
github : https://github.com/Nimzr/Music-Player

A: You could start by creating a trimmed version of the object you want to view and then create a method utility that allows you to filter out the elements of your original List according to a parametrized condition. The elements left standing you map them to the new trim version and use that new List as the source for your custom ArrayAdapter. The following is a skeleton of this idea:
    public ArrayAdapter<TrimmedElement> createCustomArrayAdapter(
            Context context, List<WholeElement> target, Predicate<WholeElement> condition) {

        List<TrimmedElement> trimmedList = target.stream()
                .filter(condition)
                .map(TrimmedElement::new)
                .collect(Collectors.toList());

        return new MyCustomArrayAdapter<TrimmedElement>(context, trimmedList);
    }

    static class WholeElement {}
    static class TrimmedElement {
        public TrimmedElement(WholeElement ele) {
            // Copy the information desired
        }
    }

Complete code on GitHub
Hope this helps.

A: By default the ArrayAdapter will create views for each array item in your ArrayList. To customise how the ArrayAdapter create views for your data you need to extend it and override its getView() method and use a different layout for each item like this
NOTE: Im assuming Music is that class which has those 3 strings and you have created a new layout called unique_layout.xml which has only one TextView to display one you those strings.
public class CustomArrayAdapter extends ArrayAdapter<Music> {
    public CustomArrayAdapter(Context context, ArrayList<Music> musicList) {
       super(context, 0, users);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

       Music music = getItem(position);

       // Here use that new layout that you created
       if (convertView == null) {
          convertView = LayoutInflater.from(getContext()).inflate(R.layout.unique_layout, parent, false);
       }

       // Assign text to the TextView from that new layout
       TextView category = (TextView) convertView.findViewById(R.id.category);
       category.setText(music.category);

       return convertView;
   }
}

UPDATE: Remove Duplicates from ArrayList
NOTE: The following methods removes duplicates and put the resulting list in a new ArrayList<String> which you can use as source of your ArrayAdapter. So you don't have to extend ArrayAdapter now.
There are 3 common ways to remove duplicates from ArrayList

*

*Do it manually ( good luck in that )

*Use Streams ( only available for API 24: Nougat and greater )

*Use LinkedHashSet ( available since API 1 )
Lets say you have array list defined as follows
ArrayList<Music> musicList = new ArrayList<>();
ArrayList<String> categoryList = new ArrayList<>();

musicList.add(new Music("song1", "category1", "artist1"));
musicList.add(new Music("song2", "category2", "artist2"));
musicList.add(new Music("song3", "category3", "artist3"));
musicList.add(new Music("song4", "category2", "artist4"));
musicList.add(new Music("song5", "category1", "artist1"));
musicList.add(new Music("song6", "category4", "artist5"));
musicList.add(new Music("song7", "category3", "artist2"));

Option 2 : Using Streams
What I'm doing here is that I'm extracting only the category field using the map() method and removing duplicates using the distinct() method then finally  collecting all this modification in categoryList. If you need to extract unique artist, just change music.category to music.artist
EZ !
NOTE: After the map() method we are now dealing with array of strings so distinct() uses the equals() and hashCode() methods of the String class to find and remove duplicates. If you are using distinct() directly on your musicList which is an array of Music class then your Music class should override and provide implementation of equals() and hashCode() methods.
Read more about them here or here
categoryList = musicList.stream()
              .map((music)-> music.category)
              .distinct()
              .collect(Collectors.toCollection(ArrayList::new));

Log.d("CATEGORY LIST" ,  categoryList.toString())

//LOG Output
CATEGORY LIST: [category1, category2, category3, category4]

Option 3 : Using LinkedHashSet
This method is rather simple. As before first extracting category fields and storing them into categoryList. Creating LinkedHashSet will automatically remove duplicate values just like the distinct() method did when using streams. Afterwards just clearing the categoryList and updating it with unique values from the hash set.
musicList.forEach((music) -> {
    categoryList.add(music.category);
});

LinkedHashSet<String> uniqueCategoryHashSet = new LinkedHashSet(categoryList);

categoryList.clear();
categoryList.addAll(uniqueCategoryHashSet);

Log.d("CATEGORY LIST" ,  categoryList.toString())

//LOG Output
CATEGORY LIST: [category1, category2, category3, category4]

Now by no means I would mark Option 3 as an efficient solution. Maybe you can do better doing it manually if you can't use streams due to API restriction. But this gets the job done.


text:
Q: Perl - A way to get only the first (.txt) filename from another directory without loading them all? I have a directory that holds ~5000 2,400 sized .txt files.
I just want one filename from that directory; order does not matter.
The file will be processed and deleted.
This is not the scripts working directory.
The intention is:

*

*to open that file,

*read it,

*do some stuff,

*unlink it and then

*loop to the next file.

My crude attempt does not check for only .txt files and also has to get all ~5000 filenames just for one filename. I am also possibly calling too many modules?
The Verify_Empty sub was intended to validate that there is a directory and there are files in it but, my attempts are failing so, here I am seeking assistance.
#!/usr/bin/perl -w
use strict;
use warnings;
use CGI;
use CGI ':standard';
print CGI::header();
use CGI::Carp qw(fatalsToBrowser warningsToBrowser);
###
use vars qw(@Files $TheFile $PathToFile);
my $ListFolder = CGI::param('openthisfolder');
Get_File($ListFolder);
###
sub Get_File{
  $ListFolder = shift;
  unless (Verify_Empty($ListFolder)) {
    opendir(DIR,$ListFolder);
    @Files = grep { $_ ne '.' && $_ ne '..' } readdir(DIR);
    closedir(DIR);
    foreach(@Files){
      $TheFile = $_;
    }
    #### This is where I go off to process and unlink file (sub not here) ####
    $PathToFile = $ListFolder.'/'.$TheFile;
    OpenFileReadPrepare($PathToFile);
    #### After unlinked, the OpenFileReadPrepare sub loops back to this script.
  }
  else {
    print qq~No more files to process~;
    exit;
  }
  exit;
}
    ####
sub Verify_Empty {
  $ListFolder = shift;
  opendir(DIR, $ListFolder) or die "Not a directory";
  return scalar(grep { $_ ne "." && $_ ne ".." } readdir(DIR)) == 0;
  closedir(DIR);
}

Obviously I am very new at this. This method seems quite "hungry"?
Seems like a lot to grab one filename and process it!
Guidance would be great!
EDIT -Latest Attempt
my $dir = '..';
my @files = glob "$dir/*.txt";
for (0..$#files){
$files[$_] =~ s/\.txt$//;
}
my $PathAndFile =$files[0].'.txt';
print qq~$PathAndFile~;

This "works" but, it still gets all the filenames. None of the examples here, so far, have worked for me. I guess I will live with this for today until I figure it out. Perhaps I will revisit and see if anyone came up with anything better.

A: You could loop using readdir inside while loop. In that way readdir won't return all files but give only one at the time,
# opendir(DIR, ...);
my $first_file = "";
while (my $file = readdir(DIR)) {

  next if $file eq "." or $file eq "..";
  $first_file = $file;
  last;
}
print "$first_file\n"; # first file in directory

A: You're calling readdir in list context, which returns all of the directory entries.  Call it in scalar context instead:
my $file;
while( my $entry = readdir DIR ) {

    $file = $entry, last if $entry =~ /\.txt$/;
}

if ( defined $file ) {
    print "found $file\n";
    # process....
}

Additionally, you read the directory twice; once to see if it has any entries, then to process it. You don't really need to see if the directory is empty; you get that for free during the processing loop.

A: Unless I am greatly mistaken, what you want is just to iterate over the files in a directory, and all this about "first or last" and "order does not matter" and deleting files is just confusion about how to do this.
So, let me put it in a very simple way for you, and see if that actually does what you want:
my $directory = "somedir";
for my $file (<$directory/*.txt>) {
    # do stuff with the files
}

The glob will do the same as a *nix shell would, it would list the files with the .txt extension. If you want to do further tests on the files inside the loop, that is perfectly fine.
The downside is keeping 5000 file names in memory, and also that if processing this file list takes time, there is a possibility that it conflicts with other processes that also access these files.
An alternative is to simply read the files with readdir in a while loop, such as mpapec mentioned in his answer. The benefit is that each time you read a new file name, the file will be there. Also, you won't have to keep a large list of file in memory.


text:
Q: Vertically centre align a cropped image in a div I'm trying to create a CSS style that will take an image and scale it to best fit a letter box shaped div. The overflow will be cropped off. I'm close with this and it currently looks like this:

The original image is

I'd like to modify this so that the image is centered vertically in the div rather than top aligned. What am I missing here? My html is

.crop {
  width: 670px;
  height: 200px;
  overflow: hidden;
}

.crop img {
  width: 670px;
}

I can't assume the height of the image to be the same everywhere I use this.

A: You can position the image relatively and then have the browser bump it upward 50% with top:-50%;:

.crop {
  width: 670px;
  height: 200px;
  overflow: hidden;
}

.crop img {
  width: 670px;
  position:relative;
  top:-50%;
}

A: You could use the CSS background-position property.
https://www.w3schools.com/cssref/pr_background-position.asp

.crop {
    width: 100%;
    height: 200px;
    overflow: hidden;
    background-image: url('http://cycle.travel/images/600/amsterdam_ccby_conor_luddy.jpg');
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
}


text:
Q: Failure encrypting web.config using RSA and file path I am using the following command in order to encrypt a file
aspnet_regiis -pef "connectionStrings" "d:\MyPath\web.config"

I get the following answer
The configuration for physical path 'd:\MyPath\web.config'
cannot be opened.
Failed!

The file is not in a read only mode and I run cmd with admin privileges.
Any Idea?

A: aspnet_regiis -pef takes the webApplicationDirectory as a parameter, and should not include the file name of the web.config;
aspnet_regiis -pef "connectionStrings" "D:\MyPath"


text:
Q: Помогите вывести все посты со списком тегов Помогите вывести все посты со списком тегов, надеюсь на скрине будет видно, и ясно как устроена баа данных.

A:   SELECT *
    FROM posts p
         JOIN posts_tags pt ON pt.post_id = p.id
         JOIN tags t ON t.id = pt.tag_id
ORDER BY t.tag_name


text:
Q: How to create a new vector from inputs in a list of vectors?
How could I make another column called "Purpose" that takes in the name of these variables if their input is "Yes"?
Note: there are observations that don't have a "Yes" input at all.
Thankfully, I already have working code:
CD$PURPOSE <- ifelse(CD$NEW_CAR == "Yes", "New_Car",
                     ifelse(CD$USED_CAR == "Yes", "Used_Car",
                            ifelse(CD$FURNITURE == "Yes", "Furniture",
                                   ifelse(CD$`RADIO/TV` == "Yes", "Radio/TV",
                                          ifelse(CD$EDUCATION == "Yes", "Education",
                                                 ifelse(CD$RETRAINING == "Yes", "Retraining", "None"))))))

I would, however, prefer to use something else. My gut instinct says that this isn't best practice.
Here is an unfinished attempt which throws an error:
PurposeCols <- c("NEW_CAR", "USED_CAR", "FURNITURE", "RADIO/TV", "EDUCATION", "RETRAINING")
Purpose <- vector(mode="character", length=1000)
possible_i= 1:1000

for (1:1000){
for (i in PurposeCols){
  if (CD[,i] == "Yes") {
    Purpose[i] = "Yes"
   }

  }
}

The reason I want to change the code is that I realize I could potentially have many more variables that I would need to do a similar process on.
Thank you.