text:
Q: Prevent modal popup reopen, angular 5 ionic framework I am using following line of code to open modal popup.
import { ModalController} from 'ionic-angular';

  openModal()
  {
    const modal = this.modalCtrl.create(ModalPage);
    modal.present();
  }

Now, from local notification click event, it opens modal popup. Everytime I click notification it open modal, I want that if modal popup is already opened in application, it should not reopen it.
How can I prevent modal from reopening?
Any help on this is highly appreciated.

A: First attempt: (track modal open status with flag)
import { ModalController} from 'ionic-angular';

  private modalOpen:boolean = false;
  openModal()
  {
    if (!this.modalOpen){
      this.modalOpen = true;
      const modal = this.modalCtrl.create(ModalPage);
      modal.present();
    }
  }

and on the dismiss function add this.modalOpen = false
Second attempt: (create Modal only once)
 import { ModalController} from 'ionic-angular';

  private modal;
  constructor(){
    this.modal = this.modalCtrl.create(ModalPage);
  }
  openModal()
  {
    this.modal.present();
  }

Edit after comments Third attempt: (track openState in Provider/Store)
import { StateProvider } from 'yourStateProvider';
import { ModalController} from 'ionic-angular';

  constructor(private state:StateProvider){}

  openModal()
  {
    if (!this.stateProvider.modalOpen){
      this.stateProvider.modalOpen = true;
      const modal = this.modalCtrl.create(ModalPage);
      modal.present();
    }
  }

ModalPage.ts
import { StateProvider } from 'yourStateProvider';

  constructor(private state:StateProvider){}

  dismiss(){
    this.stateProvider.modalOpen = false;
  }

StateProvider.ts
public modalOpen:boolean = false;

A: import {Modal} from "ionic-angular/components/modal/modal";
import {ModalOptions} from "ionic-angular/components/modal/modal-options";
import {ModalController} from "ionic-angular";

export class ModalHelper {
  protected modal:Modal;
  protected isModalIsOpen:boolean=false;

  constructor(protected modalCtrl:ModalController) {

  }
  /**
   * opens a modal
   * @param component
   * @param data
   * @param {ModalOptions} opts
   */
  openModal (component: any, data?: any, opts?: ModalOptions) {
    if (this.isModalIsOpen === false) {
      this.modal = this.modalCtrl.create(component, data, opts);
      this.modal.present().then(()=>{
        this.isModalIsOpen = true;
      });
      this.modal.onDidDismiss(()=>{
        this.isModalIsOpen = false;
      })
    }
  }
}

I used openModal helper to open a modal from provider by usinf following line of code:
Provider:
my-provider.providers.ts
import { ModalController} from 'ionic-angular';
import {ModalHelper} from "../../../helper/modal.helper";

  openModal()
  {
    this.modalHelper.openModal(ModalPage);
  }


text:
Q: Text edit toolbar solution (js), with low-level customization? I'm looking for a js text edit toolbar, which allows for customization of base functions.
The best example is: Our platform employs a custom text parsing engine, and we use custom tags. Custom tags, even for basics like bold, etc. Therefore, I will need to change existing base formatting buttons to use our tags as opposed to html.
I have not been able to locate a solution, which allows the customization of these basic buttons. I can, of course use something mainstream, and rebuild all the base functionality in custom buttons. However, before doing that, I want to make sure there is not something already available.
Do you know of a solution which supports low level customization?

A: You can have look at this one: https://github.com/bergie/hallo

redpajama_set_name: RedPajamaStackExchange


text:
Q: MongoDB loads of daily data (or stick with mysql?) In short, we have a business vehicle control via GPS currently working on mysql with a large volume of data. We are studying the possibility of moving to mongoDB as db but still do not see clear. Currently, we are testing with mongoHQ (daas mongoDB).
We have aprox 2000 gps sending information every minute with position, velocity and state. In one day, 24 hours, 1440 minutes, each gps sends 1440 tracks of information, so 1440tracks/device * 2000devices = 2.8M tracks / day.
Our first idea was to have a collection and store each track as a doc in this collection, but daily 2.8M generating tracks at the end of the month we have +-80M documents in a collection. We have to create daily, weekly or reports between dates, for example, if after 2 months of service, a client wants to see a report of 3 days, we would have to do a find of 1440 tracks/day * 3days inside about 160M documents ... how would be the response times? mongodb saturated? If multiple clients make similar requests at once, what would happen?

NOTE: Each document occupies approx 0.3KB , whereby each GPS per day
  occupies 0.3 * 1440 = 0.5MB , although greater storageSize ...

Second idea embedding.
Here we decided to group all the tracks on a daily document. Each has 1 gps doc / day and 1440 tracks of information are added $push into an array of tracks { }. Thus, each day we would have only 2k docs and by the end of the month just 60k instead of 80M! We thought 'we had found gold' until we realized that $pushing 1440 tracks inside each doc daily created  reallocation whereby each document takes much longer and is not viable .. How could we improve embedding ? If the first idea was generating about 1GB storage daily, with this is about 3GB...
With the first idea, track = doc, gps need 0.5MB each day (a little bit more storagesize), which would be about 1GB daily for 2000 teams. About 30 GB per month, even with the heaviest of mongohq plan (600GB) or mongolab (400GB), we would have a maximum of 20 months of service before reaching the limits ..
But the same in mysql after year and a half, we are not occupying more than 30GB .. :/
Currently, we do not see option to change and we have to stick with Mysql for now... any idea on how to make a good switch from mysql to nosql?

A: When you know that your documents will reach a certain size, you can avoid reallocation by prepopulating them at creation.
When you know that your array will eventually have exactly 1440 entries, you can create the document with 1440 dummy-entries with the same set of fields, all filled with placeholder data which has the same length as the real data. When you then gradually add the real data, you replace these entries with $set instead of using $push.
To improve the performance of reports which aggregate data of past days, you could run a MapReduce job every night to aggregate the relevant data of the day into a new collection.

A: Welcome to big data...
What we do is this:
We have a influx of log events at the rate of about 200 logs/sec.
These logs are put in a database.collection called log.foo.
You don't touch these records. Only new inserts are made here. NEVER EVER UPDATE THEM. It will lock your database and kill it's performance.
What you do is create a new database.collection called aggregate.foo. This is a new database because it will have its own write lock and will therefore not interfere with your log database.
Then you create a job that you run with cron or something similar. This job makes a query on log.foo for a given timeslice (ObjectId is very usefull for that). The job aggregates these lines as you see fit and puts new documents in aggregate.foo. Then you can choose to delete the rows from log.foo if you want, but storage is cheap, so why not keep them.
So essentially: combine your two ideas, but separate log insertion and aggregation.


text:
Q: How to focus input when the screen gets rendered Is there any props in TextInput Componenet? ,If Yes, tell me or comment below . Thanks in advance
 <TextInput
      style={styles.numberContainer}
      label="phoneNumber"
      id="phoneNumber"
      required
      ref={inputRef}
      autoFocus={true} //   ref={num}
      keyboardType="phone-pad"
      returnKeyType="next"
      onChangeText={val => validator(val)}
      onEndEditing={e => {
             validator(e.nativeEvent.text);
      }}
/>

A: Try this
const { useState, useRef, useEffect } = React;

const Example = () => {

  const inputRef = useRef(null);

  useEffect(() => {
      inputRef.current.focus();
  }, []);

  return (
    <div>
      <TextInput ref={inputRef}
    </div>
  );
};


text:
Q: Read R function output as columns I'm trying to come up with a way to solve this question I asked yesterday:
rpy2 fails to import 'rgl' R package
My goal is to check if certain packages are installed inside R from within python.
Following the recommendation by Dirk Eddelbuettel given in a comment on his answer, I'm using the installed.packages() function from R to list all the available packages.
This is what I've got so far:
from rpy2.rinterface import RRuntimeError
from rpy2.robjects.packages import importr
utils = importr('utils')

def importr_tryhard(packname, contriburl):
    try:
        rpack = utils.installed_packages()
    except RRuntimeError:
        rpack = []
    return rpack

contriburl = 'http://cran.stat.ucla.edu/'
rpack = importr_tryhard(packname, contriburl)
print rpack

Which returns a quite large output of the form:
           Package      LibPath                         Version
ks         "ks"         "/usr/local/lib/R/site-library" "1.8.13"
misc3d     "misc3d"     "/usr/local/lib/R/site-library" "0.8-4"
mvtnorm    "mvtnorm"    "/usr/local/lib/R/site-library" "0.9-9996"
rgl        "rgl"        "/usr/local/lib/R/site-library" "0.93.986"
base       "base"       "/usr/lib/R/library"            "3.0.1"
boot       "boot"       "/usr/lib/R/library"            "1.3-9"
class      "class"      "/usr/lib/R/library"            "7.3-9"
cluster    "cluster"    "/usr/lib/R/library"            "1.14.4"
codetools  "codetools"  "/usr/lib/R/library"            "0.2-8"
compiler   "compiler"   "/usr/lib/R/library"            "3.0.1"
datasets   "datasets"   "/usr/lib/R/library"            "3.0.1"
foreign    "foreign"    "/usr/lib/R/library"            "0.8-49"
graphics   "graphics"   "/usr/lib/R/library"            "3.0.1"
grDevices  "grDevices"  "/usr/lib/R/library"            "3.0.1"
grid       "grid"       "/usr/lib/R/library"            "3.0.1"
KernSmooth "KernSmooth" "/usr/lib/R/library"            "2.23-10"
lattice    "lattice"    "/usr/lib/R/library"            "0.20-23"
MASS       "MASS"       "/usr/lib/R/library"            "7.3-29"
Matrix     "Matrix"     "/usr/lib/R/library"            "1.0-14"
methods    "methods"    "/usr/lib/R/library"            "3.0.1"
mgcv       "mgcv"       "/usr/lib/R/library"            "1.7-26"
nlme       "nlme"       "/usr/lib/R/library"            "3.1-111"
nnet       "nnet"       "/usr/lib/R/library"            "7.3-7"
parallel   "parallel"   "/usr/lib/R/library"            "3.0.1"
rpart      "rpart"      "/usr/lib/R/library"            "4.1-3"
spatial    "spatial"    "/usr/lib/R/library"            "7.3-6"
splines    "splines"    "/usr/lib/R/library"            "3.0.1"
stats      "stats"      "/usr/lib/R/library"            "3.0.1"
stats4     "stats4"     "/usr/lib/R/library"            "3.0.1"
survival   "survival"   "/usr/lib/R/library"            "2.37-4"
tcltk      "tcltk"      "/usr/lib/R/library"            "3.0.1"
tools      "tools"      "/usr/lib/R/library"            "3.0.1"
utils      "utils"      "/usr/lib/R/library"            "3.0.1"
           Priority
ks         NA
misc3d     NA
mvtnorm    NA
rgl        NA
base       "base"
boot       "recommended"
class      "recommended"
cluster    "recommended"
...

I need to extract just the names of the packages installed, so either the first or the second columns would be enough for me.
I've tried using np.loadtxt(), np.genfromtxt() and with open(rpack) as csvfile:, but none was able to give back a list/array where either the columns or the rows was correctly separated (they all failed with different errors actually).
How could I read this output in column form, or more to the point, extract the names of the installed packages in a list/array?

A: I've not used r2py before, but it looks like it's some kind of r2py object, and that might have an option to just grab that first column.
You could hapily parse it like a text file though; when you call print XXX it grabs the string representation of the object.
Try doing something like this:
s = str(rpack)
packages = [line.split()[0] for line in s.split("\n")[1:]]

You should try both the str and repr methods to get the string representation though, some people don't use both, or use them differently.
This doesn't feel like the cleanest way to do it though, and you'll have to make sure you parse the data correctly. Try printing dir(rpack) and seeing if there are any attributes in there which sound like they'll contain what you want.
A little bit of digging, the installed_packages documentation, and a quick peek at an R tutorial suggests you can just do this:
print mpack[,"Package"]

A: rpack in your case is an rpy2.robjects.vectors.Matrix object. Therefore you can simply use rpy2 class method .rx() to extract the column:
mylist = list(rpack.rx(True, 1))

Have a try.


text:
Q: "Invalid conversion" error when visiting a variant of functions I am trying to std::visit a std::variant of std::function types.
Why does the following code not compile:
#include <functional>
#include <variant>

int main()
{
  std::variant<
      std::function< int () >,
      std::function< float () >
  > func_variant {std::in_place_index<0>, [] () { return 42; }};

  auto object = std::visit( [] (auto& func) { return func(); }, func_variant);

  return 0;
}

The error happens in the call of std::visit, where it says:
error: invalid conversion from 'std::__success_type<float>::type (*)(main()::<lambda(auto:1&)>&&, std::variant<std::function<int()>, std::function<float()> >&)' {aka 'float (*)(main()::<lambda(auto:1&)>&&, std::variant<std::function<int()>, std::function<float()> >&)'} to 'int (*)(main()::<lambda(auto:1&)>&&, std::variant<std::function<int()>, std::function<float()> >&)' [-fpermissive]
       { return _Array_type{&__visit_invoke}; }
                                           ^

A: Each of your std::function types returns a different type, so the return type of the lambda you are passing to std::visit depends on the type of the selected element of the lambda. This means that the auto-type-deduction can't work, as the call to std::visit must have a single return type which is independent of which element of the variant is active.
You could make a return type variant: using returns=std::variant<int,float> and then cast the return in your lambda to that:
using returns=std::variant<int,float>;
auto object = std::visit( [] (auto& func) { return returns(func()); }, func_variant);

That way the return type of your lambda is the same in all cases, but you will then need to query the result to see what you got.


text:
Q: LINUX - Shell Scripting - Generate map(key value pair) from flat file I have a flat file which is similar to JSON(not exactly same).
Final motive is to convert it into CSV (in specific order, not same as input JSON File ) and dump in database. now since the input file is not always in same order AWK, cut etc wont be useful. Need something like HASHMAP. Attaching sample Input and Expected out. Suggestions please.
Input JSON file sample (I have like 1000 files, 50K rows each, 200 columns each)
{"Field1":{"string":"Value,123"},"Field2":{"string":"564243"},"Field3":{"string":"SWCHP0001155"},"LOCATION":null,"OWNERUID":{"string":"655,,34"}}
{"Field1":{"string":"Value,456"},"Field2":{"string":"89565655"},"Field3":{"string":"SWCHP0001166"},"LOCATION":{"string":"BEACH,"},"OWNERUID":{"string":"65534"}}
........

Output CSV File Expected in specific order, lets say in order (OWNERUID, LOCATION, Field1, Field2, Field3)
655;;34,null,Value;123,564243,SWCHP0001155
65534,BEACH;,Value;456,89565655,SWCHP0001166

My idea so far is to do some string manipulation change eveything a standard format like below, transfer Data into hashmap, fetch in required and dump in CSV
Intermediate Standard format : (can be changed, please suggest)
Field1?Value;123,Field2?564243,Field3?SWCHP0001155,LOCATION?null,OWNERUID?655;;34
Field1?Value;456,Field2?89565655,Field3?SWCHP0001166,LOCATION?BEACH;,OWNERUID?65534
........

note:

*

*values contain , and other special characters

*I can change values a bit like converting commas to semicolon (like above)

*There are NULL values to be handled

A: jq is a C tool that aims at processing JSON strings. It acts as a filter (or a chain of filters) that processes one input at a time and has a fairly nice documentation. It may be available in your distribution, or pretends to be built from source with no to little dependancies beyond a C compiler. In your example, this should be enough:
$ cat file.json |  jq '[.OWNERUID.string, .LOCATION.string?, .Field1.string?, .Field2.string?, .Field3.string?]|join(";")'
"655,,34;;Value,123;564243;SWCHP0001155"
"65534;BEACH,;Value,456;89565655;SWCHP0001166"
$

Or if you want to get rid of the enclosing quotes, a sed filter can remove them:
$ cat ess.txt |  jq '[.OWNERUID.string, .LOCATION.string?, .Field1.string?, .Field2.string?, .Field3.string?]|join(";")' | sed -e 's/^"\(.*\)"$/\1/'
655,,34;;Value,123;564243;SWCHP0001155
65534;BEACH,;Value,456;89565655;SWCHP0001166
$


text:
Q: Algorithm to determine all possibilities for names given an array [in PHP]? Mismatch between code here & code in project caused problem.

A: foreach ($words as $first) {
    foreach ($words as $second) {
        $taken[] = $first.$second;
    }
}

A: If you want all possible combinations without having duplicates (ex:w1w1), use this:
$allCombinations = null;
$words = array('w1', 'w2', 'w3', 'w4', 'w5', 'w6', 'w7', 'w8', 'w9', 'w10');

foreach ($words as $word1)
{
    foreach ($words as $word2)
    {
        if ($word1 != $word2)
        {
            $allCombinations[] = $word1.$word2;
        }
    }
}

echo count ($allCombinations); // The count is 90, and that's what it should be.
print_r($allCombinations);


text:
Q: How to load different component if route has params using VueJS Router I'm looking for a proper way to load a different VueJS component if there are any props included in a route.
For example, if I go to

/users

I get the users list page and if I'd go to

/users/1

I would go to user profile page.
I've been trying to add another route as a child with parameters but it wouldn't seem to help:
{
            path: "users",
            name: "users",
            component: UsersList,
            children: [
                {
                    path: "users/:userId",
                    name: "User Profile",
                    component: UserProfile,
                },
            ]
},

I am pushing the user profile route from a method like this:
this.$router.push({ path: 'users', name: 'User Profile', query: { userId: row.id }})

Any ideas?

A: It is simple. This is what you need to do:
{
    path: "users",
    name: "users",
    // IMPORTANT - UserParent contains `<router-view></router-view>`
    component: UserParent,
    children: [
        {
            // IMPORTANT - NEEDS TO BE BLANK
            path: "",
            name: "user-list",
            component: UserList,
        },

        {
            path: ":userId",
            name: "user-profile",
            component: UserProfile,
        }
    ]
}

Here routes will be concatenated to form final routes.


text:
Q: Print WebElement variable name through WebDriverEventListener I am using EventFiringWebDriver and WebDriverEventListener. In listener I am implementing method after clickOn(WebElement arg0, WebDriver arg1) method.
WebElement myaccountLink =driver.findElement(By.cssSelector("div.footer>div.links>ul>li>a[title='My Account']"));
myaccountLink.click();

The listener:
public void afterClickOn(WebElement arg0, WebDriver arg1) {
    System.out.println("Clicked : "+arg0.toString());
}

The result is:

Clicked : -> css selector: div.footer>div.links>ul>li>a[title='My Account']]

But I'd like:

Clicked : myaccountLink

A: You may try to build a custom class like this:
public class Selector {
    public String name;
    public By by;

    public Selector(String name, By by){
        this.name= name;
        this.by = by;
    }

    public String getName(){
        return name;
    }

    public By getBy(){
        return by;
    }
}

Then, in your code:
Selector myAccountLink = ("Link to 'My account'", By.cssSelector("div.footer>div.links>ul>li>a[title='My Account']"));
System.out.println("Clicked: " + myAccountLink.getName());

// Output: "Link to 'My account'"

A: I'm open to correction on this but as far as i know, it's  not possible. Variable names aren't communicated in Java, only the values.


text:
Q: Открыть порт на ПК linux Как открыть порт в такой схеме: роутер, к нему присоединено 2 ПК? Нужно открыть порт 2222 на обоих компьютерах. В роутере я уже прописал оба правила. В iptables тоже, но подключение есть только на первом из двух.

A: Видимо одинаковые порты нельзя назначать. При назначении на втором ПК другого номера порта (отличного от первого), соединение появляется.


text:
Q: Delphi: What are the advantages of using System.New() instead of a local variable, other than just spare a tiny amount of memory? Let's go back to the basics. Frankly, I have never used New and Dispose functions before. However, after I read the New() documentation and the included examples on the Embarcadero Technologies's website and the Delphi Basics explanation of New(), it leaves questions in my head:
What are the advantages of using System.New() instead of a local variable, other than just spare a tiny amount of memory?
Common code examples for New() are more or less as follows:
  var
      pCustRec : ^TCustomer;
  begin
      New(pCustRec);
      pCustRec^.Name := 'Her indoors';
      pCustRec^.Age  := 55;
      Dispose(pCustRec);
  end;

In what circumstances is the above code more appropriate than the code below?
  var
      CustRec : TCustomer;
  begin
      CustRec.Name := 'Her indoors';
      CustRec.Age  := 55;
  end;

A: From a different perspective:
Both can suffer from buffer overflow and can be exploited.
If a local variable overflows, you get stack corruption.
If a heap variable overflows, you get heap corruption.
Some say that stack corruptions are easier to exploit than heap corruptions, but that is not true in general.
Note there are various mechanisms in operating systems, processor architectures, libraries and languages that try to help preventing these kinds of exploits.
For instance there is DEP (Data Execution Prevention), ASLR (Address Space Layout Randomization) and more are mentioned at Wikipedia.

A: A local static variable reserves space on the limited stack. Allocated memory is located on the heap, which is basically all memory available.
As mentioned, the stack space is limited, so you should avoid large local variables and also large parameters which are passed by value (absence of var/const in the parameter declaration).
A word on memory usage:
1. Simple types (integer, char, string, double etc.) are located directly on the stack. The amount of bytes used can be determined by the sizeof(variable) function.
2. The same applies to record variables and arrays.
3. Pointers and Objects require 4/8 bytes.

A: Every object (that is, class instances) is always allocated on the heap.
Value structures (simple numerical types, records containing only those types) can be allocated on the heap.
Dynamic arrays and strings content are always allocated on the heap. Only the reference pointer can be allocated on the stack. If you write:
  function MyFunc;
  var s: string;
  ...

Here, 4/8 bytes are allocated on the stack, but the string content (the text characters) will always be allocated on the heap.
So using New()/Dispose() is of poor benefit. If it contains no reference-counted types, you may use GetMem()/FreeMem() instead, since there is no internal pointer to set to zero.
The main drawback of New() or Dispose() is that if an exception occur, you need to use a try...finally block:
  var
    pCustRec : ^TCustomer;
  begin
    New(pCustRec);
    try
      pCustRec^.Name := 'Her indoors';
      pCustRec^.Age  := 55;
    finally
      Dispose(pCustRec);
    end;
  end;

Whereas allocating on the stack let the compiler do it for you, in an hidden manner:
  var
    CustRec : TCustomer;
  begin // here a try... is generated
    CustRec.Name := 'Her indoors';
    CustRec.Age  := 55;
  end;  // here a finally + CustRec cleaning is generated

That's why I almost never use New()/Dispose(), but allocate on stack, or even better within a class.
2

A: The usual case for heap allocation is when the object must outlive the function that created it:

*

*It is being returned as a function result or via a var/out parameter, either directly or by returning some container.

*It's being stored in some object, struct or collection that is passed in or otherwise accessible inside the procedure (this includes being signaled/queued off to another thread).

A: If you can use a local variable, do so. That's a rule with practically no exceptions. This results in the cleanest and most efficient code.
If you need to allocate on the heap, use dynamic arrays, GetMem or New. Use New when allocating a record.
Examples of being unable to use the stack include structures whose size are not known at compile time, or very large structures. But for records, which are the primary use case for New, these concerns seldom apply.
So, if you are faced with a choice of stack vs heap for a record, invariably the stack is the correct choice.

A: In cases of limited stack space you might prefer allocation from the heap.
Ref.


text:
Q: Rails: validate that all belongs_to are integers? I use the selectize plugin extensively for letting users select an associated model. Sometimes, their javascript fails and the form tries to submit a String instead of a model ID. Since I have foreign key constraints, this causes a 500 exception. Is there some rails-way to mass-apply a
validates :product_id, numericality: true

To all belongs_to references in all active record models?


text:
Q: TFS Continous build identify Build Failed Event I have implemented continous build using TFS windows workflow.
In this I have created a custom activity that will help me creating custom template of folders.
Is there any way that I can monitor the status of the build, that is if the build fails due to some exception I want to set a flag in database table that i created to failed.
I want to handle this in C# TFS API only.

A: Yes, you would need to probably create a custom build activity to enter your record in the database. You would place this custom activity in the template at the very end of the Run on Agent Sequence and check the status of Microsoft.TeamFoundation.Build.Client.BuildStatus.Failed to know if the build failed or not

A: You can use the QueryBuilds method from the IBuildServer service API to query all builds inside TFS. You can specify the Build Status as one of the filters, plus a date range when the number of builds in the database grows too large.


text:
Q: Unix Shell scripting for copying file from one folder to another Hi this is my shell script to copy files from one directory to another  directory with timestamp.But my script shows too many arguments.I want to copy files from one directory to another.What error in my code.
Date_Val="$(date +%Y%m%d%H%M%S)";

cd /etl_mbl/SrcFiles/

if [  -f /etl_mbl/SrcFiles/SrcFiles_TEMP*.csv ]
then
cp /etl_mbl/SrcFiles/SrcFiles_TEMP/*.csv /etl_mbl/SrcFiles/Archive/*_$Date_Val.csv
fi

A: The reason you got "too many arguments" error is that the wildcard in the "if" statement expands to a multitude of files. Please also note that you cannot have wildcards in the destination of a "cp". You probably want something like this:
#!/bin/bash

Date_Val="$(date +%Y%m%d%H%M%S)";

for file in ./src/*.csv; do
    filename=${file##*/}
    basename=${filename%.*}
    cp $file ./archive/$basename\_$Date_Val.csv
done


text:
Q: Show and hide divs on click What am I doing wrong? I am trying to show divs when the thumbnail is clicked. I am able to show the first div, but for some reason, the next div is not showing. I cannot figure out what I might be missing.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel tortor sit amet magna condimentum dapibus non quis nulla. Etiam varius pellentesque quam sed faucibus. Ut libero mi, porta ac tincidunt sagittis, porttitor a elit. In non tellus eu mauris tristique gravida. In rutrum arcu ullamcorper risus consequat interdum. Sed rutrum rhoncus dolor. Suspendisse potenti.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel tortor sit amet magna condimentum dapibus non quis nulla. Etiam varius pellentesque quam sed faucibus. Ut libero mi, porta ac tincidunt sagittis, porttitor a elit. In non tellus eu mauris tristique gravida. In rutrum arcu ullamcorper risus consequat interdum. Sed rutrum rhoncus dolor. Suspendisse potenti.

Enlarged Image 1

Enlarged Image 2

A: Try including a selector in the .index() method:
$(function(){
    $('.clickImage').click(function(){
        $('.popUp').hide();
        $('.popUp').eq($(this).index(".clickImage")).show();
    });
});

A: I don't think index() is doing what you are intending for it to do.
I would use a dataImageId attribute or something similar to uniquely identify the images.

A: your index is 2 as selected, use something like this:
$('.clickImage').click(function () {
       var i=$('.clickImage').index(this);
       $('.popUp').hide();
       $('.popUp').eq(i).show();
});

index is 0 based.
Note that the first returns 0 as it is the first div, and 2 on the second as it is the third div, so you need to isolate to the divs with the .clickImage class
Here is a simple fiddle to demonstrate: http://jsfiddle.net/zfZE2/

A: Your first clickable clickImage will work because it will return index:0.
Which is the right corresponding popup.
But for the second clickImage it will return index:2, which does not have a corresponding popup. Only 0 and 1 are present.
This is because .textVertical is also seen as a sibling of clickImage, thus the 2nd clickImage you clikc will be the 3rd sibling (index).
Change
  $('.popUp').eq($(this).index()).show();

To
  $('.popUp').eq($(this).index('.clickImage')).show();

http://jsfiddle.net/rNSLE/

A: Try this way:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel tortor sit amet magna condimentum dapibus non quis nulla. Etiam varius pellentesque quam sed faucibus. Ut libero mi, porta ac tincidunt sagittis, porttitor a elit. In non tellus eu mauris tristique gravida. In rutrum arcu ullamcorper risus consequat interdum. Sed rutrum rhoncus dolor. Suspendisse potenti.

Enlarged Image 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel tortor sit amet magna condimentum dapibus non quis nulla. Etiam varius pellentesque quam sed faucibus. Ut libero mi, porta ac tincidunt sagittis, porttitor a elit. In non tellus eu mauris tristique gravida. In rutrum arcu ullamcorper risus consequat interdum. Sed rutrum rhoncus dolor. Suspendisse potenti.

Enlarged Image 2


text:
Q: Is SVD included in MathNet.Numerics x86? I need to calculate the Singular Value Decomposition of a Dense matrix but it doesn't seem to be included in the package I'm using: MathNet.Numerics x86 v2.4.0.26 downloaded from Nuget package manager.
I am referencing this question Svd recomposition..
The syntax included in the answer linked is:
 var m = DenseMatrix.OfArray(new double[,] {
   { 3, 0, 0, 0, 0 },
   { 0, 2, 4, 0, 0 },
   { 0, 4, 5, -4, 5 },
   { 0, 0, -4, -8, 12},
   { 0, 0, 5, 12, -5 }});

  var svd = m.Svd(true);  //The method Svd() doesn't seem to be available in v2.4

  svd.U() * svd.W() * svd.VT()

Nor is  svd() listed in the documentation.
I'm looking for a simple example of generating a SVD of a DenseMatrix using the MathNet.Numerics x86 library.
Unfortunately the method inverse() is just returning NaN so I'm hoping to approximate the inverse using singular value decomposition.

A: From the documentation I found classes for singular value decomposition
MathNet.Numerics.LinearAlgebra. Double/Single/Generic .Factorization.Svd are abstract classes.
MathNet.Numerics.LinearAlgebra. Double/Single/Generic .Factorization.DenseSvd are implementations.  Pass your matrix to the constructor, the results are available via members.

A: Svd() used to be an extension method in v2, which unfortunately is only available if you include the right namespace. In your case, adding the following line should do the trick:
using MathNet.Numerics.LinearAlgebra.Double;

This is one of the areas that have been greatly simplified in the upcoming v3 release, where this is a proper method. I suggest you have a look at one of the recent v3 packages (as of writing this e.g. the v3.0.0-alpha7).


text:
Q: How do I save a form in double nested form? I have three models: Event, Workout, and Round.
A person can create a event, that includes a workout, and configure number of sets and weights through round.
I am currently using cocoon gem to create a nested form. I am able to use the form and save Event and Workout, however, Round is not being saved.
class Event < ActiveRecord::Base
  has_many :workouts, dependent: :destroy
  has_many :rounds, :through => :workouts
  belongs_to :user
  accepts_nested_attributes_for :workouts, :allow_destroy => true
end

class Workout < ActiveRecord::Base
  belongs_to :event
  has_many :rounds, dependent: :destroy
  accepts_nested_attributes_for :rounds, :allow_destroy => true
end

class Round < ActiveRecord::Base
  belongs_to :workout
  belongs_to :event
end

I currently have my routes set like this.
Rails.application.routes.draw do
  devise_for :users
  root 'static_pages#index'
  resources :events do
    resources :workouts do
        resources :rounds
      end
  end

In my controller, this is how I have my new methods.
  New Method for Event
  def new
    @event = current_user.events.new
  end

  New Method for Workout
  def new
    @workout = Workout.new
  end

  New Method for Round
  def new
    @round = Round.new
  end

I currently have the form under Events' view folder. Under show.html.erb of Events view file, I am trying to display Rounds as well by
<% @workout.rounds.each do |round| %>
  <%= round.weight %>
<% end %>

But I am getting undefined method for rounds. Is it not possible to display round in Event view?
Thanks for the help!

Edit 1:
Here is my nested forms.
At the top, I have form for Event.
<%= simple_form_for @event do |f| %>
  <%= f.input :title %>

Work Outs

        <%= f.simple_fields_for :workouts do |workout| %>
          <%= render 'workout_fields', f: workout %>
        <% end %>

          <%= link_to_add_association 'add workout', f, :workouts %>

        <%= f.label :start_time %>

        <%= f.datetime_select :start_time %>

        <%= f.label :end_time %>

        <%= f.datetime_select :end_time %>

        <%= f.label :description %>

        <%= f.text_area :description %>

        <%= f.submit "Create new Workout" %>

  <% end %>
<% end %>

</form>

Then there is a form for Workout

  <%= f.input :name %>

    <%= f.simple_fields_for :rounds, :wrapper => 'inline' do |round| %>
      <%= render 'round_fields', f: round %>
    <% end %>

        <%= link_to_add_association 'add round', f, :rounds, :render_option => { :wrapper => 'inline' } %>

  <%= link_to_remove_association "remove workout", f %>

And finally, I have the form for Round

        <% index = 0 %>
        <%= f.simple_fields_for :rounds do |round| %>
            <%= render 'set_fields', {f: round, index: index} %>
            <% index = index + 1 %>
        <% end %>

      Previous Weight
      <%= f.input_field :weight %>
      <%= f.input_field :repetition %>
      <%= link_to_remove_association "remove rounds", f %>

I am able to create round on rails console and save them. But when I use the form on the web, I cannot save them.

EDIT 2
This is currently how I have the event_params and workout_params set-up.
def event_params
  params.fetch(:event, {}).permit(:title, :description, :start_time, :end_time, :workouts_attributes => [:id, :name, :category, :_destroy])
end

Then the workout_params:
def workout_params
  params.require(:workout).permit(:name, :category, :rounds_attributes => [:id, :weight, :set, :repetition, :_destroy])
end

I am confused why the form would save Event and Workout. But Round always returns an empty array.

A: Finally solved it!
I had to have an association in the params as well. Double nested association.
def event_params
  params.fetch(:event, {}).permit(:title, :description, :start_time, :end_time, :workouts_attributes => [:id, :name, :category, :_destroy])
end

For my event_params, I only had :workouts_attributes. I thought having :rounds_attributes in workout_params would be okay. But I needed to have rounds_attributes in event_params as well.
Fixing it like below fixed the issue.
def event_params
  params.fetch(:event, {}).permit(:title, :description, :start_time, :end_time, :workouts_attributes => [:id, :name, :category, :_destroy, :rounds_attributes => [:id, :weight, :set, :repetition, :_destroy]])
end

A: you already have rounds attribute in Events model (has_many :rounds, :through => :workouts), why not use it?
<% @event.rounds.each do |round|
  <%= round.weight %>
<% end %>


text:
Q: mobx-state-tree error while converting to anonymousModel What should happen - succesfully create RootStore from defaultSnapshot and reset it when needed, successful backcuping in localStorage.
What happens - getting an error while trying to apply a snapshot, when attempting to open page, just by running code even without interacting with it.
When checking types manually I do not see problems with type mistakes, so can not understand why it throws error.
Codesandox live minimum code
Error
Error: [mobx-state-tree] Error while converting `{"token":"","myInnerInfo":{"login":"","type":""},"myDisplayInfo":{"login":"","type":""},"loginInfo":{"login":"","type":""},"loginList":[],"loading":false,"logined":false}` to `AnonymousModel`:

    at path "/myInnerInfo/login" value `""` is not assignable to type: `AnonymousModel` (Value is not a plain object).
    at path "/myInnerInfo/type" value `""` is not assignable to type: `AnonymousModel` (Value is not a plain object).
    at path "/myDisplayInfo/login" value `""` is not assignable to type: `AnonymousModel` (Value is not a plain object).
    at path "/myDisplayInfo/type" value `""` is not assignable to type: `AnonymousModel` (Value is not a plain object).
    at path "/loginInfo/login" value `""` is not assignable to type: `AnonymousModel` (Value is not a plain object).
    at path "/loginInfo/type" value `""` is not assignable to type: `AnonymousModel` (Value is not a plain object).

File structure

store.js (imported in index.js)
import { types, flow, onSnapshot, applySnapshot } from 'mobx-state-tree';
import { values } from 'mobx';
import axios from 'axios';

const defaultSnapshot = {
  token: '',
  myInnerInfo: { login: '', type: '' },
  myDisplayInfo: { login: '', type: '' },
  loginInfo: { login: '', type: '' },
  loginList: [],
  loading: false,
  logined: false,
}

const User = types
  .model({
    login: '',
    type: '',
  }).actions(self => ({
    setUserInfo({ login, type }) {
      self.login = login;
      self.type = type;
    }
  }))

const RootStore = types
  .model({
    token: '',
    myInnerInfo: types.map(User),
    myDisplayInfo: types.map(User),
    loginInfo: types.map(User),
    loginList: types.array(types.string),
    loading: false,
    logined: false,
  }).views(self => ({
    get loginListLength() {
      return values(self.loginList).length;
    },
  })).actions(self => ({
    // setToken (token) {
    //   self.token = token;
    // },
    // setMyInnerInfo (userInfo) {
    //   self.myInnerInfo.setUserInfo(userInfo);
    // },
    // setMyDisplayInfo (userInfo) {
    //   self.myDisplayInfo.setUserInfo(userInfo);
    // },
    // setLoginInfo (userInfo) {
    //   self.loginInfo.setUserInfo(userInfo);
    // },
    // setLoginList (loginList) {
    //   self.loginList = loginList;
    // },
    // setLoading (loading) {
    //   self.loading = loading;
    // },
    // setLogined (logined) {
    //   self.logined = logined;
    // },
    // reset() {
    //   self.token = '';
    //   self.myInnerInfo = User.create({});
    //   self.myDisplayInfo = User.create({});
    //   self.loginInfo = User.create({});
    //   self.loginList = [];
    //   self.loading = false;
    //   self.logined = false;
    // },
    register: flow(function* register(login, password) {
      self.loading = true;
      try {
        const res = yield axios({
          method: 'POST',
          url: `${process.env.REACT_APP_HOST}/users/register`,
          data: { login, password },
        });
        alert('Registered');
        self.loading=false;
      } catch (e) {
        console.error(e);
        alert(`Error registering! Please retry!`);
        resetStore();
      }
    }),
    login: flow(function* login(login, password) {
      self.loading = true;
      try {
        const res = yield axios({
          method: 'POST',
          url: `${process.env.REACT_APP_HOST}/users/login`,
          data: { login, password },
        });
        self.token = res.data.token;
        self.myInnerInfo.setUserInfo(res.data.user);
        self.myDisplayInfo.setUserInfo({ login: '', type: '' });
        self.loginInfo.setUserInfo({ login: '', type: '' });
        self.loginList = [];
        alert('Logined');
        self.logined = true;
        self.loading=false;
      } catch (e) {
        console.error(e);
        alert(`Error logining! Please retry!`);
        resetStore();
      }
    }),
    unlogin() {
      self.loading = true;
      self.logined = false;
      self.token = '';
      self.myInnerInfo.setUserInfo({ login: '', type: '' });
      self.myDisplayInfo.setUserInfo({ login: '', type: '' });
      self.loginInfo.setUserInfo({ login: '', type: '' });
      self.loginList = [];
      alert('Unlogined');
      self.loading=false;
    },
    getMyInfo: flow(function* getMyInfo() {
      self.loading = true;
      try {
        const res = yield axios({
          method: 'GET',
          url: `${process.env.REACT_APP_HOST}/users/my-info`,
          headers: {'Authorization': self.token ? `Bearer ${self.token}` : ''},
        });
        // self.token = res.data.token;
        // self.myInnerInfo.setUserInfo(res.data.user);
        self.myDisplayInfo.setUserInfo(res.data);
        // self.loginInfo.setUserInfo({});
        // self.loginList = [];
        alert('Loaded information');
        // self.logined = true;
        self.loading=false;
      } catch (e) {
        console.error(e);
        alert(`Error loading information! Please retry!`);
        resetStore();
      }
    }),
    getLoginList: flow(function* getLoginList() {
      self.loading = true;
      try {
        const res = yield axios({
          method: 'GET',
          url: `${process.env.REACT_APP_HOST}/users/list-logins`,
          headers: {'Authorization': self.token ? `Bearer ${self.token}` : ''},
        });
        // self.token = res.data.token;
        // self.myInnerInfo.setUserInfo(res.data.user);
        // self.myDisplayInfo.setUserInfo(res.data);
        // self.loginInfo.setUserInfo({});
        self.loginList = res;
        alert('Loaded list');
        // self.logined = true;
        self.loading=false;
      } catch (e) {
        console.error(e);
        alert(`Error loading list! Please retry!`);
        resetStore();
      }
    }),
    getUserInfo: flow(function* getUserInfo(login) {
      self.loading = true;
      try {
        const res = yield axios({
          method: 'GET',
          url: `${process.env.REACT_APP_HOST}/users/my-info/${login}`,
          headers: {'Authorization': self.token ? `Bearer ${self.token}` : ''},
        });
        // self.token = res.data.token;
        // self.myInnerInfo.setUserInfo(res.data.user);
        // self.myDisplayInfo.setUserInfo(res.data);
        self.loginInfo.setUserInfo(res.data);
        // self.loginList = [];
        alert('Loaded information');
        // self.logined = true;
        self.loading=false;
      } catch (e) {
        console.error(e);
        alert(`Error loading information! Please retry!`);
        resetStore();
      }
    }),
  }));

const store = RootStore.create();

if(!(localStorage[process.env.REACT_APP_LOCALSTORAGE_KEY] && JSON.parse(localStorage[process.env.REACT_APP_LOCALSTORAGE_KEY]))) {
  localStorage[process.env.REACT_APP_LOCALSTORAGE_KEY] = JSON.stringify(defaultSnapshot);
}
applySnapshot(store, JSON.parse(localStorage[process.env.REACT_APP_LOCALSTORAGE_KEY]));

onSnapshot(store, snapshot => {
  localStorage[process.env.REACT_APP_LOCALSTORAGE_KEY] = JSON.stringify(snapshot);
  console.info(snapshot);
});

export default store;
export function resetStore() {
  localStorage[process.env.REACT_APP_LOCALSTORAGE_KEY] = JSON.stringify(defaultSnapshot);
  applySnapshot(store, JSON.parse(localStorage[process.env.REACT_APP_LOCALSTORAGE_KEY]));
}

package.json
{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.9",
    "@testing-library/react": "^11.2.3",
    "@testing-library/user-event": "^12.6.0",
    "axios": "^0.21.1",
    "mobx": "^6.0.4",
    "mobx-react": "^7.0.5",
    "mobx-state-tree": "^5.0.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.1",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

A: It appears that your defaultSnapshot does not match your defined model structure.
You define your default snapshot as follows:
const defaultSnapshot = {
  token: '',
  myInnerInfo: { login: '', type: '' },
  myDisplayInfo: { login: '', type: '' },
  loginInfo: { login: '', type: '' },
  loginList: [],
  loading: false,
  logined: false,
}

However, if you getSnapshot of your store after you create it with no arguments, you get:
{
 token: "",
 myInnerInfo: {},
 myDisplayInfo: {},
 loginInfo: {},
 loginList: [],
 loading: false,
 logined: false
}

Which would be a "default snapshot" in the sense that it is what happens when you create your store with no specific data.
Now this looks like the two should be compatible, except that you defined the three Info fields as maps. Maps of models look like this:
{
  "<id>": { <model snapshot> },
  …
}

Therefore, when loading your default snapshot, it causes an error because it tries to treat what you intended to be model data as map data - it thinks you have a collections of two Users with keys of login and type, and values of "", instead of objects compatible with User. For instance,
…
myInnerInfo: {
  login: { login: 'some user data', type:'' },
  type: { login: 'another user data', type:'' }
},
…

Would work, but doesn't seem like what you intended.
What you probably intended to do was make the Info fields directly of the User type, not a map of the User type, or perhaps an optional or the User type, since then you don't need to specify a User when creating the store. So perhaps your store model should look like this:
.model({
    token: '',
    myInnerInfo: types.optional(User, {}),
    myDisplayInfo: types.optional(User, {}),
    loginInfo: types.optional(User, {}),
    loginList: types.array(types.string),
    loading: false,
    logined: false,
  })

This structure is compatible with your default snapshot, and does not require values when creating the store.
Note that primitive values are automatically optional, but models are not (hence why the explicit optional call). An optional parameter has a default value, but will still exist. It just does not need to be explicitly defined at create time. Also, be sure to reset your localStorage when testing, or it may seem like it didn't work...


text:
Q: How to detect colision on c# forms I'm trying to detect collisions between a Player obj and any other PhisicalEntity in the objectList List in C#, but I can't get it to work. any thoughts?
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyGame
{
    public partial class GameCanvas : Form
    {
        public int BlockSize = 10;
        public Timer timer1;
        private static PlayerInputHandler UINPUT = new PlayerInputHandler();
        private static List<ObjContainer> playerList = new List<ObjContainer>();
        private static List<ObjContainer> objectList = new List<ObjContainer>();
        struct speedVec
        {
            public int NormalizeSpeedVector(int value)
            {
                return (value == 0) ? 0 : ((value < 0) ? -1 : 1);
            }
        }
        class PlayerInputHandler
        {
            public int x = 0;
            public int y = 0;
            public PlayerInputHandler()
            {
            }
            public void SenceUp()
            {
                this.y = (new speedVec()).NormalizeSpeedVector(this.y - 1);
            }
            public void SenceDown()
            {
                this.y = (new speedVec()).NormalizeSpeedVector(this.y + 1);
            }
            public void SenceRight()
            {
                this.x = (new speedVec()).NormalizeSpeedVector(this.x + 1);
            }
            public void SenceLeft()
            {
                this.x = (new speedVec()).NormalizeSpeedVector(this.x - 1);
            }
            public void SenceNull()
            {
                this.x = 0;
                this.y = 0;
            }
        }
        class ObjContainer
        {
            private int OID;
            public PhisicalEntity OBJ;
            public ObjContainer(int OID, PhisicalEntity OBJ)
            {
                this.OID = OID;
                this.OBJ = OBJ;
            }
        }
        abstract class PhisicalEntity
        {
            public static PictureBox OnScreenRepresentation;
            public abstract void Step();

            public int GetX()
            {
                return OnScreenRepresentation.Location.X;
            }
            public int GetY()
            {
                return OnScreenRepresentation.Location.Y;
            }
        }
        class Player : PhisicalEntity
        {
            public int x;
            public int y;
            public int xs;
            public int ys;
            public int health;
            public int gravity;
            public int friction;
            public Player(int x, int y, int xs, int ys, int health, int gravity, int friction, PictureBox repr)
            {
                this.x = x;
                this.y = y;
                this.xs = xs;
                this.ys = ys;
                this.health = health;
                this.gravity = gravity;
                this.friction = friction;
                OnScreenRepresentation = repr;
            }
            override public void Step()
            {
                if (CheckColision(this.x, this.y, this.xs, this.ys))
                {
                    this.xs = UINPUT.x;
                    this.ys = UINPUT.y;
                    UINPUT.SenceNull();
                    this.x += this.xs * 3;
                    this.y += this.ys * 3;
                    OnScreenRepresentation.Location = new Point(this.x, this.y);
                }
            }
            public bool isBetwen(int value, int min, int max)
            {
                return (value < max) ? ((value > min) ? true : false) : false;
            }
            private bool CheckColision(int x, int y, int xs, int ys)
            {
                foreach (ObjContainer phisicalEmu in objectList)
                {
                    PhisicalEntity obj = phisicalEmu.OBJ;
                    int phiX = obj.GetX();
                    int phiY = obj.GetY();
                    if (isBetwen(x + xs, phiX + 10, phiX) || isBetwen(x + 10 + xs, phiX + 10, phiX))
                    {
                        return true;
                    }
                    if (isBetwen(y + ys, phiY + 10, phiY) || isBetwen(y + 10 + ys, phiY + 10, phiY))
                    {
                        return true;
                    }
                }
                return false;
            }
        }
        class Structural : PhisicalEntity
        {
            public int x;
            public int y;
            public int xs;
            public int ys;
            public int health;
            public int gravity;
            public int friction;
            public PictureBox OnScreenRepresentation;
            public Structural(int x, int y, int xs, int ys, int health, int gravity, int friction, PictureBox repr)
            {
                this.x = x;
                this.y = y;
                this.xs = xs;
                this.ys = ys;
                this.health = health;
                this.gravity = gravity;
                this.friction = friction;
                this.OnScreenRepresentation = repr;
            }
            override public void Step()
            {
                this.xs = UINPUT.x;
                this.ys = UINPUT.y;
                UINPUT.SenceNull();
                this.x += this.xs * 3;
                this.y += this.ys * 3;
                OnScreenRepresentation.Location = new Point(this.x, this.y);
            }
        }
        public void InitTimer()
        {
            Timer timer = new Timer();
            timer.Tick += new EventHandler(Step);
            timer.Interval = 20;
            timer.Start();
        }
        public void Step(object sender, EventArgs e)
        {
            foreach (ObjContainer obj in playerList)
            {
                obj.OBJ.Step();
            }
        }
        public GameCanvas()
        {
            InitializeComponent();
        }
        private void GC_onLoad(object sender, EventArgs e)
        {
            RegisterNewPlayer(new Player(0, 0, 0, 0, 100, 3, 0, o_934), (new Random()).Next(((new Random()).Next())));
            RegisterNewStruc(new Structural(0, 0, 0, 0, 0, 0, 0, o_980), (new Random()).Next(((new Random()).Next())));
            InitTimer();
        }
        private void RegisterNewPlayer(Player obj, int KeyGen)
        {
            int num = ((new DateTime()).Year + (new DateTime()).Month + (new DateTime()).Day + (new DateTime()).Hour + (new DateTime()).Second + (new DateTime()).Millisecond) * KeyGen;
            ObjContainer OnRegst = new ObjContainer(num, obj);
            playerList.Add(OnRegst);
        }
        private void RegisterNewStruc(Structural obj, int KeyGen)
        {
            int num = ((new DateTime()).Year + (new DateTime()).Month + (new DateTime()).Day + (new DateTime()).Hour + (new DateTime()).Second + (new DateTime()).Millisecond) * KeyGen;
            ObjContainer OnRegst = new ObjContainer(num, obj);
            objectList.Add(OnRegst);
        }
        private void ProccessKeyEvents(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Up)
            {
                UINPUT.SenceUp();
            }
            if (e.KeyData == Keys.Down)
            {
                UINPUT.SenceDown();
            }
            if (e.KeyData == Keys.Left)
            {
                UINPUT.SenceLeft();
            }
            if (e.KeyData == Keys.Right)
            {
                UINPUT.SenceRight();
            }
        }
    }
}

A: Try looking at the methods for Rectangle
https://learn.microsoft.com/en-us/dotnet/api/system.drawing.rectangle?view=netcore-3.1
Also consider having a debug mode and when running in debug mode you can draw debug items to display boundaries, collisions, to aid development.

A: An example fix using the code you provided with minor updates.
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Drawing;
    using System.Linq;
    using System.Media;
    using System.Security.Cryptography;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    namespace MyGame
    {
        public partial class GameCanvas : Form
        {
            public int BlockSize = 10;
            public Timer timer1;
            private static PlayerInputHandler UINPUT = new PlayerInputHandler();
            private static List<ObjContainer> playerList = new List<ObjContainer>();
            private static List<ObjContainer> objectList = new List<ObjContainer>();
            struct speedVec
            {
                public int NormalizeSpeedVector(int value)
                {
                    return (value == 0) ? 0 : ((value < 0) ? -1 : 1);
                }
            }
            class PlayerInputHandler
            {
                public int x = 0;
                public int y = 0;
                public PlayerInputHandler()
                {
                }
                public void SenceUp()
                {
                    this.y = (new speedVec()).NormalizeSpeedVector(this.y - 1);
                }
                public void SenceDown()
                {
                    this.y = (new speedVec()).NormalizeSpeedVector(this.y + 1);
                }
                public void SenceRight()
                {
                    this.x = (new speedVec()).NormalizeSpeedVector(this.x + 1);
                }
                public void SenceLeft()
                {
                    this.x = (new speedVec()).NormalizeSpeedVector(this.x - 1);
                }
                public void SenceNull()
                {
                    this.x = 0;
                    this.y = 0;
                }
            }
            class ObjContainer
            {
                private int OID;
                public PhisicalEntity OBJ;
                public ObjContainer(int OID, PhisicalEntity OBJ)
                {
                    this.OID = OID;
                    this.OBJ = OBJ;
                }
            }
            abstract class PhisicalEntity
            {
                protected PictureBox OnScreenRepresentation;
                public abstract void Step();

                public int GetX()
                {
                    return OnScreenRepresentation.Location.X;
                }
                public int GetY()
                {
                    return OnScreenRepresentation.Location.Y;
                }

                public int GetHeight()
                {
                    return OnScreenRepresentation.Height;
                }

                public int GetWidth()
                {
                    return OnScreenRepresentation.Width;
                }
            }
            class Player : PhisicalEntity
            {
                //public int x;
                //public int y;
                //public int xs;
                //public int ys;
                public int health;
                public int gravity;
                public int friction;
                public Player(int health, int gravity, int friction, PictureBox repr)
                {
                    //this.x = x;
                    //this.y = y;
                    //this.xs = xs;
                    //this.ys = ys;
                    this.health = health;
                    this.gravity = gravity;
                    this.friction = friction;
                    OnScreenRepresentation = repr;
                }
                override public void Step()
                {
                    if (CheckColision(this.GetX() + UINPUT.x, this.GetY() + UINPUT.y))
                    {
                        //this.xs = UINPUT.x;
                        //this.ys = UINPUT.y;
                        //UINPUT.SenceNull();
                        //this.x += this.xs * 3;
                        //this.y += this.ys * 3;
                        //this.x += this.xs;
                        //this.y += this.ys;
                        OnScreenRepresentation.Left += UINPUT.x;
                        OnScreenRepresentation.Top += UINPUT.y;
                    }
                    UINPUT.SenceNull();
                    //else
                    //{
                    //    UINPUT.x = this.x;
                    //    UINPUT.y = this.y;
                    //}
                }
                public bool isBetwen(int value, int min, int max)
                {
                    return (value < max) ? ((value > min) ? true : false) : false;
                }

                private bool CheckColision(int x, int y)
                {
                    var height = this.GetHeight();
                    var width = this.GetWidth();
                    var coordinates = new List<int[]>() { new[] {x,y }, new[] { x, y+height }, new[] { x+width, y }, new[] { x+width, y+height } };

                    foreach (ObjContainer phisicalEmu in objectList)
                    {
                        PhisicalEntity obj = phisicalEmu.OBJ;
                        int phiX = obj.GetX();
                        int phiY = obj.GetY();
                        var phiHeight = obj.GetHeight();
                        var phiWidth = obj.GetWidth();

                        var phiCoordinates = new List<int[]>() { new[] { phiX, phiY }, new[] { phiX, phiY + phiHeight }, new[] { phiX + phiWidth, phiY }, new[] { phiX + phiWidth, phiY + phiHeight } };
                        int maxPhiX = phiX + phiWidth;
                        int maxPhiY = phiY + phiHeight;

                        //Check if edge points in phi are directly part of the player object
                        foreach(var coordinate in coordinates)
                        {
                            if (isBetwen(coordinate[0], phiX, maxPhiX) && isBetwen(coordinate[1], phiY, maxPhiY))
                            {
                                return false;//Collision
                            }
                        }

                        int maxX = x + width;
                        int maxY = y + height;

                        //Check if edge points in the player object are directly part of phi
                        foreach (var coordinate in phiCoordinates)
                        {
                            if (isBetwen(coordinate[0], x, maxX) && isBetwen(coordinate[1], y, maxY))
                            {
                                return false;//Collision
                            }
                        }

                    }
                    return true;
                }
            }
            class Structural : PhisicalEntity
            {
                //public int x;
                //public int y;
                //public int xs;
                //public int ys;
                public int health;
                public int gravity;
                public int friction;
                //public PictureBox OnScreenRepresentation;
                public Structural(int health, int gravity, int friction, PictureBox repr)
                {
                    //this.x = x;
                    //this.y = y;
                    //this.xs = xs;
                    //this.ys = ys;
                    this.health = health;
                    this.gravity = gravity;
                    this.friction = friction;
                    this.OnScreenRepresentation = repr;
                }
                override public void Step()
                {
                    //this.xs = UINPUT.x;
                    //this.ys = UINPUT.y;
                    //UINPUT.SenceNull();
                    //this.x += this.xs * 3;
                    //this.y += this.ys * 3;
                    //OnScreenRepresentation.Location = new Point(this.x, this.y);
                    OnScreenRepresentation.Top += UINPUT.y;
                    OnScreenRepresentation.Left += UINPUT.x;
                    UINPUT.SenceNull();
                }
            }
            public void InitTimer()
            {
                Timer timer = new Timer();
                timer.Tick += new EventHandler(Step);
                timer.Interval = 20;
                timer.Start();
            }
            public void Step(object sender, EventArgs e)
            {
                foreach (ObjContainer obj in playerList)
                {
                    obj.OBJ.Step();
                }
            }
            public GameCanvas()
            {
                InitializeComponent();
            }

            private void GC_onLoad(object sender, EventArgs e)
            {

                RegisterNewPlayer(new Player(100, 3, 0, o_934), (new Random()).Next(((new Random()).Next())));
                RegisterNewStruc(new Structural(0, 0, 0, o_980), (new Random()).Next(((new Random()).Next())));
                InitTimer();
            }
            private void RegisterNewPlayer(Player obj, int KeyGen)
            {
                int num = ((new DateTime()).Year + (new DateTime()).Month + (new DateTime()).Day + (new DateTime()).Hour + (new DateTime()).Second + (new DateTime()).Millisecond) * KeyGen;
                ObjContainer OnRegst = new ObjContainer(num, obj);
                playerList.Add(OnRegst);
            }
            private void RegisterNewStruc(Structural obj, int KeyGen)
            {
                int num = ((new DateTime()).Year + (new DateTime()).Month + (new DateTime()).Day + (new DateTime()).Hour + (new DateTime()).Second + (new DateTime()).Millisecond) * KeyGen;
                ObjContainer OnRegst = new ObjContainer(num, obj);
                objectList.Add(OnRegst);
            }
            private void ProccessKeyEvents(object sender, KeyEventArgs e)
            {
                if (e.KeyData == Keys.Up)
                {
                    UINPUT.SenceUp();
                }
                if (e.KeyData == Keys.Down)
                {
                    UINPUT.SenceDown();
                }
                if (e.KeyData == Keys.Left)
                {
                    UINPUT.SenceLeft();
                }
                if (e.KeyData == Keys.Right)
                {
                    UINPUT.SenceRight();
                }
            }
        }
    }


text:
Q: Undo functionality in an MVC design I have a C++ application designed according to a classic Model-View-Controller pattern. The model is modified through a controller interface by an external source by means of a Command pattern. The commands are represented by an Action object (and its derivatives).
Now I want to be able to undo the modifications, but my problem is that I have no getters in my controller, only setters. This seems quite logical, since there's no reason someone should be able to get info about the model through the controller. Thus, I can't have my Action objects store the state of the Model, since they have no access to it.
How would one solve this? I'd like to keep my application as extendable as possible and I'm not quite sure which option is the best for that. The methods I though up so far are:

*

*Putting getter methods in the controller. This seems to go against the MVC pattern.

*Giving the Action a pointer to a View. The Action could then either:

*

*Use individual getters to get the state of specific elements of the model to be modified.

*Use a Memento method implemented by the Viewer.

Maybe there's an even better way to do this? Right now, to be the best option seems to be 2, suboption 1 (with suboption 2, I'd quite possible store a lot more state than necessary to undo one action).
Note: I know there's other questions on how to implement an undo action. However, the only answers I found gave suggestions to use a Command or Memento pattern. I know this is most probably the way to go. What I'm asking for is how to integrate this as cleanly & extendable as possible in an MVC design.
[Edit] What I don't like about the Memento pattern is that it forces me to store a complete state. Let's say my model is a 1000x1000 matrix and my Command is ChangeOneValueAtLocation. To be able to undo its changes, the ChangeOneValueAtLocation object only needs to store the previous value of the location it's changing, but that doesn't seem possible with Memento. The larger my model, the biggest this problem becomes.
[Edit 2] Another problem I have with Memento in the specific case of this application: for every method a Command object can execute on the Model, there's a method that does exact opposite (or can easily be coaxed to do so). This is why I would find it a waste to have to store the whole state, there should be no need to, reverting a single Command is very straightforward, the only problem is getting the data to be able to do it.
Also, I don't need to be able to undo a specific Command, only the topmost one on my history stack.

A: I'd really recommend building the undo tree into your Controller
Building it into the model could run you into trouble:

*

*the 'model' is usually fragmented per view (each view has it's own partial model)

*this will lead to non-atomic undo (undoing part of an operation due to the view not knowing what other things (models) would have to be undone etc)

The controller is the 'action dispatcher', so it'd have to say

*

*clone state (all models) snapshot

*add action to history with reference to snapshot

*run action

then undo would be

*

*pop action off history stack (optionally push to 'future' stack)

*restore snapshot

*display view

Also, make undo work with highlevel actions (see Composite Pattern or Command Pattern)

A: I also support the model layer containing undo support. There are quite a few ways to handle this in the model side. The first and most obvious is the models themselves remembering the history of the changes with "labels", but this is probably going to be difficult to synchronize for all your model classes.
One other option is to create a history manager that has a concept of a "transaction", which causes it to generate an undo point, and take a snapshot of your models, or start recording changes (for reduced memory usage), or record commands that cause model changes, etc.The models notify the manager on change, and finally you complete the transaction (or not, because the next start of transaction can be the end of the previous one). Once you add in the ability to rollback to a certain point, the work will be done. By making things slightly more complicated in this manager class, you can create an undo tree (like the one in emacs), so it is also quite a flexible way to approach it.
The above solution is not quite in the model layer, though. It is a support class that is driven by both the model and the controller. If you remove the transaction concept, then it is completely model-driven, but implementing the concept of an undo operation might be somewhat tricky. If you change it to act as a command proxy, it is the only entity used by your controllers, and is clearly a model. It is too rough a design at this point to choose one approach over another, but I am leaning towards the "transaction" model. It feels easy enough to implement.

A: Build the undo functionality in your model itself. Let you model keep a list of commands. Run the commands in the reverse order when your view passes an undo signal to the model.


text:
Q: $f\in\mathscr L([0,\infty),\lambda)$ with $\lim\limits_{x\to\infty}f(x)\neq 0$ Let $f\in \mathscr L([0,\infty),\lambda)$. Show, that there exists a continous function $f$ with $\lim\limits_{x\to\infty}f(x)\neq 0$.
I thought about a function $f_n=\chi_{B_{1/n^2}}$ and $f=\sum_{n=0}^\infty f_n(x)$. But is this acounterexample and is it continous?


text:
Q: webservices as datasource for crystal reports I am a crystal developer but new to webservices. i am using crystal reports 2008
I have following questions wrt web services as data source
1)we are currently using cxf web service with security policy SAML token how can it be enabled in crystal reports
2) can web service data source be mixed with relational data source in crystal reports as we are using more than one data base 3) how does web service datasource get cached,cleared and cleaned in crystal reports
questions on parameter
1) can we have parameter page backed up by a data source so that crystal takes parameters directly from that 2) a scripting or programming layer that can be used in crystal to pass parameters.
how can we connect to live stream data of web services to crystal reports how to webservice a datasource
Any help is appreciated.
Thank you

A: Instead of having crystal reports handle the connecting to the web service, and and also the merging that data with other relational datasources, do that accessing and merging of data in a business logic layer in code to produce a hierarchy of objects.  If you are reporting on this data, then it is likely that such a business logic layer already exists for some application consuming it.  The object hierarchy that is produced by the business logic layer can usually be serialized to XML very easily.
This XML can be used to design the report offline.


text:
Q: Alfresco: Email document link to multiple people and groups I have created a custom workflow that is to be started from a document, which is designed to run an email script to send the recipients a link to the document in share. Users can send the file to multiple people, groups, or both. The workflow immediately ends after the workflow is started, which is achieved using the timer event (Activiti prevents you from starting and ending a workflow without any tasks).
Screenshot

This works with the email template (only sends it to the DOCUMENT_TEST group, see code below), but I have some issues:
Recipients
I need to convert the Select People and Select Group elements into usable email addresses for the mail.parameters.to_many method. I understand that to send to the shown recipients, I'd do the following:
mail.parameters.to_many = ['ageorge', 'GROUP_DOCUMENT_TEST'];

How would I go about looping through the two selection elements and compiling a usable array of recipients? Since there are no tasks, how would I obtain this data in the execution? I initially thought they'd be execution variables, but my method didn't work (see .bpmn file).
mail.execute()
Currently, my mail code executes the following:
mail.execute(bpm_package.children[0].nodeRef);

This uses the first child node in the package, which happens to be the attached document. I think this is a sloppy work around, especially since bpm_package is so slow to execute (10-20 seconds on average). If I just wanted to reference the attached document's node, what would I use instead? (See config-custom)

BPMN File

<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/test">
  <process id="docWorkflow" isExecutable="true">
    <startEvent id="start" activiti:initiator="initiatorUserName" activiti:formKey="docWorkflow:start">
  <extensionElements>
   <activiti:executionListener event="start" class="org.alfresco.repo.workflow.activiti.listener.ScriptExecutionListener">
    <activiti:field name="script">
     <activiti:string><![CDATA[/*Script to set execution variables here*/]]></activiti:string>
    </activiti:field>
   </activiti:executionListener>
   <activiti:executionListener event="end" class="org.alfresco.repo.workflow.activiti.listener.ScriptExecutionListener">
    <activiti:field name="script">
     <activiti:string><![CDATA[var mail = actions.create("mail");
        mail.parameters.to_many = [execution.getVariable("docWorkflow_selectpeople").toString(), execution.getVariable("docWorkflow_selectgroup").toString()];
        mail.parameters.subject = "Alfresco: " + person.properties.firstName + " " + person.properties.lastName + " has sent you an item";
        mail.parameters.from = "alfresco-noReply@cdotech.com";
        mail.parameters.template = companyhome.childByNamePath("Data Dictionary/Email Templates/Send Document Notification/send_document_notification.html.ftl");
        mail.parameters.text = "The email template failed to load. Please contact the Alfresco administrator.";

        var document = bpm_package.children[0].nodeRef;

        // Execute mail package
        mail.execute(document);]]></activiti:string>
    </activiti:field>
   </activiti:executionListener>
  </extensionElements>
 </startEvent>
    <sequenceFlow id="sequenceFlow1" sourceRef="start" targetRef="intermediateEvent1"></sequenceFlow>
    <intermediateCatchEvent id="intermediateEvent1" name="Delay step">
      <timerEventDefinition>
        <timeDuration>PT1S</timeDuration>
      </timerEventDefinition>
    </intermediateCatchEvent>
    <endEvent id="end">
 </endEvent>
    <sequenceFlow id="sequenceFlow2" sourceRef="intermediateEvent1" targetRef="end"></sequenceFlow>
  </process>
</definitions>

Model

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model xmlns="http://www.alfresco.org/model/dictionary/1.0" name="docWorkflow:model">
    <imports>
        <import prefix="d" uri="http://www.alfresco.org/model/dictionary/1.0"/>
        <import prefix="cm" uri="http://www.alfresco.org/model/content/1.0"/>
        <import prefix="bpm" uri="http://www.alfresco.org/model/bpm/1.0"/>
    </imports>
    <namespaces>
        <namespace prefix="docWorkflow" uri="http://www.alfresco.org/model/dynamic-workflow/docWorkflow/1.0"/>
    </namespaces>
    <types>
        <type name="docWorkflow:start">
            <parent>bpm:startTask</parent>
   <mandatory-aspects>
                <aspect>docWorkflow:selectpeople</aspect>
                <aspect>docWorkflow:selectgroup</aspect>
            </mandatory-aspects>
        </type>
    </types>
 <aspects>
  <aspect name="docWorkflow:selectpeople">
   <associations>
    <association name="docWorkflow:selectpeople">
     <title>Select People</title>
     <source>
      <mandatory>false</mandatory>
      <many>true</many>
     </source>
     <target>
      <class>cm:person</class>
      <mandatory>false</mandatory>
      <many>true</many>
     </target>
    </association>
   </associations>
  </aspect>
  <aspect name="docWorkflow:selectgroup">
   <associations>
    <association name="docWorkflow:selectgroup">
     <title>Select Group(s)</title>
     <source>
      <mandatory>false</mandatory>
      <many>true</many>
     </source>
     <target>
      <class>cm:authorityContainer</class>
      <mandatory>false</mandatory>
      <many>true</many>
     </target>
    </association>
   </associations>
  </aspect>
 </aspects>
</model>

Config-Custom

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<alfresco-configuration>
    <config condition="docWorkflow:start" evaluator="task-type">
        <forms>
            <form>
                <field-visibility>
                    <show id="docWorkflow:selectpeople"/>
                    <show id="docWorkflow:selectgroup"/>
                    <show id="packageItems"/>
                    <show id="transitions"/>
                </field-visibility>
                <appearance>
                    <set appearance="title" label-id="Recipients" id="info"/>
                    <field set="info" label-id="Select People" id="docWorkflow:selectpeople"/>
     <field set="info" label-id="Select Group(s)" id="docWorkflow:selectgroup"/>
                    <set appearance="title" label-id="Document(s)" id="documents"/>
                    <field set="documents" label-id="Files" id="packageItems"/>
                    <set id="response"/>
                    <field set="response" id="transitions"/>
                </appearance>
            </form>
        </forms>
    </config>
    <config condition="activiti$docWorkflow" evaluator="string-compare">
        <forms>
            <form>
                <field-visibility>
                    <show id="docWorkflow:selectpeople"/>
                    <show id="docWorkflow:selectgroup"/>
                    <show id="packageItems"/>
                    <show id="transitions"/>
                </field-visibility>
                <appearance>
                    <set appearance="title" label-id="Recipients" id="info"/>
                    <field set="info" label-id="Select People" id="docWorkflow:selectpeople"/>
     <field set="info" label-id="Select Group(s)" id="docWorkflow:selectgroup"/>
                    <set appearance="title" label-id="Document(s)" id="documents"/>
                    <field set="documents" label-id="Files" id="packageItems"/>
                    <set id="response"/>
                    <field set="response" id="transitions"/>
                </appearance>
            </form>
        </forms>
    </config>
</alfresco-configuration>

Email template

                                                      ${person.properties.firstName} <#if person.properties.lastName?exists> ${person.properties.lastName}</#if> has sent you a new content item, ${document.name}, in the ${document.siteShortName!""} site

                                                      ${date?datetime?string.full}

Hi,

${person.properties.firstName}
                                             <#if person.properties.lastName?exists> ${person.properties.lastName}</#if>
                                             has sent you a new content item, ${document.name}, in the ${document.siteShortName!""} site.

Click this link to view the item:

${document.shareUrl}

Sincerely,

                                             Alfresco


text:
Q: How can I upload my python trading bot to the internet for auto-trading? I have written a python code that I can run it on my computer. It gets stock data from a website by GET request. Then it does some calculations on upon these online data and decides to send a buy/sell request to my broker's account.
All of these works fine on my computer, but I like to upload my code on a web server to preventing electricity/internet disconnection. I think I should upload my code on a virtual server, but this is all the thing I know and I don't have more experience or knowledge about it. I don't know if it is what I need, how can I do that?
In my experience of making some simple web pages, we should put our main code inside the public.html file? So should I buy a web host and wrap my python code inside a .html file?
Sorry if they are simple/stupid questions but I couldn't find any answer or guidence for doung what I want, so I asked here!

A: With the info you provide I can't really be sure how your script is ran.
I presume you run it by shell in that case a simple vps should suffice.
No need to mess around with a webserver.
Maybe look at Digital Ocean. They are a market leader and the simple $5 option probably enough for your purpose.
When you set it up you can connect to it with ssh (preferably with a ssh key because you are working with financial data) and setup your python script as if it were your own computer.
Ps. I don't work for digital ocean or get money from the link. It is just an example, any vps will work.


text:
Q: Get list of tags from SpaCy Does SpaCy provide a way to get a list of POS tags? For example, I can write the following code:
test1 = "The brown fox is pretty."
doc1 = nlp(test1)
for word in doc1:
    print(word.tag_)

This code generates the following output:
DT
JJ
NN
VBZ
JJ
.

I would like to get a list like this:
["DT","JJ","NN","VBZ","JJ","."]

I can obviously write code to create the list, but that seems inefficient to do every time. I expected that SpaCy provides an easy way to get the list, but so far I have not been able to find an example or figure it out. Anyone know how to do this?

A: You can try adding extraction of tag list as a part of the pipeline and create extensions
at Doc level.
I don't know if that would be more efficient in terms of performance but you will be able to access the tags using that extension.
Perhaps something like this,
Code:
import spacy
nlp = spacy.load("en_core_web_md")
def tag_list_component(doc):
    tags = [token.tag_ for token in doc]
    doc.set_extension('tags_', default=False, force=True)
    doc._.tags_ = tags

    return doc

if(nlp.has_pipe("tag_list_pipe")):
    nlp.remove_pipe("tag_list_pipe")
nlp.add_pipe(tag_list_component, name="tag_list_pipe")

doc = nlp("This is sparta!")
print(doc._.tags_)
doc = nlp("Brown fox is pretty!")
print(doc._.tags_)

Output:
['DT', 'VBZ', 'NNP', '.']
['NNP', 'NN', 'VBZ', 'JJ', '.']


text:
Q: Why is this step required in the proof of sum of first $n$ odd numbers using the Well Ordering Principle? I came across this question while doing $\text{6.042J}$ from MITOCW. I have a doubt in the part c, namely, why do we need to manipulate the formula in that way?

Here is my solution so far to the other parts:
Let us assume $\text{C}$ is the set of counter-examples for which the formula isn't true.
$\text{(a)}$ There must be a least $m$ as $n \in \mathbb{Z^+}$, which is the set of positive integers (given, $n > 0$). So, by the Well-Ordering Principle, there must exist a least $m$
$\text{(b)}$ Clearly, $m \neq 1$ as for $n = 1$, we have, $\sum_{i=0}^{0}(2i+1)=2(0)+1=1=n^2$, so the formula holds true. So, clearly, $m \geq 2$
Now, here is my doubt. For part $\text{(c)}$, what I think they have done, is replaced $i$ by $i-1$. Am I right here?
Because I see that replacing $i$ by $i-1$, we have to consequently change the lower limit to $i=1$ and the upper limit to $n$, so the formula would look like,
$$\sum_{i=1}^{n}(2(i-1)+1)=n^2$$
Is this correct? And then as $m$ is the least element such that the formula doesn't hold, the formula must hold for $m-1\geq 1 \text{from part (b)}$, and then we replace $n$ by $m-1$ in the above formula to obtain $(2.10)$. Is this reasoning okay? But what I still am confused by is why they had to change the limits of the sum to show this? Or is it just an exercise in changing the limits?

A: It's not quite as simple as replacing a variable with another. Note that, taking $n := m-1$ in $(2.9)$,
$$\sum_{i=0}^{(m-1)-1} (2i+1) = (m-1)^2$$
is effectively our starting point. (We know this much is true since $m$ is presumed our "first failure", or rather $m-1$ is our last-ensured success.)
We can reindex by letting $k := i+1$. Then:

*

*The lower bound $i=0$ gives $k=1$

*The upper bound $i=m-2$ gives $k=m-1$

*The $i$ in the summand is replaced in the obvious way

We get
$$\sum_{i=0}^{(m-1)-1} (2i+1) = \sum_{k=1}^{m-1} (2(k-1)+1) = (m-1)^2$$
In short, nothing really deep going on here (other than the validity of the claim), just algebra.


text:
Q: Problema al instalar angular-cesium en Angular 6 Estoy tratando de instalar Angular-cesium en un proyecto generado con Ngx-rocket y obtengo este error:

Intente generar el proyecto con ng-cli y el mismo error.

A: Intenta colocar lo siguiente en tu tsconfig.json
"noImplicitAny":false

Te recomiendo dar una mirada a la documentacion


text:
Q: Return cumulated string from this recursive loop I'm trying to return a final string which is concatenation of each nested object's string values. I'm not able to get it right.
I think I have some idea as whats happening; the issue is that return is called every time without checking for condition, as a result when the function calls itself, the variable _text becomes empty again. What condition should I check for return statement.
The input is just an example, the array contain any number of items and each item can be a string, object or array. Please help. Thanks for your time
var input = ["\n\t  This function constructs a named and protected temporal collection \n\t  in the schema database with the specified system and valid axes.  \n\t  This function assumes that the system and valid axes already exist.  \n\t  The temporal collection is stored in the Security database.  \n\t  ", {
    "p": {
        "_children": ["A TEMPORAL-DUPCOLLECTION exception is thrown if the collection \n          already exists.  "]
    }
}, {
    "p": {
        "_children": ["\n  For details on how to create a collection, see  \n ", {
            "a": {
                "_attributes": {
                    "href": "#display.xqy?fname=http://pubs/6.0doc/xml/temporal/temporal-quick-start.xml%2366392"
                },
                "_children": ["Create a Temporal Collection"]
            }
        }, " in the ", {
            "em": {
                "_children": ["Temporal Developer's Guide"]
            }
        }]
    }
}];

function cleanupString(str) {
    return str.replace(/(\n|\t|\s+)/g, " ").trim();
}

function parseSummary(text, item) {
   // console.log('RAW-----:' + JSON.stringify(item))

    var _text =  text || '';

    if (typeof item === 'string') {
        _text = _text + item;
        _text = cleanupString(_text);
    }
        // if item is object
    else if (item.constructor == Object) {
        for (var key in item) {
           return parseSummary(_text, item[key]);
        }
    } // if item is array
    else if (item.constructor == Array) {
        item.map(function(k) {
            return parseSummary(_text, k);
        });
    }

        console.log('___TEXT____', _text);
        // I think the because of this return being called prematurely, the
        // variable _text is reset to empty, but not sure what condition I
        // should check  because there is no way of knowing if its reached end
        // of the object
        return _text;

}
var summary = parseSummary('', input);
console.log('SUMMARY:', summary); // comes out as empty

log
 ___TEXT____ This function constructs a named and protected temporal collection in the schema database with the specified system and valid axes. This function assumes that the system and valid axes already exist. The temporal collection is stored in the Security database.
 ___TEXT____ A TEMPORAL-DUPCOLLECTION exception is thrown if the collection already exists.
 ___TEXT____
 ___TEXT____ For details on how to create a collection, see
 ___TEXT____ #display.xqy?fname=http://pubs/6.0doc/xml/temporal/temporal-quick-start.xml%2366392
 ___TEXT____ in the
 ___TEXT____ Temporal Developer's Guide
 ___TEXT____
 ___TEXT____
 ___TEXT____
 SUMMARY:

A: I am not 100% sure what you are trying to do, but clearly, you are not handling the return values of the recursion properly.  Perhaps you mean this:
function parseSummary(text, item) {
    var _text =  text || '';

    if (typeof item === 'string') {
        _text = _text + cleanupString(item);
    } else if (item.constructor == Object) {
        for (var key in item) {
          _text = parseSummary(_text, item[key]);
        }
    } else if (item.constructor == Array) {
        item.map(function(k) {
          _text = parseSummary(_text, k);
        });
    }
    return _text;
}

A: Like you say, you're returning out of the function early. What you want is probably something more like
function parseSummary(item) {
    var _text = '';

    if (typeof item === 'string') {
        _text = cleanupString(item);
    } // if item is object
    else if (item.constructor == Object) {
        for (var key in item) {
           _text += parseSummary(item[key]);
        }
    } // if item is array
    else if (item.constructor == Array) {
        item.map(function(k) {
            _text += parseSummary(k);
        });
    }
    return _text;
}

var input = ["\n\t  This function constructs a named and protected temporal collection \n\t  in the schema database with the specified system and valid axes.  \n\t  This function assumes that the system and valid axes already exist.  \n\t  The temporal collection is stored in the Security database.  \n\t  ", {
    "p": {
        "_children": ["A TEMPORAL-DUPCOLLECTION exception is thrown if the collection \n          already exists.  "]
    }
}, {
    "p": {
        "_children": ["\n  For details on how to create a collection, see  \n ", {
            "a": {
                "_attributes": {
                    "href": "#display.xqy?fname=http://pubs/6.0doc/xml/temporal/temporal-quick-start.xml%2366392"
                },
                "_children": ["Create a Temporal Collection"]
            }
        }, " in the ", {
            "em": {
                "_children": ["Temporal Developer's Guide"]
            }
        }]
    }
}];

function cleanupString(str) {
    return str.replace(/(\n|\t|\s+)/g, " ").trim();
}

function parseSummary(item) {
    var _text = '';

    if (typeof item === 'string') {
        _text = cleanupString(item);
    } // if item is object
    else if (item.constructor == Object) {
        for (var key in item) {
           _text += parseSummary(item[key]);
        }
    } // if item is array
    else if (item.constructor == Array) {
        item.map(function(k) {
            _text += parseSummary(k);
        });
    }
    return _text;
}
var summary = parseSummary(input);
console.log('SUMMARY:', summary); // comes out as empty


text:
Q: What is the wattage of my iPhone? I am trying to make a transportable charger for iPhones, but before I can start this I need to know how much power my iPhone uses when I make an emergency call.
If nobody knows this, I will be glad to have any information related to this.

A: Anandtech has some nice charts detailing the wattage of the iPhone 4S running various apps, which could be a good starting point for you.
You may also want to check out existing kits/projects, such as MintyBoost - they seem to work reasonably well with iPhones. There's a specific MintyBoost page detailing Apple device charging that may also yield some useful info.

A: The power use is going to vary somewhat depending on external factors on the RF side. Network mode in use (GSM/3G) and the power required to establish a stable connection to the cell site in use together with any other usage on the device (speaker/bluetooth/GPS)
Best guess is that your baseline should be the specified 1A required to charge the device and work up/down from there with a meter connected


text:
Q: WordPress не выводит данные с поля таксономии Подскажите почему WP не выводит контент с поля таксономии
Использую вот такой код для вывода заголовка
<?=get_field('zagolovok',$product_category->term_id); ?>

ID проверял , id возвращается верный
но wp все равно ничего не выводит
Подскажите пожалуйста из за чего это происходит и как это исправить?
Во внутренней странице таксономии используется такой код
который возвращает все тот же id ... И там все работает

<?php
  $args = array(
      'taxonomy' => 'sbor_taxonomy',
      'orderby'    => 'count',
      'order'      => 'DESC',
      'hide_empty' => false
  );

  $product_categories = get_terms( $args );
  $i;
  $count = count($product_categories);
  if ( $count > 0 ){
      foreach ( $product_categories as $product_category ) {
          if($product_category->name != "Uncategorized"){
        $i++;
              ?>
                            <option value="<?=$product_category->name; ?>"></option>

              <div class="d5-item d5-item-<?=$i;?>">
                  <img src="<?php echo get_template_directory_uri();?>/static/imgs/d5.png"
                       alt="">

<?=get_field('zagolovok',$product_category->term_id); ?>

<?=$product_category->name; ?>

<?=$product_category->term_id; ?>

                                <?=get_field('kratkoe_opisanie', $product_category->term_id); ?>

                          <a href="<?=get_permalink();?>" class="standart-more">Сборы программы

          <?}                     }
  }
  ?>

A: Потому что нужно читать документацию. Вы тянете поле из поста, а у вас термин: https://www.advancedcustomfields.com/resources/get_fields/
echo get_field( 'field1', 'term_' . $product_category->term_id );


text:
Q: Python library for string formatting with custom placeholders I am searching for a Python library for string formatting with custom placeholders. What I mean is that I would like to be able to define a string like "%f %d %3c" where for example %f would be then replaced with some filename, %d with a directory name and %3c with a counter with three digits. Or something. It does not have to be printf-like but it would be great if it would be. So I would like to be able to define what each letter means, is it string or number, and also some formatting (like number of digits) data.
The idea is that user can specify the format and I then fill it in with data. Like datefmt works. But for custom things.
Is there something like that already made for Python (2.5+, sadly not for 2.7 and 3 and its __format__)?

A: There is string.Template, but it doesn't provide exactly what you want:
>>> from string import Template
>>> t = Template("$filename $directory $counter")
>>> t.substitute(filename="file.py", directory="/home", counter=42)
'file.py /home 42'
>>> t.substitute(filename="file2.conf", directory="/etc", counter=8)
'file2.conf /etc 8'

Documentation: http://docs.python.org/library/string.html#template-strings
But I think this provides what you need. Just specify a template string and use this:
>>> template = "%(filename)s %(directory)s %(counter)03d"
>>> template % {"filename": "file", "directory": "dir", "counter": 42}
'file dir 042'
>>> template % {"filename": "file2", "directory": "dir2", "counter": 5}
'file2 dir2 005'