text:
Q: OCR every .png file in a folder I want to iterate through every .png file in a folder and print every text contained in the Images. The first iteration works fine but the second gives an Error.
Code:
import pytesseract
from PIL import Image
import os

directory = (r'C:\folder...')

for filename in os.listdir(directory):
    if filename.endswith('.png'):
        Image = Image.open(filename)
        im = pytesseract.image_to_string(Image)
        print(im)

Output:

Traceback (most recent call last):   File
  "C:\Users\Artur\Desktop\Pytesseract_test.py", line 9, in
      Image = Image.open(filename) AttributeError: 'PngImageFile' object has no attribute 'open'

What does it mean 'PngImageFile' object has no attribute 'open'? Doesn't Image = Image.open(filename) does exactly that?
Thanks in advance
Edit:
The initial PngError is solved but now another Error with PIL library occured:
import pytesseract
from PIL import Image
import os

directory = (r'C:\folder...')

for filename in os.listdir(directory):
    if filename.endswith('.png'):
        img = Image.open(filename)
        im = pytesseract.image_to_string(img)
        print(im)

Output: (ocr of 'frame_0000.png' is correct and then)
Traceback (most recent call last):
  File "C:\Users\Artur\Desktop\Pytesseract_test.py", line 9, in <module>
    img = Image.open(filename)
  File "C:\Users\Artur\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\Image.py", line 2580, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'frame_0001.png'

Edit2:
This is very strange. When I do this:
for filename in os.listdir(r'folderpath...'):
    print(filename)

it works perfectly fine, iterating through every file, printing every filename.
But when I do this:
for filename in os.listdir(r'folderpath...'):
    print(filename)
    print(pytesseract.image_to_string(Image.open(filename)))

an Error is given:
Bewegung_UHF_Plots.m
Traceback (most recent call last):
  File "C:\Users\Artur\Desktop\Pytesseract_test.py", line 19, in <module>
    print(pytesseract.image_to_string(Image.open(filename)))
  File "C:\Users\Artur\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\Image.py", line 2580, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Bewegung_UHF_Plots.m'

A: Change name of variable Image to something else like pic or picture

A: Your first pass creates an object Image which is Image.open(filename), or the implementation of the 'open' method from the 'Image' class on a file 'filename'.  This is what you want on every iteration.  Unfortunately, what you've done is boot the 'Image' class out in favor of your new 'Image' object, so that in the second pass the 'Image' in Image.open(filename) is not referring to the 'Image' class, as intended, but rather to your 'Image' object.
Solve your problem by changing:
Image = Image.open(filename)
im = pytesseract.image_to_string(Image)

to:
img = Image.open(filename)
im = pytesseract.image_to_string(img)


text:
Q: Need help with partitioning I bought a new laptop with no OS and decided to try to Linux (Ubuntu) for the first time in my life. It was a clean install, my laptop had no other OS present in it, not even DOS.
While installing, it asked for partitioning. Out of the 320GB of free space I created a new partition of 20 GB and installed Ubuntu in it. The rest of the 300GB is still available as free space.
Soon I realized that I can't use the 300GB of space and that only 20GB is available to me for use.
Can anyone tell me how I can take away some free space away from the 300GB and add that to my 20GB partition?
I have installed the Gparted Partition editor from the Ubuntu Software Center but have no idea how to go ahead with it.
Thanks :)

A: Start your laptop with Ubuntu Live CD and run Gparted from there. Then select your 20 GB partition, right click on it and click resize. Resize it to use all the free space and click apply. Reboot your system after removing the CD and thats it.

A: Your best using a live cd as you can't resize a mounted partition. gparted have a live CD here,  download and burn it to cd, boot from it then select partion edittor you should then see a visual layout of your hard disk I think if you right click on your 20gb partition you should get the object to expand it.
There is a good video tut here

A: You could use Gparted from the Live CD/USB and expand the 20GB Ubuntu partition. You have to do it from CD/USB. Trying to modify a system partition from from within the installation won't work because the partition won't be editable. Gparted is preinstalled on all Ubuntu CDs.
Another option is reinstall, and let Ubuntu have all of the space. Make a backup first, in case there is stuff to backup.

A: 20GB if fine for Ubuntu. You could create another partition in the remaining space and move all your data there. The idea is to separate data from operating system. I like to encrypt the data partition. Use Ubuntu's disk utility -- it's a great tool. Link your data (docs,pics etc) to your home directory and your done.

redpajama_set_name: RedPajamaStackExchange


text:
Q: rust const fn what does it exactly mean Rust const fn
In the following article I saw the following:

A const fn allows you to execute code in a "const context." For
example:

const fn five() -> i32 {
    5
}

const FIVE: i32 = five();

What does const fn exactly do in rust? Does it just say that the function can be completely be calculated at compile time (my guess based on reading the article)


text:
Q: capturing states between tags in python using xpath I want to capture the word WORD sentence This is what I want. in following format:

WORD This is what I want.

What I tried is:
import requests
from lxml import html
cont=session.get('http://mywebsite.com').content
tree=html.fromstring(cont)
word=tree.xpath('//div[@class="message2"]/strong')
sentence=tree.xpath('//div[@class="message2"]/br')
print word
print sentence

Nothing is printed for me!

A: I find xpath helper is great for solving problems like this one
word = tree.xpath('//div[@class="message2"]/strong/text()')[0]
sentence = tree.xpath('//div[@class="message2"]/strong/following-sibling::text()[1]')[0]

A: This is what you want :)
from lxml import html

text = """

WORD This is what I want.

"""

tree = html.fromstring(text);
print(tree.xpath("//div[@class='message2']/strong/following-sibling::text()")[0])

A: I'm not sure specific about LXML but if that is the text you're looking for, calling text will not return the child tree text which exists inside of the strong tag.
So in general XPath terms, this is what you're looking for to only match that text.
//*[@class="message2"]/text()


text:
Q: Windows 11 Outlook Behaviour "Mark messages as read when deleted" not working (gmail) I have had this problem for a while now (I checked the "Mark messages as read when deleted" checkbox but it doesn't work).
My outlook version:
Microsoft® Outlook® for Microsoft 365 MSO (Version 2207 Build 16.0.15427.20182) 64-bit

It seems that the problem is only linked to gmail, because on another mailbox (one related to where I work), the option works.
Useless context: even if it's minor (at first I just recorded it for the bants), it is quite annoying as I receive a lot of emails from slurm and I don't like having unread messages in my bin (Corbeille is the French word for bin).

A: Updated:
As shown in the below figure, when the unread messages in the inbox are moved to the Trash folder, they will be marked as read.

Is your mailbox shown as mine?

Do you mean it didn't work when you select the below option?

If so, does this issue occur recently? Have you done any specific operations before that? Such as installing some third-party add-ins?
Based on my test on this option, the unread emails are marked as read after i delete them. What's the version of your Outlook? (File > Office Account > About Outlook). Please make sure you have upgraded your Outlook to the latest version.
On the other hand, it's suggested that you could uncheck it > restart Outlook > check it again to check if there're any differences.
If the issue still exists, considering that it would also be affected when the outlook program itself is damaged, it is recommended that you try to fix the Office application.


text:
Q: How do I get the number of character repetitions in a few names in the following program? I want to write a program that, with the help of pointers, takes the names of a number of people from the input and receives one character from the input for each row of the array and prints the number of repetitions of that character in the array line.
#include <stdio.h>
int main () {
   int n, i, j;
   char str[30][30];
   printf ("how many names?:");
   scanf ("%d", &n);
   int m = 0;
   for (i = 0; i < n; i++)
    {
      char ch, *s;
      scanf ("%s", str[i]);
      gets (str[i]);
      s = str[i];
      ch = getche ();
      while (*s)    if (*s++ == ch)       m++;
      printf ("%d\n", m);
    }
   return 0;
}

This program is incomplete and wrong. I want to know how we can take a letter from each of the names separately from the input and get the number of repetitions after giving the name entries to the program.
input: 2** leonardo ** peter ** o ** p /////
output:
how many names?
2
please enter 1th name:
leonardo
please enter 2th name:
peter
Number of repetitions Which letter of the name 1 do you want?
o
2
Number ofrepetitions Which letter of the name 2 do you want?
p
1

A: You can define a struct say containing the name and the count of all characters.
struct name_st
{
    char name[30];
    int count[26];
};

Create an array of the struct objects like: struct name_st s[30];
Read each name in the for loop like scanf("%s", s[i].name);

*

*For each name, after reading you can parse the name character by character and update the count for each character like s[i].count[s[i].name[j] - 'a']++;
Then in another for loop, read the character you want to display the count for in the ith name, and simply output the count for that particular character like printf("%d", s[i].count[c - 'a']);


text:
Q: Neither BindingResult nor plain target object for bean name 'user' available as request attribute during form implemetntaion I am getting this error when I run my Project and I tried all the fixes online but it did not work.

Neither BindingResult nor plain target object for bean name 'user' available as request attribute during form implementation

I am pasting the code below
Do I have to create a table in my database or how do I fix this?
I am trying to read the values entered from the form to another jsp page using spring mvc but without using annotations. And while doing so I am getting this error: Neither BindingResult nor plain target object for bean name 'user' available as request attribute My Controller Class code is as follows:
User.java
    package User;

    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;

    @Entity
    @Table
    public class User {
     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
     private Integer id;
     private String name;
     private Integer age;
     private String gender;
     private String email;
     private String city;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    }

UserController.java
    package Controller;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.PostMapping;

    import User.User;

    @Controller
    public class UserController {

    @Autowired

    private UserRepository userRepository;

    @GetMapping("/greeting")
    public String greetingForm(Model model) {

        model.addAttribute("user", new User());
        return "greeting";
    }

    @PostMapping("/greeting")
    public String greetingSubmit(@ModelAttribute User user , Model model) {

        User newUser = new User();

        newUser.setName(user.getName());
        newUser.setAge(user.getAge());
        newUser.setGender(user.getGender());
        newUser.setEmail(user.getEmail());
        newUser.setCity(user.getCity());
        userRepository.save(user);

        return "result";
    }
    @GetMapping("/all")
    public String getMeassage(Model model ) {
        Iterable<User> users = userRepository.findAll();

        model.addAttribute("users", users);
        return "all";
    }

    }

greeting.html

<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Form Submission</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

Form

    <form class="form-horizontal" role="form" action="#" th:action="@{/greeting}" th:object="${user}" modelAttribute="user" method="post">

            Name

                <input type="text"  th:field="*{name}" class="form-control" id="name" placeholder="Enter name">

            Age

                <input type="text" th:field="*{age}" class="form-control" id="age" placeholder="Enter age">

            Gender

                <input type="text" th:field="*{gender}" class="form-control" id="gender" placeholder="Enter gender(M or F)">

            Email

                <input type="text" th:field="*{email}" class="form-control" id="email" placeholder="Enter email">

            City

                <input type="text" th:field="*{city}" class="form-control" id="city" placeholder="Enter city">

                <button type="submit" class="btn btn-primary" id="btn">Submit</button>
                <input type="reset" class="btn btn-warning" value="Reset" />

    </form>

Thanks in advance for the help


text:
Q: Why is my SoapUI user interface full of odd fonts (and is completely unusable)? After multiple re-installs and using different versions, I suspect there could be some kind of corruption in the font file used by SoapUI but I am unable to determine which font to reinstall.
The versions I have installed are 5.4.0 and 5.5.0.

A: As I suspected, a font file was corrupted and by following instructions (and downloading the full default fonts pack) from https://www.w7df.com/ I was able to resolve the issue.


text:
Q: Reverse proxy setup for distributed storage I have 4 file servers that I want to access under a single mount point from another server. This server has a web application that should serve content from the mounted point.
I think I can achieve this with glusterfs.
Considering that the file servers have fairly powerful hardware, I want to install a webserver on each of them and serve those files via a reverse proxy.
Any thoughts on how I may be able to do so?

A:
I have 4 file servers that I want to access under a single mount point from another server

I suspect that sentence is rather confused. Yes you can have multiple filesystems accessible and mounted at the same place - but its not a trivial exercise - I suspect your intention is to provide a gateway to the four filesystems via a single mount point - which is not the same thing at all.
Do you mean that the same filesystem is to be available on 4 servers? This is the only scenario where glusterfs would seem to make sense.
What are the protocols involved here?
Assuming that its a replication problem, how near to real time does it have to be? How should it cope with failures?
You seem to think that a reverse-proxy is a solution. But a solution to what?

A: As a follow up, I ended up using gluster fs on the servers, having a single web server on the machine that hosted the gluster client for all the hosts.


text:
Q: Angular 4 get function return value afrer http post request I created a controller method that sends a captcha response to google server after solving a reCaptcha and the request returns a captcha response JSON. Controller method returns true if captcha response is =="success", else it returns false.
The request is sent with http POST, but the problem I'm facing is: how do I get the  boolean value from controller method after receiving a resposne after POST request?
Controller method:
 {
        if(ModelState.IsValid)
        {
            bool success = false;

            var client = new System.Net.WebClient();

            string PrivateKey = "6LeiumYUAAAAAMS0kU0OYXaDK0BxHO7KJqx2zO7l";

            var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", PrivateKey, Model.RecaptchaResponse));

            var captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ReCaptchaController>(GoogleReply);

            success = captchaResponse.Success.ToLower() == "true" ? true : false;

            return Ok(success);
        }

        return BadRequest();

    }

    [JsonProperty("success")]
    public string Success
    {
        get { return m_Success; }
        set { m_Success = value; }
    }

    private string m_Success;
    [JsonProperty("error-codes")]
    public List<string> ErrorCodes
    {
        get { return m_ErrorCodes; }
        set { m_ErrorCodes = value; }
    }

    private List<string> m_ErrorCodes;
}

POST request in DataService:
//Http Post request for server-side reCAPTCHA validation
checkRecaptcha(url: string, data: Object): Observable<boolean> {
    this.timerService.resetTimer();
    return this.http.post(url, JSON.stringify(data), this.sharedService.getRequestHeaders())
        .map((response: Response) => {
            return response.json() as boolean
        })
        .catch((response: Response) => {
            return Observable.throw(response);
        });
}

app.component.ts:
resolved(captchaResponse: string) {
    let data = {
        RecaptchaResponse: captchaResponse
    };
    let result = this.dataService.checkRecaptcha('api/recaptcha/validate', data);
    console.log(result);
}

In chrome debug I get an Observable: http://prntscr.com/ke5eeo

A: The line return response.json() as boolean returns for the observable, not for your checkRecaptcha function. You will need to listen to your own checkRecaptcha's returned Observable:
this.dataService.checkRecaptcha('api/recaptcha/validate', data).subscribe(
  (result: boolean) => console.log(result)
);

A: You need to subscribe the observable...
checkRecaptcha(url: string, data: Object): Observable<boolean> {
    this.timerService.resetTimer();
    return this.http.post(url, JSON.stringify(data), this.sharedService.getRequestHeaders());
}

afterwards you should be able to call the Service and Subscribe to its results:
this.dataService.checkRecaptcha('api/recaptcha/validate', data).subscribe((result) => {
   console.log(result);
});


text:
Q: CentOS 6.5 - After compiling gdal.so: Unable to load dynamic library CentOS release 6.5 (Final)
Linux version 2.6.18-028stab101.1 (root@rhel5-build-x64) (gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
I'm trying to Install Cartaro CMS (http://cartaro.org/). GeoServer, Postgresql and PostGIS are up and running.
The only missing software requirement to install Cantaro is the GDAL-PHP extension. I've spend hours to resolve the dependencies but after successfully compiling the gdal.so, "make test" fails with the following warning:
PHP Warning:  PHP Startup: Unable to load dynamic library '/tmp/php5-gdal-0.1.3/modules/gdal.so' - /tmp/php5-gdal-0.1.3/modules/gdal.so: undefined symbol: _ZN17GDALDriverManager10MoveDriverEP10GDALDriveri in Unknown on line 0

*

*PHP_SAPI    : cli

*PHP_VERSION : 5.4.36

*ZEND_VERSION: 2.4.0

*PHP_OS      : Linux - Linux 268.xxx.de 2.6.18-028stab101.1

*INI actual  : /tmp/php5-gdal-0.1.3/tmp-php.ini

*More .INIs  :

*CWD         : /tmp/php5-gdal-0.1.3

*Extra dirs  :

*VALGRIND    : Not used

*SKIP Test: OGRGeometry [tests/ogrgeometry.phpt]

*FAIL Test: Version number [tests/version.phpt]

I've compiled the actual stable vesions of gdal (1.9.2) and proj4 (4.8.0) by following these instructions:
https://github.com/wavded/ogre/wiki/Compiling-a-recent-ogr2ogr-from-source-on-CentOS-%28RHEL%29


text:
Q: Angular dev build fail, prod build works I've a problem with my CI and angular dev build. I didn't change anything in my code and now I can't do a dev build on an server (it works on my vm). The log says I've got an error into my code but I didn't change something in this part. Morever, the build prod works perfectly.
The problem appears on a server where I build my application through git lab ci. It worked perfectly until now.
The error I've got :
ERROR in src/Site/coreModule/sidenav/sidenav.extended.service.ts(73,21): error TS2339: Property 'customClass' does not exist on type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...'.
  Property 'customClass' does not exist on type 'number'.
src/Site/coreModule/sidenav/sidenav.extended.service.ts(74,22): error TS2339: Property 'customClass' does not exist on type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...'.
  Property 'customClass' does not exist on type 'number'.
src/Site/coreModule/sidenav/sidenav.extended.service.ts(76,22): error TS2339: Property 'customClass' does not exist on type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...'.
  Property 'customClass' does not exist on type 'number'.
src/Site/coreModule/sidenav/sidenav.extended.service.ts(80,27): error TS2339: Property 'hasParent' does not exist on type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...'.
  Property 'hasParent' does not exist on type 'number'.
src/Site/coreModule/sidenav/sidenav.extended.service.ts(81,49): error TS2345: Argument of type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...' is not assignable to parameter of type 'SidenavItem'.
  Type 'number' is not assignable to type 'SidenavItem'.
src/Site/themeModule/sidenav/sidenav.service.ts(110,22): error TS2339: Property 'hasParent' does not exist on type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...'.
  Property 'hasParent' does not exist on type 'number'.
src/Site/themeModule/sidenav/sidenav.service.ts(111,42): error TS2345: Argument of type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...' is not assignable to parameter of type 'SidenavItem'.
  Type 'number' is not assignable to type 'SidenavItem'.
src/Site/themeModule/toolbar/search-bar/search-bar.component.ts(32,54): error TS2345: Argument of type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...' is not assignable to parameter of type 'SidenavItem'.
  Type 'number' is not assignable to type 'SidenavItem'.
src/Site/themeModule/toolbar/search-bar/search-bar.component.ts(37,40): error TS2345: Argument of type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...' is not assignable to parameter of type 'SidenavItem'.
  Type 'number' is not assignable to type 'SidenavItem'.
src/Site/themeModule/toolbar/search-bar/search-bar.component.ts(50,47): error TS2345: Argument of type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...' is not assignable to parameter of type 'SidenavItem'.
  Type 'number' is not assignable to type 'SidenavItem'.
src/Site/themeModule/toolbar/search-bar/search-bar.component.ts(53,42): error TS2345: Argument of type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...' is not assignable to parameter of type 'SidenavItem'.
  Type 'number' is not assignable to type 'SidenavItem'.
src/Site/themeModule/toolbar/search-bar/search-bar.component.ts(56,50): error TS2345: Argument of type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...' is not assignable to parameter of type 'SidenavItem'.
  Type 'number' is not assignable to type 'SidenavItem'.
src/Site/themeModule/toolbar/search-bar/search-bar.component.ts(59,43): error TS2345: Argument of type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...' is not assignable to parameter of type 'SidenavItem'.
  Type 'number' is not assignable to type 'SidenavItem'.
src/Site/themeModule/toolbar/search-bar/search-bar.component.ts(62,47): error TS2345: Argument of type 'number | ((callbackfn: (value: SidenavItem, index: number, array: SidenavItem[]) => void, thisArg...' is not assignable to parameter of type 'SidenavItem'.
  Type 'number' is not assignable to type 'SidenavItem'.

My package.json
{
  "name": "Backoffice-master",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "config": "ts-node git.version.ts",
    "start": "npm run config && ng serve --env=vm --host 0.0.0.0 --disable-host-check --port 4200 --live-reload false",
    "test": "ng test",
    "build": "./node_modules/@angular/cli/bin/ng build --prod --env=prod -vc=true --build-optimizer --sourcemaps=false --named-chunks --output-path=dist/prod",
    "lint": "ng lint",
    "e2e": "ng e2e --disable-host-check --port 4200 --env=e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "5.2.0",
    "@angular/cdk": "5.2.0",
    "@angular/cli": "1.6.7",
    "@angular/common": "5.2.0",
    "@angular/compiler": "5.2.0",
    "@angular/compiler-cli": "5.0.0",
    "@angular/core": "5.2.0",
    "@angular/flex-layout": "2.0.0-beta.12",
    "@angular/forms": "5.2.0",
    "@angular/http": "5.2.0",
    "@angular/material": "5.2.0",
    "@angular/platform-browser": "5.2.0",
    "@angular/platform-browser-dynamic": "5.2.0",
    "@angular/router": "5.2.0",
    "@angular/service-worker": "5.2.3",
    "@ng-select/ng-select": "1.0.5",
    "@ngx-translate/core": "8.0.0",
    "@ngx-translate/http-loader": "1.1.0",
    "angular-sortablejs": "2.1.0",
    "core-js": "2.5.1",
    "css-element-queries": "0.4.0",
    "hammerjs": "2.0.8",
    "highlight.js": "9.12.0",
    "lodash-es": "4.17.5",
    "moment": "2.20.1",
    "ng-pick-datetime": "5.0.0-beta.11",
    "ngx-cookie-service": "1.0.9",
    "ngx-device-detector": "^1.2.2",
    "ngx-perfect-scrollbar": "5.0.0-9",
    "ngx-permissions": "4.1.0",
    "ngx-webstorage": "2.0.1",
    "node-sass": "4.7.2",
    "normalize.css": "7.0.0",
    "rxjs": "5.5.6",
    "screenfull": "3.3.2",
    "smooth-scrollbar": "8.2.6",
    "sortablejs": "1.6.1",
    "ts-helpers": "1.1.2",
    "ts-node": "4.1.0",
    "typescript": "2.6.2",
    "webpack": "3.10.0",
    "zone.js": "0.8.20"
  },
  "devDependencies": {
    "@types/jasmine": "2.8.6",
    "@types/lodash-es": "4.17.0",
    "@types/node": "6.0.90",
    "codelyzer": "4.1.0",
    "jasmine": "2.8.0",
    "jasmine-core": "2.8.0",
    "jasmine-spec-reporter": "4.2.1",
    "karma": "1.7.1",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "1.2.1",
    "karma-jasmine": "1.1.0",
    "karma-jasmine-html-reporter": "0.2.2",
    "protractor": "5.1.2",
    "tslint": "5.9.1"
  }
}

My gitlab ci :
cache:
    key: "$CI_COMMIT_SHA"
    untracked: true
    paths:
      - node_modules/
      - dist/

build:
    stage: build
    script:
        - rm ./package-lock.json
        - npm install
        - npm run config
        - ./node_modules/@angular/cli/bin/ng build --env=dev --sourcemaps=false --named-chunks --output-path=dist/dev/
        - ./node_modules/@angular/cli/bin/ng build --prod --env=int -vc=true --build-optimizer --sourcemaps=false --named-chunks --output-path=dist/int/
        - ./node_modules/@angular/cli/bin/ng build --prod --env=prod -vc=true --build-optimizer --sourcemaps=false --named-chunks --output-path=dist/prod/
    when: manual
    only:
        - tags

Version :
npm -> 5.6.0
Ubuntu -> 16.04
Any idea ?


text:
Q: Does the diffeomorphism group preserving a particular section act transitively? Let $\mathcal{D} \approx \mathbb{P}^{\delta_d}$, be the space of homogeneous
degree $d$ polynomials in three  variables $[X,Y,Z] \in \mathbb{P}^2$ upto scaling, where
$\delta_d = \frac{d(d+3)}{2}$. Note that we have two tautological line bundles
$$ \gamma_{\mathcal{D}} \rightarrow \mathcal{D}, \qquad \gamma_{\mathbb{P}^2} \rightarrow \mathbb{P}^2.$$
Note that we have a natural section of the line bundle
$$ \psi: \mathcal{D} \times \mathbb{P}^2\rightarrow
  \gamma_{\mathcal{D}}^* \otimes \gamma_{\mathbb{P}^2}^{*d}  $$
given by
$$ \psi( [s], p) = s(p) $$
Let
$$ g : \mathcal{D} \times \mathbb{P}^2 \rightarrow \mathcal{D} \times \mathbb{P}^2$$
be a diffeomorphism (need not be a biholomorphism).
Consider the subgroup under
which $\psi$ is invariant, i.e.
$$ \psi \circ g = \psi. $$
Does this subgroup act transitively on $\mathcal{D} \times \mathbb{P}^2$ ?
In other words given any two points $([s_1], p_1)$ and $([s_2], [p_2])$ does
there always exist a diffeomorphism preserving $\psi$ that takes one point to
the other?
More generally consider the section
$$ \psi_2: \mathcal{D} \times ((\mathbb{P}^2)^2 - \Delta)\rightarrow
  \gamma_{\mathcal{D}}^* \otimes \gamma_{\mathbb{P}^2}^{*d} \oplus
 \gamma_{\mathcal{D}}^* \otimes \gamma_{\mathbb{P}^2}^{*d}  $$
given by
$$ \psi_2 ([s], p_1, p_2) = s(p_1), s(p_2).$$
Does the subgroup of
$$\mathcal{Diff} ( \mathcal{D} \times ((\mathbb{P}^2)^2 - \Delta))$$
under which $\psi_2$ is invariant act transitively on
$\mathcal{D} \times ((\mathbb{P}^2)^2 - \Delta)$? Here
$\Delta$ is the diagonal.
Finally I have the same question for $k$ distinct
points.

A: I am not sure I understand the meaning of the equation $\psi\circ g=\psi$ as I don't see how to compare a section at two different points without fixing an isomorphism between the line-bundle and its pull-back under $g$. Anyway, in any possible interpretation, I don't think the group preserving $\psi$ acts transitively as it should preserve  the zero locus of $\psi$.


text:
Q: How to do prototypal inheritance in JavaScript? I've tried several ways but I couldn't do it.
On the next example I want the Soldier gets all properties of Person, and allowing to add more properties. How to do it correctly?
function Person(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.hi = function (message) {
    console.log(message + "!!!");
};

var Soldier = new(Person); // it is not the way to do it

Soldier.prototype.good_hi = function (message) {
    console.log("Sir! " + message + ", sir!");
};

A: You don't have a Soldier constructor. You need to make that first. Then you'd apply the Person constructor to new Soldier instances.
function Person(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.hi = function (message) {
    console.log(message + "!!!");
};

function Soldier(name, age) {
    Person.apply(this, arguments);
}

Soldier.prototype = Object.create(Person.prototype); // is better
Soldier.prototype.constructor = Soldier;

Soldier.prototype.good_hi = function (message) {
    console.log("Sir! " + message + ", sir!");
};

Then use it like this:
var s = new Soldier("Bob", 23);

s.good_hi("Hello");

DEMO: http://jsfiddle.net/3kGGA/


text:
Q: How to handle IllegalAccessException when calling a public method In reflection, there're such cases where you know the method you invoke is a public method, for example the constructor you get from getConstructor or getMethod. However, the compiler is still complain about IllegalAccessException when you try to invoke these methods. This is somehow contradictory, but understandable since the return type is still a Method. I'm just wondering what's the best practice to handle such cases? An dummy try catch can work but looks weird.

A: Rethrowing the exception is the correct thing to do, i.e.
try {
  Method m = ...
  m.invoke(...);
} catch (IllegalAccessException e) {
  throw new RuntimeException(e);
}

Otherwise, if the method you 'know' is public changes so that it isn't, you might never find out (if your catch clause just ignored the exception).

A: There is no way that the compiler can tell whether that the method / constructor / field / whatever you code is accessing public or not.
For example, suppose that I write and compile the following
 public class Mystery {
     public static int field;
 }

Then I write some reflective Java code to access Mystery.field, and a hypothetical Java compiler can figure out that field is public and that no exception handling is needed for the checked exceptions.
Now suppose that I modify the Mystery class to make field a private member.  Then recompile it ... without recompiling the reflective code.  Now my reflective code is going to get a checked exception that it is not coded to handle.

In summary, the reflection APIs may throw an exception, and the Java compiler (literally) CANNOT determine if that is possible or not.  Therefore, your code must1 deal with that possibility ... somehow.

I'm just wondering what's the best practice to handle such cases? An dummy try catch can work but looks weird.

*

*There are no Best Practices.

*The best answer will depends on the context.

*It is rarely a good idea to squash exceptions that you are not expecting.  (I assume that is what you mean by a "dummy catch".)  If your expectation is incorrect, you usually need to know about it.

*Wrapping and rethrowing the exception may be the correct thing to do, but there is no single "best" exception to throw.  (And I personally would never use RuntimeException for this.)

1 - If you really don't like this, the solution is "simple".  Avoid using reflection in cases where the APIs you are accessing reflectively can be used without reflection ... or could be, if you redesigned them.

A:
This is somehow contradictory

You can pass the name of any method to getMethod. The compiler has no way of knowing that you are requesting a public method. Hence getMethod declares that it may throw IllegalAccessException. Since that is a checked exception, your code must handle it. Presumably, if you request a public method, then the exception should not be thrown. Since it is unexpected that IllegalAccessException will be thrown for a public method then it is something that your code may not be able to recover from. In such cases, I usually wrap the IllegalAccessException in an unchecked exception, for example RuntimeException and throw the unchecked exception.


text:
Q: Stuck trying to createFile inside a specific folder I was hoping someone could help me with something (probably simple) that I'm stuck on.
I have a basic script which outputs each row of a spreadsheet as a separate text file. I'm using createFile to do that, and it's working fine so far. Except - I just can't work out how to make Google Scripts save the text files in a specific folder, only ever in the root. The closest I have managed to get is to create a folder, but even then I can't get the file into it (and I don't want to create a folder every single time of course).
I'm sure it's straight forward but I can't quite get my head round any of the examples I've found elsewhere. Thanks in advance.
Code below:
function processSheets() {
var sheet = SpreadsheetApp.openById("18QHevoo0TjldkjsbvljkhaljhbdFILdMNLIHEVrKsg");
SpreadsheetApp.setActiveSpreadsheet(sheet);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();

var startRow = 1; // First row of data to process
var numRows = SpreadsheetApp.getActiveSpreadsheet().getLastRow() - 1; //Get number of rows, then use to set last row to fetch

// Fetch the range of those cells
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
// Fetch values for each row in the range.
var data = dataRange.getValues();
for (i in data) {
    var row = data[i];
    var jobnumber = row[0]; // First column
    var jobname = row[1]; // Second column

    // Make friendly name by concatenating job number and job name with a space in between
    var friendlyname = jobnumber + " " + jobname

    // Create a text file with the job name as file name and content
    DriveApp.createFile(friendlyname, friendlyname);

}

}

A: If you know the Id of Google Drive Folder:
function createFile(id) {
  var folder = DriveApp.getFolderById(id);
  folder.createFile(name, content);
}

If you know the name of the folder and not the name.
function createFile(folderName) {
  var folder = DriveApp.getFoldersByName(folderName).getNext();
  folder.createFile(name, content);
}

A: For now, it has been changed to .next() instead of .getNext()


text:
Q: Windows 7 Something's running in the background that's visiting websites and running scripts A while ago I checked the option in IE's settings to always ask for 1st party cookies.
So then as I'm working (no browsers open) I started getting dialogue boxes about sites that I've never been to wanting to save cookies, and also some script warning errors. I ran scans using every AV I could get, and they didn't find anything, so I kind of forgot about it.
But then today I installed IE, and before long my history is full of pages I've never been to.
My current AV (Security Essentials) says there's nothing untoward, and a quick look through the list of running processes looks fine.
What's the next step to work out what's going on?
I'm running Windows 7 x64.

A: I'd get a firewall, maybe Zone Alarm. It should be able to tell you what's running against those sites.


text:
Q: django celeryd using wrong broker even after config_from_object This is my celery file:
from celery import Celery
from django.conf import settings

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings')
app = Celery('my_app', broker=settings.BROKER_URL)

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

and in my settings.py I have this:
#Celery stuff
BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

But when running celeryd this happens:
- ** ---------- [config]
- ** ---------- .> app:         default:0x1052af590 (.default.Loader)
- ** ---------- .> transport:   amqp://guest:**@localhost:5672//
- ** ---------- .> results:     disabled://
- *** --- * --- .> concurrency: 8 (prefork)

It doesn't seem like it's using the configuration that I have provided. What am I missing?
EDIT: comment suggested me to use djcelery:
import djcelery
djcelery.setup_loader()
BROKER_HOST = 'localhost'
BROKER_PORT = 6379
BROKER_USER = 'guest'
BROKER_PASSWORD = 'guest'
BROKER_VHOST = '/'
BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

Even with this running celeryd still defaults to 5672

A: I  think you forget to specify namespace property in config_from_object method.
so, your need to replace this
app.config_from_object("django.conf:settings", namespace="CELERY")
with
app.config_from_object("django.conf:settings")


text:
Q: What elements does it contain? I want to show that $\text{Aut}(\mathbb{Z}_n)$ is an abelian group of order $\phi (n)$.
The automorphism group of the group $\mathbb{Z}_n$, $\text{Aut}(\mathbb{Z}_n)$, is the group of isomorphisms from $\mathbb{Z}_n$ to $\mathbb{Z}_n$.
How do the elements of $\text{Aut}(\mathbb{Z}_n)$ look like?

A: Suppose $\phi\in\mathrm{Aut}(\mathbb{Z}_n)$ and suppose $\phi([1])=[m]$. Then, for $0\leq r<n$ we have
\begin{align*}
\phi([r])=&\phi([\underbrace{1+\cdots+1}_r])\\
&=\phi(\underbrace{[1]+\cdots+[1]}_r)\\
&=\underbrace{\phi([1])+\cdots+\phi([1])}_r=\underbrace{[m]+\cdots+[m]}_r=[mr]
\end{align*}
Hence, $\phi$ is multiplication by $m$ and we may write $\phi=\phi_m$. But, $\mathrm{Aut}(\mathbb{Z}_n)$ is closed under inverses and we have $\phi_m^{-1}=\phi_k$ for some $k$. Now,
$$
[1]=\phi_m^{-1}\phi_m([1])=\phi_k\phi_m([1])=\phi_k([m])=[mk]=[m][k]
$$
Hence, $[k]=[m]^{-1}$ and $[m]\in\mathbb{Z}_n^{\times}$.
Now, a computation similar to the one above also shows that $\phi_r\phi_s=\phi_{rs}$. Hence, the map
$$\Phi:\mathrm{Aut}(\mathbb{Z}_n)\to\mathbb{Z}_n^{\times}$$
given by $\Phi(\phi_m)=[m]$ is a homomorphism. It is now straighforward to check that this map is bijective. Hence, $\mathrm{Aut}(\mathbb{Z}_n)$ is an abelian group of order $|\mathbb{Z}_n^\times|=\varphi(n)$.


text:
Q: InflateException When Trying to Load Fragment I am trying to load a fragment from my activity and am getting the an error as below:
07-25 21:09:53.221 31245-31245/kitchenpal.troychuinard.com.kitchenpal E/AndroidRuntime: FATAL EXCEPTION: main
Process: kitchenpal.troychuinard.com.kitchenpal, PID: 31245
java.lang.RuntimeException: Unable to start activity ComponentInfo{kitchenpal.troychuinard.com.kitchenpal/kitchenpal.troychuinard.com.kitchenpal.IndividualRecipeActivity}: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class fragment
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class fragment
 Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class fragment
 Caused by: java.lang.NullPointerException
    at java.lang.VMClassLoader.findLoadedClass(Native Method)
    at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:742)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at android.support.v4.app.Fragment.isSupportFragmentClass(Fragment.java:404)
    at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3679)
    at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:114)
    at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:374)
    at android.support.v4.app.BaseFragmentActivityApi14.onCreateView(BaseFragmentActivityApi14.java:39)
    at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:68)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
    at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:412)
    at android.app.Activity.setContentView(Activity.java:2414)
    at kitchenpal.troychuinard.com.kitchenpal.IndividualRecipeActivity.onCreate(IndividualRecipeActivity.java:15)

I understand it may have to do with the support library that I am using for my fragment manager.
public class IndividualRecipeActivity extends AppCompatActivity implements RecipeStepsFragment.OnFragmentInteractionListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_individual_recipe);

    if (savedInstanceState == null){

        RecipeStepsFragment recipeStepsFragment = new RecipeStepsFragment();
        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction()
                .add(R.id.recipe_list_fragment, recipeStepsFragment)
                .commit();

    }
}

@Override
public void onFragmentInteraction(Uri uri) {

     }
}

Fragment:
 public class RecipeStepsFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public RecipeStepsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RecipeStepsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RecipeStepsFragment newInstance(String param1, String param2) {
        RecipeStepsFragment fragment = new RecipeStepsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_recipe_steps, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

XML:
<?xml version="1.0" encoding="utf-8"?>

<fragment
    android:id="@+id/recipe_list_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</fragment>


text:
Q: Android Studio subprojects All the examples/samples I've seen concern one app in one project in one package. Can I put two apps into the same project? into the same package? in Android Studio? I am obviously unclear on the concepts. I also don't know if a limitation will be due to the concepts or my choice of tool. I'll give an example. Suppose two apps are extremely closely related and share a lot of code as Adobe Acrobat and Adobe Reader must be. I assume Reader to be simply a subset of Acrobat code, plus a little of its own code. Could their code reside in the same package? project?
Could this be the case: Project & package = com.adobe.pdfapps
Apps = com.adobe.pdfapps.acrobat + com.adobe.pdfapps.reader (+ com.adobe.pdfapps.mobileviewer, + etc.)
So, there would be multiple apps and main activities within the project/package.
If I can organize my related apps in this manner, can I do so with Android Studio? if so, how?
Or is this addressed through build tools such as Gradle? (Yes. I am ready to write my app's viewer.)
Thanks

A: Precisely for this requirement you have libraries. Taking you example into consideration, this is how it should work:

*

*The project would be divided into several libraries, with each having its own task (there would be one library for PDF rendering, one for creating annotations, one for editing a PDF, one for converting it to a different format, etc).

*Now, since Reader and Acrobat have different set of tasks, they import different libraries into their main project, which they add as dependencies in their build.gradle file. For instance, Reader being the lighter one, imports PDF renderer, but not PDF Editing library, while acrobat imports all of them.

*Dividing it into packages has nothing to do with separation of apps, its just a way to logically separate tasks of your code. To actually separate out tasks to suit your apps, you need to separate them out as libraries, and then import them as dependencies.


text:
Q: Value Accessor issues on a radio button component So I'm trying to make just a really simple and clean radio button component that can be used with value accessor to be used in the common angular forms scenarios with FormsModule, ReactiveFormsModule and using changeDetectionStrategy.OnPush but I've ran into the issue(s) you can see ON THIS Stackblitz where I'm getting unexpected results which I understand is probably me missing something since it's been a long time since I've done a custom radio.
When it first loads, you get the radio outlines but no labels until you click something and writeValue and onModelChange are undefined while I get a  No value accessor for form control with name: error. So could use another pair of eyes so I can use the instance with good 'ol ngModel, formControlName, FormBuilder.
You'll see in the Stackblitz the value accessor is there and implementing ControlValueAccessor so I'm a bit confused since I've done the same approach with another component recently just fine. I could copy/paste parts of the blitz here but figured the example should be enough however if not just let me know.

A: I have made few changes to your code on Stackblitz, please check and let me know if it resolves your issue.
Below is the summary of the changes done:

*

*Introduced a new RadioButtonComponent property named internalValue and used it to bind to [ngModel]. Also updating it's value within writeValue() method.

*Commented the code within writeValue related to this.checked and manual update to input element's checked property. That should automatically be handled by Angular Forms API.

*Within RadioButtonComponent html template removed [attr.checked] binding and instead of using attribute binding for name and value, simply used property binding.

*In app.component.html instead of using property binding, used two-way binding [(ngModel)] syntax, so that the value gets reflected when you print it using ngModel: {{testing}}
You may change/tweak other things too, but hopefully the above changes will help you get going.

A: providers: [RADIO_VALUE_ACCESSOR]

You are missing this in your code. You need to add this in providers in component decortor


text:
Q: Trying to toggle a Redux boolean on a button click, however the toggle only works the first time and I'm not sure why I have a very simple redux slice that has 2 reducers which toggle a boolean to either on or off and a function inside of a hook that dispatches these actions depending on the current forceToggle state. By default forceToggle is false, so the first click should change forceToggle to true.
When I click the button for the first time, forceToggleOn gets dispatched which changes forceToggle to true which is what I expect.
The problem is that if I click that button again, I expect that forceToggleOff would get dispatched because forceToggle is true and change forceToggle to false, but this does not happen anymore. Only the first toggle works.
import { createSlice } from '@reduxjs/toolkit';

export type ToggleState = {
    forceToggle: boolean;
};

const initialState: ToggleState = {
    forceToggle: false,
};

export const toggleSlice = createSlice({
    name: 'activity',
    initialState,
    reducers: {
        forceToggleOn: (state) => {
            state.forceToggle = true;
        },
        forceToggleOff: (state) => {
            state.forceToggle = false;
        },
    },
});

export const { actions: toggleActions, reducer: toggleReducer } = toggleSlice;

The function that gets called on button click:
const test = () => {
    forceToggle ? dispatch(forceToggleOff()) : dispatch(forceToggleOn());
};

A: Try
const toggleForceNativeActivities = useCallback(() => {
    forceNativeActivities ? dispatch(toggleForceNativeActivitiesOff()) : dispatch(toggleForceNativeActivitiesOn());
    setItem(PERSISTED_FORCED_ACTIVITY_KEY, forceNativeActivities.toString());
}, [forceNativeActivities]);

Your handler is working with a stale value without useCallback.


text:
Q: Why is my RxJava subscription in unit test lost without being disposed I am trying to write a unit test for my view model based on RxJava. In production it runs fine but in my unit test one of my subscriptions is lost without dispose or anything ever being called.
I am using the MVI pattern. All classes (Intent, Action, Result, ViewState) just have a text for simplicity reasons.
public class ViewModel {
    private static final String TAG = ViewModel.class.getSimpleName();
    private final ISchedulerProvider schedulerProvider;
    private Observable<ViewState> viewState;
    private PublishSubject<Intent> intentEmitter = PublishSubject.create();
    private IActionProcessHolder<Action, Result> actionProcessHolder;

    public ViewModel(ISchedulerProvider schedulerProvider, IActionProcessHolder actionProcessHolder){
        this.schedulerProvider = schedulerProvider;
        this.actionProcessHolder = actionProcessHolder;
        viewState = compose();
    }

    private Observable<ViewState> compose() {
        return intentEmitter
                .compose(getIntentToActionTransformer())
                .compose(actionProcessHolder.getActionProcessor())
                .map(result -> new ViewState(result.getText()));
    }

    public void processIntents(Observable<Intent> intent){
        intent
                .subscribeOn(schedulerProvider.io())
                .observeOn(schedulerProvider.io())
                .subscribe(
                        anIntent -> intentEmitter.onNext(anIntent),
                        error -> Log.e(TAG, error.getMessage())
                );
    }

    public Observable<ViewState> getViewState(){
        return viewState;
    }

    private ObservableTransformer<Intent, Action> getIntentToActionTransformer(){
        return intent ->
                intent.map(theIntent -> new Action(theIntent.getText()));
    }
}

public class ATestScheduler implements ISchedulerProvider {

    @Override
    public Scheduler computation() { return Schedulers.trampoline(); }

    @Override
    public Scheduler io() { return Schedulers.trampoline(); }

    @Override
    public Scheduler ui() { return Schedulers.trampoline(); }
}

public class Intent {
    String text;
    public Intent(String text){ this.text = text; }
    public String getText(){ return text; }
}

public class ActionProcessHolder implements IActionProcessHolder<Action,Result>{
    @Override
    public ObservableTransformer<Action,Result> getActionProcessor(){
        return action -> action.map(theAction -> new Result(theAction.getText()));
    }
}

public class ViewModelTest {

    @Mock
    private ObservableTransformer<Action, Result> actionProcessor;
    @Mock
    private IActionProcessHolder<Action, Result> actionProcessHolder;
    private TestObserver<ViewState> testObserver;
    private ViewModel viewModel;
    private CompositeDisposable subscriptions = new CompositeDisposable();

    @Before
    public void setup(){
        MockitoAnnotations.initMocks(this);
        ISchedulerProvider schedulerProvider = new ATestScheduler();
        testObserver = new TestObserver<>();

        when(actionProcessHolder.getActionProcessor()).thenReturn(actionProcessor);
        when(actionProcessor.apply(any())).thenReturn(Observable.just(new Result("mocked text")));

        viewModel = new ViewModel(schedulerProvider, actionProcessHolder);
        subscriptions.add(viewModel.getViewState()
            .observeOn(schedulerProvider.ui())
            .subscribe(
                    viewState -> testObserver.onNext(viewState)
                    , error -> Assert.fail(error.getMessage())));
    }

    @Test
    public void testProcessIntent(){
        viewModel.processIntents(Observable.just(new Intent("newText")));
        testObserver.assertValueAt(0, viewState -> viewState.getText().equals("mocked text"));
        verify(actionProcessor, times(2)).apply(any());
    }

I am expecting the actionProcessor to be called twice, once during initialization and once when I process another intent in the actual test. However when the intent is processed, the intentEmitter in the view model no longer has any subscribers, so onNext does nothing.
I have worked out that the line in the ViewModel class:

.compose(actionProcessHolder.getActionProcessor())

seems to break it. When i simply map my action to a result like this:

.map(action -> new Result(action.getText()))

(the same the actionProcessor should do) the subscription is not disposed.
I have set breakpoints everywhere the subscriptions are disposed but none of them are ever called.
Does anyone have any idea why this happens?

A: The problem is actually not that the subscription is disposed but the chain of subscriptions is never established.
During the setup, when subscribe is called, with this line

when(actionProcessor.apply(any())).thenReturn(Observable.just(new Result("mocked text")));

Mockito immediately caused the Observable to emit its value and broke the subscription process.
I solved it now by mocking the actionProcessor without using Mockito, simply substituting above line with this:

actionProcessor = action -> action.map(ignore -> new Result("mocked text"));


text:
Q: Commutative diagrams with antiparallel arrows A diagram in category theory is said to commute when for all objects $A$ and $B$ in it, every the composite morphism resulting from a possible path from $A$ to $B$ are the identical. Does that mean that if the following diagram commutes,

Then $g = h \circ e = h \circ e \circ (f \circ e) = h \circ e \circ (f \circ e)^2 = h \circ e \circ (f \circ e)^3$ and so on?
If so, then commutative diagrams with antiparallel arrows (like $e$ and $f$ in the above diagram) must be heavily restricted...


text:
Q: Тень элемента с использованием CSS2 Как можно сделать тень элемента без использования box-shadow?

A: В CSS2 не было возможности создавать тени. Можно сделать обычный блок с тенью, заскринить его, и целиком поставить как background-image внешнего блока, внутри которого будет основной - ровно попадать внутри тени.

.pseudo-shadow {
  position: relative;
  margin-top: -4px;
  background-image: url('https://gyazo.com/e64c54f87f9d29d9f6302e5524d27ef7.png');
  width: 212px;
  height: 112px;
}

.box {
  position: absolute;
  top: 4px;
  left: 4px;
  width: 200px;
  height: 100px;
  background-color: orange;
}

/***/

.control {
  margin: 4px;
  width: 200px;
  height: 100px;
  background-color: orange;
  box-shadow: 1px 1px 5px #000;
}

картинка

box-shadow

Для блоков разного размера, можно было заморочиться и сделать 8 скринов: тени 4-х углов и 4-х сторон, расположить их в сетку + background-repeat: repeat-x / repeat-y;
https://caniuse.com/#search=CSS3%20Box-shadow - box-shadow поддерживается почти везде...


text:
Q: Textarea content produces error when trying to be alerted in JavaScript I created a HTML form that submits to a PHP script. The script should just write content of a dynamically created input element as an argument to alert JavaScript function. The input is from WYSIWYG editor (CKEditor).
When I input multiple lines of text in the editor and I press the submit button of the form, Firebug shows that the woa.php (form's target) produces an error:
SyntaxError: unterminated string literal

alert("
Hi watsup

How can I solve this?
Page with form:

<form method="post" action="woa.php" id="myForm">
<textarea name='editor1'></textarea>

<button id="button">finish edit</button>
<button>save</button>
</form>

Target of the form (woa.php):

A: JavaScript does not like line breaks inside strings. You have to change newlines to escape sequences. Use
alert("<?php echo strtr($_POST["userInput"], array("\r" => '', "\n" => '\n')); ?>");


text:
Q: Run wall command as another user RHEL8 How do I send a wall message as root (or any other user) and it not identify the original user?
Looking at the below I would have expected wall to display message from root but it still shows admin1, what am I missing?
I have tried various sudo -i, -s, using -c to send command, tmux, runuser but always the same result. Is it a global setting in sudoers or something else?
For context this was a question on a test I couldn't figure out and not been given an answer!
 [admin1@RHELPOC ~]$ sudo su - [root@RHELPOC ~]# id uid=0(root)
 gid=0(root) groups=0(root)
 context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
 [root@RHELPOC ~]# wall "whoisthis"

 Broadcast message from admin1@RHELPOC (pts/0) (Fri Jan  8 13:58:40
 2021): whoisthis

A: wall uses getlogin to get the username for the message and fallbacks to getpwuid only when getlogin call fails (see here).
getlogin returns name of the user logged in on the controlling terminal of the process (from getlogin manpage) and su only runs a shell with user and group ID 0 and even with su - it's not a "login shell" so it doesn't change the result of getlogin: Start  the shell as a login shell with an environment similar to a real login (from su manpage).
getpwuid(getuid()) actually returns the "correct" user, but that's called only when the getlogin call fails.
So to get wall "from root" you actually need to login as root on TTY. You should also be able to login using the login command but this doesn't seem to be working for me from terminal on Fedora.
Edit: Not sure what's broken in my Fedora, login is working as expected in an Ubuntu VM:
vtrefny@ubuntu:~$ sudo login
ubuntu login: root
Password:
Welcome to Ubuntu 20.04.1 LTS (GNU/Linux 5.4.0-58-generic x86_64)

...

root@ubuntu:~# wall "aaaa"

Broadcast message from root@ubuntu (pts/0) (Fri Jan  8 21:57:39 2021):

aaaa

So the answer is to use login on a system that works :-)


text:
Q: How to trigger an action upon change of state? I am testing salt as a management system, using ansible so far.
How can I trigger an action (specifically, a service reload) when a state has changed?
In Ansible this is done via notify but browsing salt documentation I cannot find anything similar.

*

*I found watch, which works the other way round: "check something, and if it changed to this and that".

*there is also listen which seems to be closer to my needs (the documentation mentions a service reload) but I cannot put together the pieces.
To set an example, how the following scenario would work in salt: check a git repo (= create it if not existing or pull from it otherwise) and if it has changed, reload a service? The Ansible equivalent is
- name: clone my service
  git:
    clone: yes
    dest: /opt/myservice
    repo: http://git.example.com/myservice.git
    version: master
    force: yes
  notify:
    - restart my service if needed

- name: restart my service if needed
  systemd:
    name: myservice
    state: restarted
    enabled: True
    daemon_reload: yes

A: Your example:
ensure my service:
  git.latest:
    - name: http://git.example.com/myservice.git
    - target: /opt/myservice
  service.running:
    - watch:
      - git: http://git.example.com/myservice.git

When there will be change in repo (clone for the first time, update etc.)
the state will be marked as "having changes" thus the dependent states -
service.running in this case - will require changes, for service it means to restart
What you are asking is covered in salt quickstart


text:
Q: Can I store a generic method in a list? I have a solution to store generic delegates into a List of objects, but is there a way to store them in a typed list and avoid casting?
I find no way and get always errors like "namespace T not found".
class TestClass {
    public delegate void dEvent<T>(object sender, T value);

    // is it possible to store the generic delegate directly ?
    // List<dEvent<T>> eventlist = new List<dEvent<T>>();

    List<object> objLst = new List<object>();

    public void Subscribe<T> (dEvent<T> ev){
        if (objLst.Contains(ev) == false)
            objLst.Add(ev);
    }

    public void InvokeAll<T>(object sender, T value) {
        foreach (var d in objLst.Where(o => (o as dEvent<T>) != null)) {
            (d as dEvent<T>).Invoke(sender, value);
        }
    }

    static public void StringSubscriber(object sender, string value) {
        Debug.WriteLine(value);
    }
    static public void IntSubscriber(object sender, int value) {
        Debug.WriteLine(value);
    }

    static public void RunTest() {
        TestClass testClass = new TestClass();
        testClass.Subscribe<string>(StringSubscriber);
        testClass.Subscribe<int>(IntSubscriber);
        testClass.InvokeAll<string>(testClass, "Hello");
        testClass.InvokeAll<string>(null, "World");
        testClass.InvokeAll<int>(testClass, 4);
        testClass.InvokeAll<int>(null, 2);
    }
}

A: It's not possible but I like this approach as a workaround:
First create 2 reusable helper classes:
public abstract class DelegateDef
{
    public abstract Type Type { get; }
}

public class TypedDelegateDef<T> : DelegateDef
{
    private T deleg;
    public T Deleg
    {
        get
        {
            return deleg;
        }
        set
        {
            deleg = value;
        }
    }
    public override Type Type
    {
        get
        {
            return typeof(T);
        }
    }
}

Then they can be used a such:
class TestClass
{
    public delegate void dEvent<T>(object sender, T value);

    public List<DelegateDef> DelegList = new List<DelegateDef>();

    public void InvokeAll<T>(object sender, T value)
    {
        var list = DelegList.Where(o => (o.Type == typeof(dEvent<T>))).ToList();
        foreach (var d in list)
        {
            TypedDelegateDef<dEvent<T>> s = ((TypedDelegateDef<dEvent<T>>)d);
            ((dEvent<T>)s.Deleg).Invoke(sender, value);
        }
    }

    static public void StringSubscriber(object sender, string value)
    {
        Debug.WriteLine(value);
    }
    static public void IntSubscriber(object sender, int value)
    {
        Debug.WriteLine(value);
    }

    static public void RunTest()
    {
        TestClass testClass = new TestClass();
        testClass.DelegList.Add(new TypedDelegateDef<dEvent<string>>() {Deleg = StringSubscriber });
        testClass.DelegList.Add(new TypedDelegateDef<dEvent<int>>() { Deleg = IntSubscriber });
        testClass.InvokeAll<string>(testClass, "Hello");
        testClass.InvokeAll<string>(null, "World");
        testClass.InvokeAll<int>(testClass, 4);
        testClass.InvokeAll<int>(null, 2);
    }
}

Solution based on:
https://www.roelvanlisdonk.nl/2010/08/31/how-to-mix-generic-classes-in-a-generic-list-in-c/


text:
Q: How do I open a terminal in Stackblitz while working on an Angular project? I know Stackblitz offers support for generating services and components from a couple of clicks. But I still need to work on terminal for my practice and add dependencies. Please don't answer that there are other better, methods than Terminal, that is not the question.
And I know that a terminal can be opened as I just opened an angular project which had terminal opened in it, but I couldn't find it or redo it.
So, How do I open a terminal in Stackblitz while working on an Angular project?

A: In Stackblitz You do not have a terminal to run Angular CLI commands.
But you can use Angular Generator to generate components, services, Pipe, Directive, etc., etc.

A: It seems like you can't open a terminal in an Angular Project, but if you create a Node.js app, you can use the terminal to create an Angular project just as you would locally.
However, I assume there is some sort of downside to this as the standard Angular setup available on the StackBlitz dashboard doesn't allow you to use the terminal. My guess is that booting a WebContainer (StackBlitz's Node.js runtime) is slower than just rendering the app statically.

A: To get a terminal, create a Node.js application on StackBlitz and use npm and the Angular CLI to create an Angular application .
StackBlitz screenshot with terminal:

A: Stackblitz mentioned there is no terminal for Angular project
https://ng-girls.gitbook.io/todo-list-tutorial/workshop-todo-list/installations/stackblitz
Not sure how did you had terminal, but I'll keep looking :P

A: Just discovered that when you get access to a terminal via NodeJS project, like Chris mentioned, and completely replace the files within it with local angular app files... you're up and running in less than a minute pretty much (after you run npm install of course)!
I did this today so I could share a private project with team members (and avoid having to set up their environments locally)!

Hope this helps someone else looking for similar solutions!

A: I suggest you to fork the sample project provided by the Angular Quick Start Guide, and replace with your code: https://angular.io/generated/live-examples/getting-started-v0/stackblitz.html
Source: https://angular.io/start#create-the-sample-project

A: Actually I came in here with the exact question @user5432838 . I saw terminal when I first opened stackblitz , however couldnt find it later .
I tried opening stackblitz again and I realized that the terminal is just getting hidden in the bottom.
To open it Just scroll to the bottom and drag up the bottom margin.
And there you go !!!
There is terminal in stackblitz.enter image description here

A: Create a NodeJS Project then you can see the terminal. After that type these commands:

*

*npm install @angular/cli

*ng new your-app-name

*cd your-app-name

*ng serve --open

Your Angular project is now published on a port, you should check the browser(on the right hand side of the Stackblitz platform)
Don't type anything in that terminal after your program was published, You can click the + button the open new Terminal. Use the new terminal for the new commands.

A: Also check that you are using Chrome or Firefox, and not Safari. As Safari will just not show the terminal!

A: When you use Angular "template", you cannot open the terminal.

*

*The template is configured as such so that everything works automatically (compile, serve).

*All your local console.log results are redirected to the web console on the page view (right side).

*You install packages in the "dependencies" part of the file project view (left side)

*

*You can directly edit package.json and add a dependency line if you have the code.

*You add angular things, such as Components, Modules, etc, by "Angular Generator"

*

*right click on any folder (or create one) at any level

*select an option in "Angular Generator" item.

*give it a name in newly opened input fields

*press enter

To have a terminal in your project, you need to start without a template (actually with a bare template)

*

*Have a new project from "Node.js" template.

*work out every step (create, run, etc.) manually.

*

*page view will automatically detect and refresh when you "serve"

*terminal shortcut is Ctrl+`  (check for MAC)

*

*or move the mouse to the bottom of the editor view (middle) and pull it out. (especially when hidden)


text:
Q: Changing password of a sftp chrootDirectory stops it from logging in So I have a chrootdir setup in sshd_config to a folder, and the user myuser, it's been working fine for months, then today I wanted to change myuser's password, so I did this with passwd, then restarted /etc/init.d/ssh restart, but now when I try login via sftp with the updated password it fails.
The sshd_config settings:
Subsystem sftp internal-sftp

Match User myuser
   ChrootDirectory /chrootDIR
   ForceCommand internal-sftp
   AllowTcpForwarding no
   PermitTunnel no
   X11Forwarding no

The logs in /var/log/auth.log are:
 sshd[13368]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=[client ip is here]  user=myuser
 sshd[13368]: Failed password for myuser from [client ip is here] port 39154 ssh2
 sshd[13368]: Connection closed by [client ip is here] [preauth]

I don't think I'm missing any steps am I?

A: Ok, so seems the issue had something todo with AllowUsers in sshd_config, as when I commented it out and restarted ssh it was working, then I added it back at the bottom of the file, restarted and it worked, then I commented the bottom one out and uncommented the original line, and restarted ssh and it still works.
So in conclusion, I'm not quite sure what it is, maybe ssh wasn't restarting proper.


text:
Q: Typing freezes in Chromium omnibox and enigmatic letter "a" in bar since Ubuntu 14.04 Since Lubuntu/Ubuntu 14.04 I can't use Chromium browser, because serious typing freezes appears in Chromium omnibox. It is possible type site address only in first tab, only one time after Chromium restart. After this it is impossible to change anything in Chromium omnibox by keyboard. It looks like keyboard not working completely. I used Chromium few years from Ubuntu 10.10 till 13.10 without problems. Typing freezes appears from 14.04 in both Lubuntu and Ubuntu.
Another note. Blue letter "a" appears in bar:

Exactly simultaneously with described problem. The letter is not a problem, but may it linked with typing freezes in some way. Clicking on the blue letter "a" don't give any effect.
How to solve problem with typing freezes in Chromium? Thanks.

A: The problem is solved here: Unable to type anything on Chromium by DK Bose:
Go to Preferences > Language Support and change Keyboard input method system from ibus to none. Then log out and log in again.
After changing ibus to none in Keyboard input methods Chromium works great.


text:
Q: PHP Base64 encode with salt string How can I encode string using PHP Base64_encode function with passing some Salt String
I don't want others to hack my string. If some one is having little knowledge in php, he can easily hack if I directly encode string. Because this is the only function allow you to decode encoded content. As far as I know.
In the tutorials I see above function will accept only one parameter.
Any Help ?

A: You should use mcrypt php extension.


text:
Q: Asymptotic Analysis of Complex Integrals Let $\gamma\subset B(0,2)\subset \mathbb{C}$ a smooth Jordan curve envolving the origin and $\phi:\mathbb{C}\setminus (-\infty,0)\to \mathbb{C}$ an analytic function having finite boundary values, that is, there exist $\phi_+(s)$ and $\phi_-(s)$ for all $s\in(-\infty,0)$.
Fix $z\in\mathbb{C}\setminus \gamma$ and suppose that
$$
\left| \int_{\gamma}\frac{e^{n\phi(s)}}{s-z}\ ds\right|\to 0,\quad \text{when}\ n\to\infty.
$$
Consider $\{g_n\}$ is a sequence of entire functions satisfying $g_n(z)=O(\frac{1}{n^{\alpha}})$ (in my case this sequence is composed by polynomials of fixed degree vanish at zero), uniformly in $B(0,2)$, for some fixed $0<\alpha<1$, let $\varepsilon>0$ be given. Have I enough hypothesis to say something about
$$
\lim_{\varepsilon\to 0}\ \ \limsup_{n\to\infty}\ \  e^{-n\varepsilon}\left| \int_{\gamma}\frac{e^{n(\phi(s)+g_n(s))}}{s-z}\ ds\right| \ ?
$$


text:
Q: How to make a transfer function in oop Hello guys i want to ask you about how should i make a transfer function for example i want to transfer money .I have two variables bank = BankAccount and i want to transfer money to them if accountNumber for example is not correct I want to print this account number didn't exist can you help me about this idea thank you a lot.Here's what i tried by far and tell me if code is good or i could change something ,Thank you a lot!
import time
import datetime
class BankSystem:
    total_deposit = 0
    total_withdraw = 0
    def __init__(self,name,accountNumber,born,salary):
        self.name = name
        self.accountNumber = accountNumber
        self.born = born
        self.salary = salary
        self.withdraw_history = []
        self.deposit_history = []
        self.account_list = []
    def description(self):
        print("Name is: " , self.name)
        print("AccountNumber: " , self.accountNumber)
        print("Salary: " , self.salary)
    def deposit(self,deposit):
        self.salary = self.salary + deposit
        self.deposit_history.append(deposit)
        self.total_deposit += 1
    def withdraw(self,withdraw):
        self.salary = self.salary - withdraw
        self.withdraw_history.append(deposit)
        self.total_withdraw += 1
    def transaction_history(self):
        print("You have withdraw", self.withdraw_history , "On date:" , datetime.datetime.now())
        print("You have deposit" , self.deposit_history , "On date:" , datetime.datetime.now())
    def take_loan(self):
        answer = int(input("Enter the amount of loan who would you like to take between - 100Euros and 300 Euros: "))
        if answer > 300:
            print("Choose between 100 - 300 Euros not more")
        else:
            print("You have taken out for loan, you will pay extra 1.5 from that sum" , answer * 1.5)
    def open_account(self):
        self.account_list.append(self.name)
        self.account_list.append(self.accountNumber)
        self.account_list.append(self.born)
    def see_account(self):
            print("New Account list" , self.account_list)

bank = BankSystem("Bill" , 42919502 , "Massachutes" , 4000)
bank = BankSystem("John" , 30503202104 , "Cardiff" , 4000)
bank.open_account()
bank.see_account()

A: To make transfer you have to assign every person to separated variable
account1 = BankSystem("Bill", 42919502, "Massachutes", 4000)

account2 = BankSystem("John", 30503202104, "Cardiff", 4000)

# transfer 100 from Bill to John
value = 100
account1.withdraw(value)
account2.deposit(value)

print('---')

account1.description()

print('---')

account2.description()

print('---')

Result:
---
Name is:  Bill
AccountNumber:  42919502
Salary:  3900
---
Name is:  John
AccountNumber:  30503202104
Salary:  4100
---

But I would rather named this class Account and I would remove account_list, open_account, see_account or move it to class Bank.
import datetime

class Account:

    def __init__(self, name, number, born, money=0):
        self.number = number
        self.name = name
        self.born = born
        self.money = money

        self.number_of_deposits = 0
        self.number_of_withdraws = 0

        self.history = []

    def description(self):
        print("Name is: " , self.name)
        print("Account Number: " , self.number)
        print("Money: " , self.money)

    def deposit(self, value):
        self.money += value
        self.history.append(value)
        self.number_of_deposits += 1
        return True

    def withdraw(self, value):
        if self.money < value:
            print(f'{self.name} no enought money')
            return False

        self.money -= value
        self.history.append(-value)
        self.number_of_withdraws += 1
        return True

    def transaction_history(self):
        today = datetime.datetime.now()
        print("You have withdraw", self.number_of_withdraws , "On date:" , today)
        print("You have deposit" , self.number_of_deposits  , "On date:" , today)

    def take_loan(self):
        answer = int(input("Enter the amount of loan who would you like to take between - 100Euros and 300 Euros: "))
        if answer > 300:
            print("Choose between 100 - 300 Euros not more")
        else:
            print("You have taken out for loan, you will pay extra 1.5 from that sum" , answer * 1.5)

class Bank:

    def __init__(self):
        self.all_accounts = {}

    def open_account(self, name, account_number, born, money):
        account = Account(name, account_number, born, money)
        self.all_accounts[account_number] = account

    def show_accounts(self, show_history=False):
        for number, account in self.all_accounts.items():
            print('\n---', number, '---\n')
            account.description()
            if show_history:
                print('History:', account.history)

    def transfer(self, account_number1, account_number2, value):
        # check if it can withdraw
        if self.all_accounts[account_number1].withdraw(value):
            self.all_accounts[account_number2].deposit(value)

    def get_account(self, number):
        return self.all_accounts[number]

# --- main ---

bank = Bank()
bank.open_account("Bill", 42919502, "Massachutes", 4000)
bank.open_account("John", 30503202104, "Cardiff", 4000)

print('\n===== before =====\n')
bank.show_accounts(show_history=True)

bank.transfer(42919502, 30503202104, 100)
bank.transfer(42919502, 30503202104, 300)
bank.transfer(30503202104, 42919502, 500)

print('\n===== after =====\n')
bank.show_accounts(show_history=True)

Result:
===== before =====

--- 42919502 ---

Name is:  Bill
Account Number:  42919502
Money:  4000
History: []

--- 30503202104 ---

Name is:  John
Account Number:  30503202104
Money:  4000
History: []

===== after =====

--- 42919502 ---

Name is:  Bill
Account Number:  42919502
Money:  4100
History: [-100, -300, 500]

--- 30503202104 ---

Name is:  John
Account Number:  30503202104
Money:  3900
History: [100, 300, -500]

EDIT:
Eventually you could use normal dictionary instead of Account but then you would have to move functions from Account to Bank and use account_number as first argument
import datetime

class Bank:

    def __init__(self):
        self.all_accounts = {}

    def open_account(self, name, account_number, born, money):
        account = {
            'name': name,
            'number': account_number,
            'born': born,
            'money': money,
            'number_of_deposits': 0,
            'number_of_withdraws': 0,
            'history': []
        }
        self.all_accounts[account_number] = account

    def show_accounts(self, show_history=False):
        for number, account in self.all_accounts.items():
            print('\n---', number, '---\n')
            self.description(number)
            if show_history:
                print('History:', account['history'])

    def transfer(self, account_number1, account_number2, value):
        # check if it can withdraw
        if self.withdraw(account_number1, value):
            self.deposit(account_number2, value)

    def get_account(self, number):
        return self.all_accounts[number]

    # -- from Account, need account_number as first argument ---

    def description(self, number):
        account = self.get_account(number)
        print("Name is: " , account['name'])
        print("Account Number: " , account['number'])
        print("Money: " , account['money'])

    def deposit(self, number, value):
        account = self.get_account(number)
        account['money'] += value
        account['history'].append(value)
        account['number_of_deposits'] += 1
        return True

    def withdraw(self, number, value):
        account = self.get_account(number)
        if account['money'] < value:
            print(f'{self.name} no enought money')
            return False

        account['money'] -= value
        account['history'].append(-value)
        account['number_of_withdraws'] += 1
        return True

    def transaction_history(self, number):
        account = self.get_account(number)
        today = datetime.datetime.now()
        print("You have withdraw", account['number_of_withdraws'] , "On date:" , today)
        print("You have deposit" , account['number_of_deposits']  , "On date:" , today)

    def take_loan(self, number):
        account = self.get_account(number)
        answer = int(input("Enter the amount of loan who would you like to take between - 100Euros and 300 Euros: "))
        if answer > 300:
            print("Choose between 100 - 300 Euros not more")
        else:
            print("You have taken out for loan, you will pay extra 1.5 from that sum" , answer * 1.5)

# --- main ---

bank = Bank()
bank.open_account("Bill", 42919502, "Massachutes", 4000)
bank.open_account("John", 30503202104, "Cardiff", 4000)

bank.deposit(42919502, 500)
bank.withdraw(30503202104, 1200)

print('\n===== before =====\n')
bank.show_accounts(show_history=True)

bank.transfer(42919502, 30503202104, 100)
bank.transfer(42919502, 30503202104, 300)
bank.transfer(30503202104, 42919502, 500)

print('\n===== after =====\n')
bank.show_accounts(show_history=True)

Result:
===== before =====

--- 42919502 ---

Name is:  Bill
Account Number:  42919502
Money:  4500
History: [500]

--- 30503202104 ---

Name is:  John
Account Number:  30503202104
Money:  2800
History: [-1200]

===== after =====

--- 42919502 ---

Name is:  Bill
Account Number:  42919502
Money:  4600
History: [500, -100, -300, 500]

--- 30503202104 ---

Name is:  John
Account Number:  30503202104
Money:  2700
History: [-1200, 100, 300, -500]


text:
Q: find number of pairs in an array that are out-of-order I have written a program that inputs an array of n elements and outputs the number of pair of elements that are out-of-order.
We will call a pair of elements arr[i] and arr[j] out-of-order if i < j and arr[i] > arr[j].
The running time of my program is O(n^2). It's a naive approach with two nested for loops. I was wondering if there is another way to solve this problem in less time. maybe in O(nLogn) time?

A: The algorithm you are looking for is called Counting inversions. Yes you can solve this problem using divide and conquer approach and the time complexity will be O(nlogn). It's similar to merge sort and additionally we need to keep track of inversions count. I am only printing the inversions count.
public class InversionsInOrderNSquared {
    public static void main(String[] args) {
        int array[] = { 10, 15, 2, 2, -4, 100, 99999, -10 };
        System.out.println("Inversions Count: "+inversions(array));
    }

    private static int inversions(int[] array) {
        int n = array.length;
        int inversionCountLeft = 0;
        int inversionCountRight = 0;
        int inversionCountCross = 0;
        if (n >= 2) {
            int mid = n / 2;
            int[] leftArray = new int[mid];
            int[] rightArray = new int[n - mid];
            for (int i = 0; i < n; i++) {
                if (i < mid) {
                    leftArray[i] = array[i];
                } else {
                    rightArray[i - mid] = array[i];
                }
            }
            inversionCountLeft = inversions(leftArray);
            inversionCountRight = inversions(rightArray);
            inversionCountCross = computeInversions(array, leftArray,
                    rightArray);
        }
        return (inversionCountLeft + inversionCountRight + inversionCountCross);
    }

    private static int computeInversions(int[] array, int[] leftArray,
            int[] rightArray) {
        int n_left = leftArray.length;
        int n_right = rightArray.length;
        int inversionCount = 0;
        int i = 0;
        int j = 0;
        int k = 0;
        while (i < n_left && j < n_right) {
            if (leftArray[i] > rightArray[j]) {
                array[k] = rightArray[j];
                inversionCount += (n_left - i);// logic is we are doing index
                // wise element comparison
                // between 2 sorted arrays thus
                // for any index if any element
                // in left
                // sub-array is grater than
                // element in right sub array
                // that mean all the elements
                // after that element present in
                // left sub-array should be
                // grater than right sub-array
                // elements. Thus we are
                // considering (n_left - i) in
                // inversion count calculation.
                j++;

            } else {
                array[k] = leftArray[i];
                i++;
            }
            k++;
        }
        while (i < n_left) {
            array[k] = leftArray[i];
            i++;
            k++;
        }
        while (j < n_right) {
            array[k] = rightArray[j];
            j++;
            k++;
        }
        return inversionCount;
    }
}

Execution 1:
Output:

Input array:
int array[] = { 10, 15, 2, 2, -4, 100, 99999, -10 };
Inversions Count: 15

Execution 2:
Input array:
int array[] = { 1,2,3,4,5,6 };

Output:
Inversions Count: 0

Regarding time complexity calculation:
computeInversions() method will take theta(n) time.

inversions() method is getting called 2 times with array size n/2.

Hence the recurrence relation is,
T(n) = 2T(n/2) + theta(n);

It's following Master's theorem equation format.

Hence a =2, b=2 and f(n)=theta(n)

n^log a base b = n^log 2 base 2 =  n^1 = n

Thus above recurrence is matching case 2 of Master's theorem.

Thus time complexity is O(nlogn)

A: You can calculate  such out of order pairs in o(nlogn) complexity.
For example if arr[] = {1,5,3,2,4}
Out of order pairs are : (5,3), (5,2), (5,4), (3,2).
Below is the working code for the same :
    public static int countOutOfOrder(int []nums) {
            int len = nums.length, index=len-1, count=0, currindex=0, total=0;
            List<Integer>sorted = new ArrayList<Integer>();
            while(index>=0) {
                currindex = search(sorted, nums[index]);
                sorted.add(currindex, nums[index]);
                total+=(currindex);
                index--;
            }
            return total;
    }

    private static int search(List<Integer> sorted, int value) {
            int start=0, end = sorted.size()-1, mid=0;
            while(start<=end) {
                mid = (start+end)/2;
                if(sorted.get(mid) == value && (mid==start || sorted.get(mid-1) == value)) {
                    return mid;
                } else if(sorted.get(mid) <= value) {
                    start = mid+1;
                } else {
                    end = mid-1;
                }
            }
            return start;
 }

Explanation for o(nlogn) solution based on above example :

*

*Maintain a list of sorted elements say sorted

*Start from end index

*

*search in sorted list where we can insert the current element in

*Based on position we can insert , find total number of elements before this index that will be total inversions.

*Add this element in the sorted list.

Time complexity :

*

*We are looping through all elements so complexity for this is o(n)

*For each element we are searching in sorted list , search complecity is o(logn).
So, total complexity is o(n)*o(logn) = o(nlogn)


text:
Q: Update nuget pacakge adds Error Condition to csproj I am working on a project with multiple solutions. I recently added a reference to a Nuget package, X in one of my solutions. This caused some version conflicts so i updated the versions of x in all my solutions. Now in solutions which had a conflict, i can see the below lines have been added
<Import Project="..\packages\X.3.3.2.0\build\X.props" Condition="Exists('..\packages\X.3.3.2.0\build\X.props')" />

<Error Condition="!Exists('..\packages\X.3.3.2.0\build\X.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\X.3.3.2.0\build\X.props'))" />

Does anyone know why this gets added and what is the significance of these lines?

A: NuGet packages may add build logic to consuming projects by having .props and/or .targets files inside their build folder.
When installed into "classic" csproj files (packages.config method), NuGet adds these statements to the csproj file to include this logic. What this actually is depends on the package. Some set values for use during the build process, some add content files that are copied to the build output and some add custom build steps (transformations etc.).
The <Import … /> element consumes the logic file, with a condition to prevent against the file missing - e.g. when the NuGet packages have not yet been restored (fresh clone/checkout, build server). If the Condition wasn't checking if the file exists, the project file may fail to load in VS.
The <Error … /> element then emits an error message if this file does not exist so that VS will show an error after the project has been loaded.

A: The problem is caused because VS doesn't manage nuget packages very well. If you move or rearrange project locations, you might have to manually correct the paths in the project file. Also, make sure that the paths for project A packages don't actually point at the project B package directory. I have seen a lot of problems with nuget packages caused by invalid paths in project files.
Also, answering your question directly, I believe that the reason you see a single error condition check, is because it was added by a nuget package. Adding most nuget packages won't trigger this check being added to your project file, only nuget packages that depend on other nuget packages. (For example, something that depended on a common package like Newtonsoft.Json might add this line of code to insure that a proper version was present)
I think (but I am not sure) that this is controlled by the package author setting a flag or something, as opposed to VS automatically tracing dependency chains.
Removing those checks is harmless and will allow you to complete an otherwise solid build in a pinch, but if you do that you risk a runtime error if the proper assembly isn't present.


text:
Q: Can anyone identify this notation? $C_{c}(G)$ Apologies if this appears to be a 'low effort' question, but I've been trying to understand this proposition in some lecture notes, and after searching online I cannot understand the following use of notation It isn't defined in the notes, so I was hoping that someone here may have seen it before might be able to let me know what it is.
We have $C_{bu}(G)$ which is defined to be the set of functions on $G$ that are both bounded and uniformly continuous.
Then it states that $C_{c}(G) \subset C_{bu}(G)$ but I'm not sure what $C_{c}(G)$ is. My first thought would be that the $c$ stood for continuous, but then the inclusion wouldn't make sense.

A: $C_c(G)$ is the set of all continuous functions with compact support.


text:
Q: Listing items by the category they belong to I'm a complete Newb so please bear with me. I've never used OOP or a framework before.
I'm creating a book keeping system where I want the ledgers to be displayed by the category they belong to. Here's my model and it seems to work:
class COAGroup(models.Model):
    Name = models.CharField(max_length=200)
    def __str__(self):
        return self.Name

class Ledger(models.Model):
    Name = models.CharField(max_length=200)
    COAGroup = models.ForeignKey(COAGroup, on_delete=models.CASCADE)
    def __str__(self):
        return self.Name

I'm working on my first view which should list all the ledgers by the category they belong to. Eg

Some COAGroup Name

A ledger that belongs to this group

Another ledger that belonds to the group

And another

Another COAGroup

A ledger that belongs to this second group

Another ledger

I've written the following view in views.py:
def showledgers(request):
    COAGroups = COAGroup.objects.all()
    Ledgers = Ledger.objects.all()
    context = {
        "COAGroups":COAGroups,
        "Ledgers":Ledgers,
    }
    return render(request,"ListLedgers.html",context)

I've  managed to get the ledgers to show in ListLedgers.html but I can't figure out how to get them to list by COA Group as per my example.
Thank you!

A: In your view, you better already .prefetch_related(..) [Django-doc] the related Ledgers:
def showledgers(request):
    COAGroups = COAGroup.objects.prefetch_related('ledger')
    context = {
        'groups': COAGroups,
    }
    return render(request, 'ListLedgers.html', context)
Then in the template, you can iterate over the COAGroups, and for each such group over the related .ledger_set:
{% for group in groups %}

{{ group.Name }}

  {% for ledger in group.ledger_set.all %}

{{ ledger.name }}

  {% endfor %}

{% endfor %}

Note: normally the name of the fields in a Django model are written in snake_case, not PerlCase, so it should be: name instead of Name.