text:
Q: Can someone explain to me how this function works? I'm learning to code and I'm trying to understand Higher Order Functions and abstractions.  I don't understand how this piece of code runs to return "true".
function greaterThan(n) {
  return function(m) { return m > n; };
}

var greaterThan10 = greaterThan(10);

console.log(greaterThan10(11));

Thanks for the help.

A: The function greaterThan returns a function when called. The returned function has access to all the members of the outer function even after the function has returned. This is called closure.
function greaterThan(n) {
    return function (m) {
        return m > n;
    };
}

When following statement is executed
var greaterThan10 = greaterThan(10);

it is converted as
var greaterThan10 = function (m) {
    return m > 10;
};

So, greaterThan10 is now the function and can be called as
console.log(greaterThan10(11));

Now, value of m is 11 and return 11 > 10; returns as true.
Read more about closures:
How do JavaScript closures work?
Also, I'll recommend following great article to all the JS developers
http://dmitryfrank.com/articles/js_closures


text:
Q: Is it possible to use another programming language for example python(backend) for flutter(frontend)? Please, Can somebody help me. I need to do cross-platform app based on flutter as frontend, and there is problem with backend. I know python very well and I want use it for my app as backend. Is it possible to use python(backend) for flutter(frontend)?
And I just started to learn flutter and don't knowing the Dart language.

A: Yes, you can
you can make the front end and UI of your app with flutter/dart, then you can make a backend with whatever language and technologies you want, such as node js, python, go, travel...
then you can link it and use it in your app using a REST API.

A: Frontend and backend technologies are independent. You can use any server side language(back end) to connect with Flutter. server side languages(back end) are just going to provide information using API. I have been working Flutter with nodejs,Flutter with java. It's upto you

redpajama_set_name: RedPajamaStackExchange


text:
Q: Boost build show default toolset and version Is there anyway to have boost build (bjam/b2) show the default toolset and version that it will use?
Without explicitly specifying a toolset, there is some way it settles on a toolset and version such as gcc-4.8 or darwin-4.2.1.

A: One possible way could be putting something like this in a jamfile:
import notfile ;
import property-set ;

notfile print_toolset : @print_toolset_version ;

rule print_toolset_version ( t : : properties * )
{
    local ps = [ property-set.create $(properties) ] ;
    local toolset = [ $(ps).get <toolset> ] ;
    echo Toolset is $(toolset) ;
    local version = [ $(ps).get <toolset-$(toolset):version> ] ;
    echo Toolset version is $(version) ;
}


text:
Q: Data not inserting in MySQL I am making a script for a guy and he uses Advanced Outgoing API (not familiar). He gives me this URL where the POST variable will be stored in http://example.com/your_script.php?email_address={u_email}&firstname={u_firstname}. So here is my php code. The problem is it cannot read the post values. When I echo it, it's empty.
NOTE: This is the instruction from the API Manual.
Advanced Outgoing API
You can have up to 5 URLs for each Product/Podcast/RSS Feed/Membership be notified whenever a subscriber event happens. You can enter these URLs by clicking on "Edit Notifications/Custom Fields" for a particular item. The system will then POST the following variables to the URLs you've entered. You can also include any of the variables below as a "tags" in your URL and the system will replace the tag with the actual value. This way you can post the values to an existing script that expects a variable name to be different than the ones listed below. For example, your notification URL could be: http://example.com/your_script.php?email_address={u_email}&firstname={u_firstname} . The system would then post all the variables below to: http://example.com/your_script.php?email_address=joe@example.com&firstname=Joe
    $con = mysql_connect("localhost","xyz","xyz","xyz"); // Establish connection to insert in the first table.

    $username = $_POST['paypal_email']; // username of the user.
    $rawpass = $_POST['access_code']; // Raw password.
    $pass = md5($rawpass); // Password of the user encrypted with md5.
    $email = $_POST['email_address']; // E-mail of the user.
    $time = date("Y-m-d H:i:s");

    echo $username;
    echo $pass;
    echo $email;
    echo $time;

    mysql_query("INSERT INTO wpinrootusers ('user_login', 'user_pass', 'user_email', user_registered, 'user_status') VALUES ('$username', '$pass', '$email', '$time', 0), $con"); // Insertion into wpinrootusers table.

    mysql_close($con); // Close connection.

    $con = mysql_connect("localhost","xyz","xyz","xyz"); // Establish connection to insert in the second table.

    mysql_query("INSERT INTO customers ('receipt', 'prod_num', 'email') VALUES ('$rawpass', '6', '$email')", $con); // Insertion into customers table.

    mysql_close($con); // Close second connection.

A: With mysql you have to do:
$con = mysql_connect("localhost","xyz","xyz");

and then select the database:
$db = mysql_select_db("xyz");

The code you used to connect to database works with mysqli (i stands for improved) and you should consider switching from mysql to mysqli

A: When you send the variable as GET parameters you have to use $_GET of course.


text:
Q: Creating a custom color plot with tones of colors Here is a sample set of data
m = {{3.37778, -2.73333, 21, 2}, {0.644444, 2.28889, 9, 3},
     {2.82222, -4.6, 13, 4}, {4.15556, -2.4, 17, 1},
     {-0.866667, -0.4, 6, 2}, {3.64444, 2.26667, 26, 4},
     {2.08889, 3.73333, 12, 3}, {1.73333, -4.48889, 12, 4},
     {-4.44444, -0.777778, 14, 2}, {-4.62222, 2.2, 12, 5},
     {0.977778, 0.755556, 18, 5}, {1.77778, -0.822222, 10, 1},
     {-1.02222, -1.86667, 11, 2}, {4.62222, 4.82222, 16, 3},
     {2., 2., 13, 3}, {0.666667, -1.88889, 8, 4},
     {-2.15556, 4.64444, 18, 5}, {-3.08889, 3.37778, 12, 5},
     {0.311111, -4.22222, 12, 4}, {-4.26667, -3.31111, 12, 2}};

The first two elements of the list represent the coordinates $(x,y)$, while the other two integers $k$, $n$, indicate other type of information.
Now let's setup a color code according to the second integer $n$ (last column)
getColor[m_List, i_Integer] := Module[{s = m[[i, 4]]},
Which[s == 0, Black, s == 1, Darker[Green], s == 2, Red, s == 3,
Blue, s == 4, Magenta, s == 5, Orange, s == 6, Cyan, s == 7,
Brown]];

and then create the graph
data = Table[{PointSize[0.02], getColor[m, i], Point[{m[[i, 1]],
       m[[i, 2]]}]}, {i, 1, Length[m]}];
S0 = Graphics[data];

Now I would like the to keep the colors according to $n$ but modify their tone according to the value of the first integer $k$ (third column). In particular, plot again the $(x,y)$ points in tones of green, red, blue, magenta, etc where darker color means higher value of $k$.
EDIT
Applying @J.M method to the actual data file the output is the follwoing
clist = {Black, Darker[Green], Red, Blue, Magenta, Orange,
 Cyan, Brown};
 Graphics[{PointSize[0.02], MapThread[{Darker[clist[[#[[4]] + 1]], #2],
 Point[Take[#, 2]]} &, {m, 1 - Rescale[m[[All, 3]]]}]}]

As we can see the entire plot is too dark and the colors are hardly distinguishable.
In case anyone wants to play with the actual data file
The resulted plot should be something like this

Any suggestions?
Many thanks in advance!

A:     colors = Lighter[#, 0.2] & /@ {Black, Darker[Green], Red, Blue, Magenta, Orange, Cyan, Brown};

    cols = (Darker[colors[[#[[4]] + 1]], #[[3]]/40.] & /@ bigM);

    cols = Partition[cols, 451];

    Image[cols, ColorSpace -> "RGB"]

EDIT (diagnostics):


text:
Q: Entity is not initialized I'm trying to build a function that gets orders of a customer by id but it gives me an exception: Entity is not initialized
that's my code
<?php

namespace VendorName\Orders\Model\Orders;

use VendorName\Orders\Api\Orders\MyOrdersInterface;
use Magento\Eav\Model\Entity\Collection\AbstractCollection;

class MyOrders extends AbstractCollection implements MyOrdersInterface
{

    /**
     * @api
     * @param int $customerId
     * @return array
     */
    public function getOrders($customerId){
        return [
            $this->addAttributeToFilter('customer_id',$customerId)->load()
        ];
    }
}
?>

A: You'll need to define which class the Collection should use as a resource model and which class it should be a collection of.
You could take a look at one of the existing collections, or use the Mageplaza tutorial (which is usually fine for the basic stuff).
You're looking for something like this:
    /**
     * Resource initialization
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init(Model::class, ResourceModel::class);
    }

Remember to set $_idFieldName, $_eventPrefix and $_eventObject as well.

A: Try this code:
protected $_orderCollectionFactory;
protected $orders;
public function __construct(
    .....
            \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
           .......
        ) {
    ...
    $this->_orderCollectionFactory = $orderCollectionFactory;
    ........
    parent::__construct($context, $data);
}

public function getOrders()
{

    if (!$this->orders) {
        $this->orders = $this->_orderCollectionFactory->create()->addFieldToSelect(
            '*'
        )->addFieldToFilter(
            'customer_id',
            $customerId
        )->setOrder(
            'created_at',
            'desc'
        );
    }
    return $this->orders;
}


text:
Q: Separating Divs

I am trying to separate this 2 divs with a space between them (Please see Picture 1).
The problem is when I add margin or padding this happens (Please see Picture 2).
Here is my code, Please take note I am not using Bootstrap:

.row {
  margin-left: -0.75rem !important;
  margin-right: -0.75rem !important;
}

.col-50 {
  width: 50%;
  float: left;
  position: relative;
  min-height: 1px;
  margin-left: 0.75rem !important;
  margin-right: 0.75rem !important;
}

View Data

              Excel
              PDF

            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">

            </form>

View Data

              Excel
              PDF

            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">

            </form>

Here is my HTML and CSS code. I am trying to make this work for days. Please help. I want to separate these 2 divs with equal space between them perfectly. I am trying to mimic the grid from Bootstrap in order to learn before I try the Bootstrap approach.

A: I would use flexbox to achieve the same results. Or if you aim only to modern browsers, use the newest grid properties.

.row {
  background-color: red;
  display: flex;
  flex: 2 0 50% 50%;
  width: 100%;
}

.card-box {
  width: 100%;
}

.col-50 {
  background-color: yellow;
  display: flex;
  flex: 2 0 50% 50%;
  width: 100%;
}

View Data

              Excel
              PDF

            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">

            </form>

View Data

              Excel
              PDF

            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">

            </form>

A: Have you tried adding margin-right / left to the .cardbox div?
EDIT:
You have to extend the width on row/container, the div you have around the whole page.

A: add *{ box-sizing: border-box; } in your,  remove negative margin for row and use padding instead of margin for .col-50

.col-50 {
width: calc(50% - 1.5rem);
float: left;
position: relative;
min-height: 1px;
padding-left: 0.75rem !important;
padding-right: 0.75rem !important;
margin:0 0.75rem;
background:green
}

.row {
margin-left: -0.75rem !important;
margin-right: -0.75rem !important;}

*{
  box-sizing: border-box;
}
input{
  width:100%
}
/*.col-50:first-child{
  margin-left:0
}
.col-50:last-child{
  margin-right:0
}*/

View Data

 Excel PDF

                        <form class="pull-right">
                            <input type="text" placeholder="Search..." class="form-control">  </form>

View Data

 Excel PDF

                        <form class="pull-right">
                            <input type="text" placeholder="Search..." class="form-control">  </form>


text:
Q: vim - how to NOT automatically switch buffer with :cn and :cb I use the quickfix list to store errors. But i hate when it automatically jump to different buffers when pressing :cn or :cb. I want to press Enter myself to jump to location. Is there any solution ?
Thx.

A: The whole purpose of :cnext is precisely to jump to the next entry in the quickfix list. If that's not what you want, then don't use it.
Navigating to the next line in the quickfix window is done with <Down> or j.


text:
Q: Property 'initializeOnMount' required in type 'MoralisProviderInitializedProps' I was getting an error due to the following code snippet:

Type '{ children: Element; appId: string | undefined; serverUrl: string | undefined; }'
is not assignable to type 'IntrinsicAttributes & MoralisProviderProps'.
Property 'initializeOnMount' is missing in type '{ children: Element; appId: string |
undefined; serverUrl: string | undefined; }' but required in type
'MoralisProviderInitializedProps'.ts(2322)
MoralisProvider.d.ts(19, 5): 'initializeOnMount' is declared here.

Here's my _app.jsx
import "../styles/globals.css";
import { MoralisProvider } from "react-moralis";

function MyApp({ Component, pageProps }:any) {

return (

 < MoralisProvider
   appId={process.env.NEXT_PUBLIC_APP_ID}
   serverUrl={process.env.NEXT_PUBLIC_SERVER_URL} >

 <Component {...pageProps} />

 </MoralisProvider>

        );
 }

 export default MyApp;

Even deploying on vercel gave this same error:

A: Just to further elaborate on my comment: the error you're getting informs you that the prop initializeOnMount is missing from your <MoralisProvider> component, as the typing indicates as such. It does appear to be an inconsistency with their documentation, as their example clearly leaves out the prop.
However, it seems like this can be fixed by simply setting initializeOnMount={false} on the component itself:
<MoralisProvider
  appId={process.env.NEXT_PUBLIC_APP_ID}
  serverUrl={process.env.NEXT_PUBLIC_SERVER_URL}
  initializeOnMount={false}>
  <Component {...pageProps} />
</MoralisProvider>


text:
Q: How do I avoid duplicate dims in one sub? So I basically have this report A. I want to copy all of report B and paste it at the end of report A but it gave me this duplicate dim error and I dont know how to differentiate it. I realize the duplicates but I want the vba program to read my report A excel file ( If ws.Name Like "A*" Then ws.Activate) and activate it but ignore the numbers after A because the file name keeps changing. If theres another way to do that. That would be amazing help I've been trying to figure out all day.
Sub CopyBdata_into_Adata()
Dim ws As Worksheet
For Each ws In Worksheets
If ws.Name Like "B*" Then
ws.Activate
Exit Sub
End If

Next ws
Rows("1:1").Select
Selection.Delete Shift:=xlUp
Range("A2:BG3").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Dim ws As Worksheet
For Each ws In Worksheets
If ws.Name Like "A*" Then
ws.Activate
Exit Sub
End If
Next ws

ActiveWindow.ScrollRow = 20
ActiveWindow.ScrollRow = 120
ActiveWindow.ScrollRow = 259
ActiveWindow.ScrollRow = 318
ActiveWindow.ScrollRow = 1251
ActiveWindow.ScrollRow = 1867
ActiveWindow.ScrollRow = 2462
ActiveWindow.ScrollRow = 4348
ActiveWindow.ScrollRow = 5162
ActiveWindow.ScrollRow = 6571
ActiveWindow.ScrollRow = 6948
ActiveWindow.ScrollRow = 7604
ActiveWindow.ScrollRow = 7921
ActiveWindow.ScrollRow = 8080
ActiveWindow.ScrollRow = 8437
ActiveWindow.ScrollRow = 8576
ActiveWindow.ScrollRow = 9092
ActiveWindow.ScrollRow = 9211
ActiveWindow.ScrollRow = 9648
ActiveWindow.ScrollRow = 9886
ActiveWindow.ScrollRow = 10244
ActiveWindow.ScrollRow = 10561
ActiveWindow.ScrollRow = 11177
ActiveWindow.ScrollRow = 11514
ActiveWindow.ScrollRow = 12090
ActiveWindow.ScrollRow = 12308
ActiveWindow.ScrollRow = 12487
ActiveWindow.ScrollRow = 13122
ActiveWindow.ScrollRow = 13241
ActiveWindow.ScrollRow = 13579
ActiveWindow.ScrollRow = 13599
ActiveWindow.ScrollRow = 13757
ActiveWindow.ScrollRow = 13797
ActiveWindow.ScrollRow = 13817
ActiveWindow.ScrollRow = 13936
ActiveWindow.ScrollRow = 13996
ActiveWindow.ScrollRow = 14015
ActiveWindow.ScrollRow = 14174
ActiveWindow.ScrollRow = 14194
ActiveWindow.ScrollRow = 14274
ActiveWindow.ScrollRow = 14393
ActiveWindow.ScrollRow = 14512
ActiveWindow.ScrollRow = 14532
ActiveWindow.ScrollRow = 14690
ActiveWindow.ScrollRow = 14710
ActiveWindow.ScrollRow = 14750
ActiveWindow.ScrollRow = 14810
ActiveWindow.ScrollRow = 14829
ActiveWindow.ScrollRow = 14849
ActiveWindow.ScrollRow = 14869
ActiveWindow.ScrollRow = 14909
ActiveWindow.ScrollRow = 14929
ActiveWindow.ScrollRow = 14949
ActiveWindow.SmallScroll Down:=3

Range("A14988").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False

Windows("Report_Instructions_and_macros_Test1.xlsm").Activate

End Sub

A: Just remove the second
dim ws as Worksheet
statement.  For a loop control variable in vba, you only need to dim it once within a sub or function.


text:
Q: JSON to POJO null check for fields I have a very large complex JSON and I'm mapping this to a simple POJO (with only the required fields). In groovy JSON is interpreted as Map.
MyObject build(Map<String, Object> payload){

...
    o.name = payload.a.b.name
    o.gender = payload.c.d.e.gender

return o
}

The fields are optional and throws NullPointerException when not present. How to map to "" without putting try-catch for each line? My be straight forward but can't figure out how.

A: You would combine the safe navigation operator and the elvis operator.
If this throws while walking down the payload:
o.gender = payload.c.d.e.gender

Change it to:
o.gender = payload?.c?.d?.e?.gender ?: Gender.UNSET

(or if a null is fine, then leave out the ?:... part)


text:
Q: will mongodb index work on looked up collection? assume I have collection A like:
A{
  b: bid
}

and collection B with index on field x
assume I do an aggregation on A like:
{ $lookup from B as b where b._id = a.bid}
{ $match b.x = something}

will the index on B improve query?


text:
Q: How do you ask something which is not exactly "half a glass"? I know to ask,

Please, fill half a glass of water/tea.

Well, the context for the above sentence is understandable. But, what if I need to ask the same, where
Cases:

*

*The tea/water is more than half but not full.

*It is less than half but neither empty nor very little.
Do we have any words/sentences to express for these two cases?
I guess we can't say:

Please fill 25% or 37% of tea OR 75% of water

A: Simply use any word for a small amount, and make it relative to the half-full mark. For example, you could ask for the glass to be filled

*

*just shy of half full

*a tad more than half full


text:
Q: angular 2+ get location from within a provider I have just started trying to learn Angular. I was familiar with Angular JS and decided to take the plunge into 2+. Apparently, I got started with Angular 6. That was quite a jump.
I am trying to get some information from my API when the application starts. For this, I have created a provider and I hard coded some of the information I needed to get it working. Now I am trying to remove the hard coded part and actually get a url segment from the current location. I have tried using Router and I have tried using Location. I keep getting a message that they do not have a provider. I am not sure how to work around that. My preferred solution would not be to use window.location, but something I can mock and/or unit test.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule, Router } from '@angular/router';

import { AppComponent } from './app.component';
import { CoreModule } from './core/core.module';
import { TemplateListComponent } from './template-list/template-list.component';
import { SectionEditorComponent } from './section-editor/section-editor.component';
import { SiteGuidProvider } from './core/siteGuid.provider';
import { LocationStrategy, PathLocationStrategy } from '@angular/common';

@NgModule({
  declarations: [
    AppComponent,
    TemplateListComponent,
    SectionEditorComponent
  ],
  imports: [
    BrowserModule,
    CoreModule,
    HttpClientModule,
    RouterModule
  ],
  providers: [
    SiteGuidProvider, {
      provide: APP_INITIALIZER,
      useFactory: siteGuidProviderFactory,
      deps: [SiteGuidProvider],
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

export function siteGuidProviderFactory(provider: SiteGuidProvider){
  return () => provider.load();
}

siteGuid.provider.ts
import { Injectable } from "@angular/core";
import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';
import { HttpClient } from "@angular/common/http";
import { DefaultUrlSerializer, Router, UrlTree } from "@angular/router";

import { environment } from "../../environments/environment";
import { OperationReturn } from "./models/OperationReturn";
import { Site } from "./models/Site";

@Injectable()
export class SiteGuidProvider {
    private siteGuid: string = null;

    constructor(private http: HttpClient,
                private location: Location) {}

    public getSiteGuid(): string{
        return this.siteGuid;
    }

    load(){
        console.log(this.location);
        return new Promise((resolve, reject) => {
            this.http
                .get<OperationReturn>(environment.apiUrl + '/site/name/' + 'ja2')
                .subscribe(response => {
                    this.siteGuid = (<Site>(response.successReturn)).siteGuidString;
                    resolve(true);
                })
        });
    }

    // private getDirectoryName() : string {
    //     let url : UrlTree = new DefaultUrlSerializer(this.router.url);
    // }
}


text: Q: Prove that matrix $A = \sum_k^{n}x_k\lambda_ky_k^T$ Prove that matrix $\ A = \sum_{k=1}^n {\bf x}_k \lambda_k {\bf y}_k^T.\ $ If $\ {\bf x}_k\ $ and $\ {\bf y}_k\ $ are the corresponding eigenvector from the left and from the right of $\lambda_k$. Any idea how to start on this proof? Also $A\in\mathbb{R}^{n\times n}$.


text:
Q: Compare two algorithms with each other I am fairly new algorithms and the math behind it.
I am very sorry if this is the wrong place to ask if so please let me know and I can delete this question.
I would need help with the following algorithms.
The task is to choose α so that B is asymptotically faster than A.

A: $\ T_a$(n) = 7$T_a$($\frac{n}{2}$)+n²
B: $\ T_b$(n) = α$T_b$($\frac{n}{4}$)+n²

I have tried to figure out what the asymptotically upper bound would be and I have come up with this formula for A:

A: T(n) = n² + $\sum_{k=1}^k 7^{k-1} \frac{(n^2)}{2^k}+7^kT(\frac{n}{2^k})$

k is for n < 2 = ld(n)
But I do not understand how to go on from here.
Any help would be very apricated.

A: If you are familiar with Master theorem, you can solve it easily. From the master theorem as $c_{crit} = \log_27 \sim  2.81$ we know that $A = O(n^{2.81}) = \Theta(n^{\log_27})$. Hence, if $a = 4^2 = 16$, from master thorem $B = \Theta(n^2\log(n))$ and asymptotically faster than $A$. Also, for all $a < 16$ this would be true.


text:
Q: How do I limit results from webhose data feeds def run_query(search_term):
"""
Given a string containing search terms (query), returns a list of   results from the Webhose API,
with each result consisting of a title, link and summary.
"""
webhose_api_key = read_webhose_key()

if not webhose_api_key:
    raise KeyError('webhose key not found')

try:
    search_term = search_term.strip()
    webhoseio.config(token=webhose_api_key)
    query_params = {"q": "\"{search_term}\" is_first:true language:english domain_rank:<100".format(search_term=search_term), "sort": "relevancy" }
    output = webhoseio.query("filterWebContent", query_params)

    results = []

    for post in output['posts']:
        results.append({'title': post['title'],
                        'link': post['url'],
                        'summary': post['text'][:200]})

except:
    print("Error when querying the Webhose API")

return results

New programmer here. I'm integrating a webhose data feed into my django application. By default queries return the total number of results, however I only want to display the first N results based on my filter parameters. After reading through the API docs I haven't found a solution.

*

*How do I limit the number of results returned from a query?

*If there isn't a succinct solution available via the API, how can I do this using python since the keys aren't ordered?

A: You can use pagination.
This is from webhose documentation

from
A paging parameter that works only for relevancy sort order.
&from=100

https://docs.webhose.io/docs/getpost-parameters


text:
Q: Find the value of : $\lim_{n \rightarrow \infty} \prod_{k=1}^n \left(1+\ln\left(\frac{k+\sqrt{k^2+n^2}}{n}\right)^{\frac{1}{n}}\right)$
Compute $\displaystyle \lim_{n \rightarrow \infty} \prod_{k=1}^n \left(1+\ln\left(\frac{k+\sqrt{k^2+n^2}}{n}\right)^{\frac{1}{n}}\right)$

Note that $\frac{k+\sqrt{k^2+n^2}}{n}\geq 1$ so we're dealing with positive terms.
Taking $\log$ of the product, we're interested in the limit of $\displaystyle \sum_{k=1}^n \ln\left(  1+ \exp \left(\frac 1n\ln\ln \left( \frac kn + \sqrt{\left( \frac{k}{n} \right) ^2 +1}\right)\right) \right)$
which look very much like a Riemann sum.
Setting $f(x) =\ln\ln(x+\sqrt{x^2+1})$, the sum rewrite as $\displaystyle \sum_{k=1}^n \ln\left(  1+ \exp \left(\frac 1nf \left(\frac kn\right)\right) \right)$
I've been trying to use the usual bounds on $\ln$ and $\exp$ to exhibit a Riemann sum, but it's quite messy.

A: Call $$a(n,k)=\ln \left( \frac{k}{n}+\sqrt{\frac{k^2}{n^2}+1 } \right)$$
and notice that $|a(n,k)|\le C$ for some fixed constant $C$.
We want to evaulate
$$S_n=\sum_{k=1}^n \ln(1+1/n\ln(\frac{1}{n}a(n,k))).$$
Using $\log(1+x)=x+O(x^2)$, we can write
$$S_n=\sum_{k=1}^n \frac{1}{n}a(n,k)+O(\frac{1}{n}a(n,k))=\sum_{k=1}^n \frac{1}{n}a(n,k)+O(\frac{1}{n^2})=R_n+O(1/n)$$
where $R_n$ is the n-th Riemann sum of the integral
$$\int_0^1 \ln(x+\sqrt{x^2+1}) dx=I.$$
Hence
$$\lim_{n \to \infty} S_n=I$$
and then the original product is $e^I$.


text:
Q: polynom division without package polynom I am quite new to TeX, so i don't know how to represent polynom division in latex. I can't use package polynom, since I don't have a polynom with numbers so this is a generic solution for this fraction (x_1^n-x_0^n)/(x_1-x_0)
I would appreciate some help to represent this somehow like this:

A similar question was answered there: How to draw polynom division? but i want to picture polynom division in more convinient style

like the package polynom does it and don't know how to tune that solution for my purposes

A: This is using the under-development tabstackengine package, first introduced here at Writing a table with equally spaced columns, based on the widest column (source code available at Measuring align).
The package extends the stackengine package by adding tabbing capability.  This answer, Can I tab inside of align environment?, gives some of the syntax of the package.  I apologize that I have been lax in completing the package and getting it out the door, so the only way to see it in action is by searching this site for tabstackengine.
In this particular answer, I set up the polynomial division with a tabular stack, where I set the alignments of each column.  The only twist is the introduction of the macro \rl{} which give a rule corresponding to the typeset contents of the mathematical argument (extended with a llap and \rlap to make smooth transitions).
The answer below has been EDITED in response to Barbara'a comment, through a redefinition of \rl{}.  My earlier solution artificially extended the horizontal gap between stacked columns, which was a proper criticism.  An additional criticism levied had to do with the unequal spacings around the math operators.  To a large extent, this edit corrects much of that.  However, residual asymmetries about the - and + characters are notably due to the alignment requirements of the columns.  For example, in the middle rows, there is more space prior to the 7x than after the preceding -x^2.  This occurs because the 7x must achieve right-alignment with the somewhat wider (4x three rows later.  In essence, mathrel spacings are sacrificed in order to maintain column alignments, which is considered essential to this problem.
\documentclass{article}
\usepackage{fixltx2e}
\usepackage{tabstackengine}
\stackMath
\newsavebox\tempbox
\newlength\templen
\def\rl#1{%
  \sbox\tempbox{$#1$}%
  \setlength\templen{\wd\tempbox}%
  \llap{\rule{1.5pt}{.1ex}}\rule{\templen}{.1ex}\rlap{\rule{1.5pt}{.1ex}}}
\setstacktabulargap{0pt}
\begin{document}
\tabularShortstack{crcrcrcrl}{
 &(3x^3&-&10x^2&+&7x &-&12&): (x-3) = 3x^2 -x + 4\\
-&(3x^3&-&9x^2 &)&   & &  &\\
\rl{-}&\rl{(3x^3}&\rl{-}&\rl{-(x^2}&\rl{+}&&&&\\
 &     & &-x^2 &+&7x & &  &\\
 &     &-&(-x^2&+&3x &)&  &\\
&&\rl{-}&\rl{-(x^2}&\rl{+}&\rl{(7x}&\rl{-}&&\\
 &     &&      & &4x &-&12&\\
 &     &&      &-&(4x&-&12&)\\
&&&&\rl{+}&\rl{(7x}&\rl{-}&\rl{12}&\rl{)}\\
 &&&&&&&0&
}
\end{document}

Here is an example of another problem cited by the OP.  The only differences here were the need to use \rlap if an entry was to be allowed to cross column boundaries, and I also changed the column alignment to l for the polynomial entries, as opposed to r in the last example, which had constant coefficients.
\documentclass{article}
\usepackage{fixltx2e}
\usepackage{tabstackengine}
\stackMath
\newsavebox\tempbox
\newlength\templen
\def\rl#1{%
  \sbox\tempbox{$#1$}%
  \setlength\templen{\wd\tempbox}%
  \llap{\rule{2.1pt}{.1ex}}\rule{\templen}{.1ex}\rlap{\rule{2.1pt}{.1ex}}}
\setstacktabulargap{0pt}
\begin{document}
\tabularShortstack{crllclcl}{
 &(x^n&-&x_0^n&)%
  \rlap{$:(x-x_0) =  x^{n+1} + x_0x^{n-2} + x_0^2x^{n-3} + \ldots $}&&&\\
-&(x^n&-&x_0x^{n-1} &)&   & &\\
\rl{-}&\rl{(x^n}&\rl{-(}&\rl{(x_0x^{n-1}}&\rl{+}&&&\\
 &     & &x_0x^{n-1} &-&x_0^n & &\\
 &     &-(&x_0x^{n-1}&-&x_0^2x^{n-2} &)&\\
&&\rl{-(}&\rl{(x_0x^{n-1}}&\rl{+}&\rl{x_0^2x^{n-2}}&\rl{-}&\\
 &     &&      & &x_0^2x^{n-2}&-&x_0^n\\
\rule{0ex}{3ex}&&&&&\rlap{...................}&&
}
\end{document}


text:
Q: Touchpad settings not available on ubuntu 16.04 for dell latitude I did a fresh install of ubuntu 16.04 on my new latitude E5570.  The mouse/touchpad settings only has the General and Mouse sections, nothing to change the touchpad options (like inverse scroll).  The xinput command returns:
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ ImPS/2 Generic Wheel Mouse                id=12   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Power Button                              id=8    [slave  keyboard (3)]
    ↳ Sleep Button                              id=9    [slave  keyboard (3)]
    ↳ Integrated_Webcam_HD                      id=10   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=11   [slave  keyboard (3)]
    ↳ Dell WMI hotkeys                          id=13   [slave  keyboard (3)]
    ↳ DELL Wireless hotkeys                     id=14   [slave  keyboard (3)]

So it appears that it isn't recognizing the touchpad.  How do I get ubuntu to load the correct driver?


text:
Q: Vue 3 package version mismatch I'm trying to update a package I made to vue 3, and I'm facing an issue with vue-template-compiler.
I tried to follow a similar post that had some kind of a similar problem but it doesn't seems to work for me.(Vue package Version mismatch)
I got the following error:
> @utt/message-system@1.1.4 build:es
> cross-env NODE_ENV=production rollup --config build/rollup.config.js --format es

[!] Error:

Vue packages version mismatch:

- vue@3.1.1 (C:\projects\UTT-Message-System\module\node_modules\vue\index.js)
- vue-template-compiler@2.6.14 (C:\projects\UTT-Message-System\module\node_modules\vue-template-compiler\package.json)

This may cause things to work incorrectly. Make sure to use the same version for both.
If you are using vue-loader@>=10.0, simply update vue-template-compiler.
If you are using vue-loader@<10.0 or vueify, re-installing vue-loader/vueify should bump vue-template-compiler to the latest.

Error:

Vue packages version mismatch:

- vue@3.1.1 (C:\projects\UTT-Message-System\module\node_modules\vue\index.js)
- vue-template-compiler@2.6.14 (C:\projects\UTT-Message-System\module\node_modules\vue-template-compiler\package.json)

This may cause things to work incorrectly. Make sure to use the same version for both.
If you are using vue-loader@>=10.0, simply update vue-template-compiler.
If you are using vue-loader@<10.0 or vueify, re-installing vue-loader/vueify should bump vue-template-compiler to the latest.

    at Object.<anonymous> (C:\projects\UTT-Message-System\module\node_modules\vue-template-compiler\index.js:10:9)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Object.require.extensions.<computed> [as .js] (C:\projects\UTT-Message-System\module\node_modules\rollup\dist\shared\loadConfigFile.js:516:13)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:\projects\UTT-Message-System\module\node_modules\@vue\component-compiler\dist\compiler.js:26:26)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Object.require.extensions.<computed> [as .js] (C:\projects\UTT-Message-System\module\node_modules\rollup\dist\shared\loadConfigFile.js:516:13)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)

[nodemon] app crashed - waiting for file changes before starting...

Update: I used rollup-plugin-vue package, and its not compatable with vue 3, so I installed rollup-plugin-vue@next and now I don't get vue-template-compiler inside my package-lock.json file.
But now I have a new error on the plugin babel, and I'm trying to resolve this issue, so if anyone can share any ideas it would be much appreciated:
[!] (plugin babel) SyntaxError: C:\projects\UTT-Message-System\module\Components\MessageContainer.vue?vue&type=style&index=0&id=3d58915e&lang.css: Unexpected token (2:0)

  1 |
> 2 | ._messageList_yig6l_3 {
    | ^
  3 |   position: absolute;
  4 |   display: flex;
  5 |   flex-direction: column;
Components\MessageContainer.vue?vue&type=style&index=0&id=3d58915e&lang.css (2:0)
SyntaxError: C:\projects\UTT-Message-System\module\Components\MessageContainer.vue?vue&type=style&index=0&id=3d58915e&lang.css: Unexpected token (2:0)

  1 |
> 2 | ._messageList_yig6l_3 {
    | ^
  3 |   position: absolute;
  4 |   display: flex;
  5 |   flex-direction: column;
    at Parser._raise (C:\projects\UTT-Message-System\module\node_modules\@babel\parser\src\parser\error.js:134:45)
    at Parser.raiseWithData (C:\projects\UTT-Message-System\module\node_modules\@babel\parser\src\parser\error.js:129:17)
    at Parser.raise (C:\projects\UTT-Message-System\module\node_modules\@babel\parser\src\parser\error.js:78:17)
    at Parser.unexpected (C:\projects\UTT-Message-System\module\node_modules\@babel\parser\src\parser\util.js:179:16)
    at Parser.parseExprAtom (C:\projects\UTT-Message-System\module\node_modules\@babel\parser\src\parser\expression.js:1202:20)
    at Parser.parseExprSubscripts (C:\projects\UTT-Message-System\module\node_modules\@babel\parser\src\parser\expression.js:613:23)
    at Parser.parseUpdate (C:\projects\UTT-Message-System\module\node_modules\@babel\parser\src\parser\expression.js:593:21)
    at Parser.parseMaybeUnary (C:\projects\UTT-Message-System\module\node_modules\@babel\parser\src\parser\expression.js:560:23)
    at Parser.parseExprOps (C:\projects\UTT-Message-System\module\node_modules\@babel\parser\src\parser\expression.js:364:23)
    at Parser.parseMaybeConditional (C:\projects\UTT-Message-System\module\node_modules\@babel\parser\src\parser\expression.js:329:23)

[nodemon] app crashed - waiting for file changes before starting...

Thanks for the help.

A: remove "vue-template-compiler" from your app with
npm uninstall vue-template-compiler

then install compiler-sfc which replaces vue-template-compiler
npm i -D @vue/compiler-sfc

make sure there is no vue-template-compiler on your package.json and you see vue/compiler-cfs
since you've removed vue-template-compiler then vue-loader will complain to need it to work so upgrade it as well to work for vue 3 with the following command
npm install vue-loader@next

since you're doing upgrade, there might happen other errors here and there depending on your project configuration. but keeping on solving, soon you'll get it running


text:
Q: Prometheus - Measure time a container has been running in Grafana Time Range for dashboard I am trying to get the time that a certain container/pod has been running in the time range interval from the grafana dashboard in kubernetes. Taking into account that the pod can be stopped and started with the same name.
Based on: how to create query to monitoring how many minutes docker containers ran for a day
I was able to test the following query:
count_over_time(
  (changes(container_last_seen{namespace="dslab", pod=~"$user"}[90s])>0)
  [<interval>:90s]
)*90

But it doesn't work because the pod is restarted with the same name

A: The following solution works.
In prometheus this query:
(kube_pod_container_status_running{pod=~"$pod_name"} > 0) * ($__interval_ms / 1000)

$__interval_ms is the time in ms for the time range selected in the dashboard
And then in the grafana transfromation option: group by and calculate Total or Count:


text:
Q: Why does iPhone text not suggest an American flag emoji? When typing out country names for example Canada, Russia, Mexico, Cuba, and China and all other country names I have tried using my iPhone with iOS 10 emojis are suggested with the respective flag for the country name I have just typed. When I type "America" this is not the case, why does typing the word America not suggest the use of the American flag emoji like so for all other countries?

A: Apple is just being strict about America not being a country, but a continent. If you type USA or United States, predictive text will suggest the American flag:


text:
Q: How to use gdb with Ceedling? I want to debug the C source code under test when use Ceedling. I found that the following command could be used, but I could not set breakpoint. It seems the symbol information is not generated. I use the default settings in project.yml and I checked -g option is enabled in defaults.rb config file.
gdb --args -S rake test:sample_program
GNU gdb (GDB) (Cygwin 7.10.1-1) 7.10.1
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
Reading symbols from ruby...(no debugging symbols found)...done.

A: Well, I find someway!
In Ceedling project, the executable is located in \build\test\out\test_sample.out
I tried,

gdb build\test\out\test_sample.out

Now, all symbols are loaded and I can set breakpoint and step as well.
This may not be Ceedling way of debugging, but it works for me!!

A: For those of us using Visual Studio Code with the Ceedling Test Explorer extension, the following launch.json file (put inside the .vscode folder) can be used to debug with GDB:
{
    "version": "0.2.0",
    "configurations": [
        {
            // Use the following for the Ceedling Explorer Debug Configuration
            "name": "ceedling_gdb",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/build/test/out/${command:ceedlingExplorer.debugTestExecutable}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "gdb",
            // May omit the following if gdb is on the PATH
            "miDebuggerPath": "<path to gdb executable>",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}

This will conveniently launch whichever test module you click the little bug icon.
Derived from https://gist.github.com/bd2357/b2d69ab18849c1e2f70959eef426ff09

A: Thanks SRAK
FYI, for MacOS, I used
lldb build/test/out/test_sample.out

since whichever gdb (installed by home brew) expects a different format.
Cheers,
Greg


text:
Q: Python Multiprocessing, Difference between Process and Pool, Pickling of Data I am wondering what is the difference between starting a Pool of workers to manage a task in parallel or to start individual processes when it comes to pickling and distributing jobs.
I do have a task (here do_my_job) whose objects cannot be pickled. Thus, I cannot start a pool of workers to execute the task in parallel. The following snippet does NOT work, where iterator iterates over different parameters settings for do_my_job:
import multiprocessing as multip

mpool = multip.Pool(ncores)
mpool.map(do_my_job, iterator)
mpool.close()
mpool.join()

Yet, the following code snippet DOES work:
import time
import multiprocessing as multip

keep_running=True
process_list = []

while len(process_list)>0 or keep_running:

    terminated_procs = []
    for idx, proc in enumerate(process_list):

        if not proc.is_alive():
            terminated_procs.append(idx)

    for terminated_proc in terminated_procs:
        process_list.pop(terminated_proc)

    if len(process_list) < ncores and keep_running:
        try:
            task = iterator.next()
            proc = multip.Process(target=do_my_job,
                                                   args=(task,))

            proc.start()
            process_list.append(proc)
        except StopIteration:
            keep_running=False

    time.sleep(0.1)

How is my job in the latter case distributed to the individual processes? Is there not step of pickling the task and all related objects involved before a process is started? If not how are the task and objects passed to the new processes?

A: When you fork a new process the child process will inherit his parent data. So, if the parent defines a variable before forking, the child will be able to see it as it were its own variable. After the fork syscall child and parent process should use some IPC to share data between them.
When you create a Pool you are forking N processes, then, when you call map, you pass them your data. But, because the processes were already forked, the only way to share this data is using IPC which involves "pickling" the object. In the latter case you are forking after creating the data, so the child process is able to access it as it where its own.
I think that the best thing that you could do would be to make your object "pickable".


text:
Q: If the orbit space is Hausdorff, must the action be proper? Let $G$ be a Lie group acting continuously on a manifold $M$. It is well known that if the action is proper, then the quotient space $M/G$ is Hausdorff.
Does the converse hold? If $M/G$ is Hausdorff, must the action be proper?

A: This is a silly counterexample but it's a counterexample. Let $M=\{0\}$ and let $G=\mathbb{R}$ act on $M$ by multiplication. Then $M/G$ is still only one point but the action is not proper, since the preimage of $(0,0) \in M\times M$ is $G\times M$.
This is a instant of a more general phenomena, namely that if $M$ is compact and $G$ is not then the action is not proper. If it happens (as in this case) that the action is transitive your quotient will be one point and thus Hausdorff.
This should be seen as a complement to Tsemo Aristide's answer.

A: No, let $G$ be a non locally compact Lie group (infinite dimensional) the left action of $G$ on $G$ is not proper, for example, take any neighborhood $U$ of the identity $1$, the set $\{g\in G, g(U)\cap U\neq \phi\}$ is infinite. but the quotient of $G$ by $G$ is a point.
An interesting question is to know if your question is true when $G$ is a discrete group acting on a manifold $M$.


text:
Q: Is it possible to autowire local server port outside of a test class in Spring Boot test? I was wishing to wrap my controller calls for rest api testing for handy usage and wrote
class BaseControllerWrapper {
    @LocalServerPort
    int port;
    ...
}

@Component
class SpecificControllerWrapper extends BaseControllerWrapper {
    void callEndpoint() {
        ...
    }
}

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
public class PermissionsTest {

     @Autowire
     SpecificControllerWrapper specificControllerWrapper;

     @Test
     public void testSomething() {
         ...
         wrapper.callEndpoint();
         ...
     }

}

Unfortunately, Spring was unable to instantiate beans with

Error creating bean with name 'specificControllerWrapper': Injection of autowired
dependencies failed; nested exception is
java.lang.IllegalArgumentException: Could not resolve placeholder
'local.server.port' in value "${local.server.port}"   at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:405)

Is it possible to overcome?


text:
Q: Django / DRF: Serializing QuerySet leads no "No attribute found error" When I serialize a multi-item queryset, it throws id not found error - despite each item having an id attribute (I checked this already).
Serializing: json_data = SampleSerializer(Sample.objects.all(), many=True)
Serializer:
class SampleSerializer(serializers.ModelSerializer):
    sample_id = serializers.SerializerMethodField()

    class Meta:
        model = Sample
        fields = ["sample_id",]

    def get_sample_id(self, obj):
        return encoded_id(obj.id)  # not found error

Model
class Sample(models.Model):
    objects = SampleManager()

    id = models.AutoField(primary_key=True)
    vector_column = SearchVectorField(null=True)

    class Meta:
        indexes = (GinIndex(fields=["vector_column"]),)

ViewSet
class SampleViewSet(viewsets.ViewSet):
    serializer_class = SampleSerializer

    @action(detail=False, methods=["POST"])
    def search_samples(self, request):
        samples = Link.objects.all()
        json_samples = SampleSerializer(samples, many=True).data
        return Response(json_links, status=status.HTTP_200_OK)

Traceback
Traceback (most recent call last):
  File "venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 204, in _get_response
    response = response.render()
  File "venv/lib/python3.8/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "venv/lib/python3.8/site-packages/rest_framework/response.py", line 70, in rendered_content
    ret = renderer.render(self.data, accepted_media_type, context)
  File "venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 724, in render
    context = self.get_context(data, accepted_media_type, renderer_context)
  File "venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 696, in get_context
    'post_form': self.get_rendered_html_form(data, view, 'POST', request),
  File "venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 511, in get_rendered_html_form
    return self.render_form_for_serializer(serializer)
  File "venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 519, in render_form_for_serializer
    serializer.data,
  File "venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 548, in data
    ret = super().data
  File "venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 248, in data
    self._data = self.to_representation(self.validated_data)
  File "venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 515, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "venv/lib/python3.8/site-packages/rest_framework/fields.py", line 1882, in to_representation
    return method(value)
  File "/serializers.py", line 22, in get_sample_id
    return encoded_id(obj.id)

Exception Type: AttributeError at /api/samples/search_samples/
Exception Value: 'collections.OrderedDict' object has no attribute 'id'

A: Could you define the SampleAPIView class in your views directory?
class SampleAPIView(ListAPIView):
  permission_class = (IsAccessUser,)
  serializer_class = SampleSerializer
  queryset = Sample.object.all()

Also If you gonna get it as json format, I think you should use the

json.loads()


text:
Q: How to convert string with some "\r\n" into list? I have a string and want to convert it into a LinkedList such that every line is a single element.
I use Visual Studio 2012.
Is there any easy way to do it?
This string looks like:
LOAD  =5.01E+10
MPY   $1
ADD   $2

But in fact it contain LOAD  =5.01E+10\r\nMPY   $1\r\nADD   $2
IMPORTANT UPDATE: i don't need to remove "\r\n" or something like this. I need list (actually not linked) with pair of "left part" and "right part" in each element. Example of what kind of list i what to get from previous example:
("LOAD  ", "=5.01E+10") => ("MPY   ", "$1") => ("ADD   ", "$2") => null

Actually, better to save all this free space after left part.

A: The way newlines are represented can depend on the environment: Linux for instance uses \n.
To make things easier, you can use a StringReader:
public static IEnumerable<string> Lines (string text) {
    string line;
    using (StringReader reader = new StringReader(text)) {
        while ((line = reader.ReadLine()) != null) {
            yield return line;
        }
    }
}

For lazy evaluation to lines: this can be helpful in the future if you for instance have a huge file, and only need the to show the first 10 lines to a user.
And then call:
return new LinkedList<string>(Lines(text));

EDIT:
To obtain the pairs, you can introduce a new method:
A second method then can be used split items into pairs:
public static KeyValuePair<string,string> SplitToKeyValue(string text) {
    Regex p = new Regex(@"^(\w+)\s+(.*)$");
    Match m = p.Match(text);
    return new KeyValuePair<string,string>(m.Groups[1].Value,m.Groups[2].Value);
}

And then create the LinkedList with:
return new LinkedList<KeyValuePair<string,string>>(Lines(text).Select(SplitToKeyValue));

DEMO
using Mono's csharp interactive shell:
$ csharp
Mono C# Shell, type "help;" for help

Enter statements below.
csharp> using System.IO;
csharp> using System.Text.RegularExpressions;
csharp> public static class Foo {
      >
      > public static KeyValuePair<string,string> SplitToKeyValue(string text) {
      >     Regex p = new Regex(@"^(\w+)\s+(.*)$");
      >     Match m = p.Match(text);
      >     return new KeyValuePair<string,string>(m.Groups[1].Value,m.Groups[2].Value);
      > }
      >
      > public static IEnumerable<string> Lines (string text) {
      >     string line;
      >     using (StringReader reader = new StringReader(text)) {
      >         while ((line = reader.ReadLine()) != null) {
      >             yield return line;
      >         }
      >     }
      > }
      >
      > }
csharp> string inp = "LOAD =5.01E+10\nMPY $1\nADD $2";
csharp> new LinkedList<KeyValuePair<string,string>>(Foo.Lines(inp).Select(Foo.SplitToKeyValue))
{ [LOAD, =5.01E+10], [MPY, $1], [ADD, $2] }

or fiddle.

A: So from your question, I get that you need this string to be transformed into a linked list - key, value pairs. Here is a way to do that:
Edit (sorry this question had too may edits):
string input = "LOAD  =5.01E+10\r\nMPY   $1\r\nADD   $2";

IEnumerable<KeyValuePair<string, string>> pairs =
    input.Split(new string[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
        .Select(x => x.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries))
        .Select(x => new KeyValuePair<string, string>(x[0], x[1]));

var data = new LinkedList<KeyValuePair<string, string>>(pairs);

Edit
Here is how you iterate over the linked list:
foreach (KeyValuePair<string, string> pair in data) {
    Console.WriteLine("Key: {0} - Value: {1}", pair.Key, pair.Value);
}

Or get a node and access its Value, which is the key-value pair:
KeyValuePair<string, string> p = data.First.Value;
string k = p.Key; // LOAD
string v = p.Value; // =5.01E+10

A: Yes,
 yourString = yourString.Replace(System.Environment.NewLine, "\r\n");

http://www.dotnetperls.com/newline

A: Here is the output
string LOAD = "5.01E+10\r\nMPY $1\r\nADD $2";
string newstring1 = LOAD.Replace("\r", " ");
string newstring2 = newstring1.Replace("\n", " ");
Console.WriteLine(newstring2);

output
5.01E+10 MPY $1 ADD $2

A: i understand as you need to convert string to list. if it right then solution is
 Regex.Matches("your string","\r\n", RegexOptions.Singleline|RegexOptions.IgnoreCase)


text:
Q: Не работает виджет QMediaPlayer в программе Python Начал разрабатывать медиаплеер на Python, используя PyQt5, и  столкнулся с проблемой. Весь функционал я реализовал, кроме воспроизведения видео.
Нигде не могу найти решение моей проблемы. Буду благодарен любому, кто поможет.
Прилагаю код:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(484, 371)
        self.centralWidget = QtWidgets.QWidget(MainWindow)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.centralWidget.sizePolicy().hasHeightForWidth())
        self.centralWidget.setSizePolicy(sizePolicy)
        self.centralWidget.setObjectName("centralWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralWidget)
        self.horizontalLayout.setContentsMargins(11, 11, 11, 11)
        self.horizontalLayout.setSpacing(6)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setObjectName("verticalLayout")
        self.playlistView = QtWidgets.QListView(self.centralWidget)
        self.playlistView.setAcceptDrops(True)
        self.playlistView.setProperty("showDropIndicator", True)
        self.playlistView.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly)
        self.playlistView.setAlternatingRowColors(True)
        self.playlistView.setUniformItemSizes(True)
        self.playlistView.setObjectName("playlistView")
        self.verticalLayout.addWidget(self.playlistView)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setSpacing(6)
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.currentTimeLabel = QtWidgets.QLabel(self.centralWidget)
        self.currentTimeLabel.setMinimumSize(QtCore.QSize(80, 0))
        self.currentTimeLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.currentTimeLabel.setObjectName("currentTimeLabel")
        self.horizontalLayout_4.addWidget(self.currentTimeLabel)
        self.timeSlider = QtWidgets.QSlider(self.centralWidget)
        self.timeSlider.setOrientation(QtCore.Qt.Horizontal)
        self.timeSlider.setObjectName("timeSlider")
        self.horizontalLayout_4.addWidget(self.timeSlider)
        self.totalTimeLabel = QtWidgets.QLabel(self.centralWidget)
        self.totalTimeLabel.setMinimumSize(QtCore.QSize(80, 0))
        self.totalTimeLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
        self.totalTimeLabel.setObjectName("totalTimeLabel")
        self.horizontalLayout_4.addWidget(self.totalTimeLabel)
        self.verticalLayout.addLayout(self.horizontalLayout_4)
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setSpacing(6)
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.previousButton = QtWidgets.QPushButton(self.centralWidget)
        self.previousButton.setText("")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("images/control-skip-180.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.previousButton.setIcon(icon)
        self.previousButton.setObjectName("previousButton")
        self.horizontalLayout_5.addWidget(self.previousButton)
        self.playButton = QtWidgets.QPushButton(self.centralWidget)
        self.playButton.setText("")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("images/control.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.playButton.setIcon(icon1)
        self.playButton.setObjectName("playButton")
        self.horizontalLayout_5.addWidget(self.playButton)
        self.pauseButton = QtWidgets.QPushButton(self.centralWidget)
        self.pauseButton.setText("")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("images/control-pause.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pauseButton.setIcon(icon2)
        self.pauseButton.setObjectName("pauseButton")
        self.horizontalLayout_5.addWidget(self.pauseButton)
        self.stopButton = QtWidgets.QPushButton(self.centralWidget)
        self.stopButton.setText("")
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap("images/control-stop-square.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.stopButton.setIcon(icon3)
        self.stopButton.setObjectName("stopButton")
        self.horizontalLayout_5.addWidget(self.stopButton)
        self.nextButton = QtWidgets.QPushButton(self.centralWidget)
        self.nextButton.setText("")
        icon4 = QtGui.QIcon()
        icon4.addPixmap(QtGui.QPixmap("images/control-skip.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.nextButton.setIcon(icon4)
        self.nextButton.setObjectName("nextButton")
        self.horizontalLayout_5.addWidget(self.nextButton)
        self.viewButton = QtWidgets.QPushButton(self.centralWidget)
        self.viewButton.setText("")
        icon5 = QtGui.QIcon()
        icon5.addPixmap(QtGui.QPixmap("images/application-image.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.viewButton.setIcon(icon5)
        self.viewButton.setCheckable(True)
        self.viewButton.setObjectName("viewButton")
        self.horizontalLayout_5.addWidget(self.viewButton)
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_5.addItem(spacerItem)
        self.label = QtWidgets.QLabel(self.centralWidget)
        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap("images/speaker-volume.png"))
        self.label.setObjectName("label")
        self.horizontalLayout_5.addWidget(self.label)
        self.volumeSlider = QtWidgets.QSlider(self.centralWidget)
        self.volumeSlider.setMaximum(100)
        self.volumeSlider.setProperty("value", 100)
        self.volumeSlider.setOrientation(QtCore.Qt.Horizontal)
        self.volumeSlider.setObjectName("volumeSlider")
        self.horizontalLayout_5.addWidget(self.volumeSlider)
        self.verticalLayout.addLayout(self.horizontalLayout_5)
        self.horizontalLayout.addLayout(self.verticalLayout)
        MainWindow.setCentralWidget(self.centralWidget)
        self.menuBar = QtWidgets.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 484, 22))
        self.menuBar.setObjectName("menuBar")
        self.menuFIle = QtWidgets.QMenu(self.menuBar)
        self.menuFIle.setObjectName("menuFIle")
        MainWindow.setMenuBar(self.menuBar)
        self.statusBar = QtWidgets.QStatusBar(MainWindow)
        self.statusBar.setObjectName("statusBar")
        MainWindow.setStatusBar(self.statusBar)
        self.open_file_action = QtWidgets.QAction(MainWindow)
        self.open_file_action.setObjectName("open_file_action")
        self.menuFIle.addAction(self.open_file_action)
        self.menuBar.addAction(self.menuFIle.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Failamp"))
        self.currentTimeLabel.setText(_translate("MainWindow", "0:00"))
        self.totalTimeLabel.setText(_translate("MainWindow", "0:00"))
        self.menuFIle.setTitle(_translate("MainWindow", "FIle"))
        self.open_file_action.setText(_translate("MainWindow", "Open file..."))

def hhmmss(ms):
    # s = 1000
    # m = 60000
    # h = 360000
    h, r = divmod(ms, 36000)
    m, r = divmod(r, 60000)
    s, _ = divmod(r, 1000)
    return ("%d:%02d:%02d" % (h, m, s)) if h else ("%d:%02d" % (m, s))

class ViewerWindow(QMainWindow):
    state = pyqtSignal(bool)

    def closeEvent(self, e):
        # Emit the window state, to update the viewer toggle button.
        self.state.emit(False)

class PlaylistModel(QAbstractListModel):
    def __init__(self, playlist, *args, **kwargs):
        super(PlaylistModel, self).__init__(*args, **kwargs)
        self.playlist = playlist

    def data(self, index, role):
        if role == Qt.DisplayRole:
            media = self.playlist.media(index.row())
            return media.canonicalUrl().fileName()

    def rowCount(self, index):
        return self.playlist.mediaCount()

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)

        self.player = QMediaPlayer()

        self.player.error.connect(self.erroralert)
        self.player.play()

        # Setup the playlist.
        self.playlist = QMediaPlaylist()
        self.player.setPlaylist(self.playlist)

        # Add viewer for video playback, separate floating window.
        self.viewer = ViewerWindow(self)
        self.viewer.setWindowFlags(self.viewer.windowFlags() | Qt.WindowStaysOnTopHint)
        self.viewer.setMinimumSize(QSize(480, 360))

        videoWidget = QVideoWidget()
        self.viewer.setCentralWidget(videoWidget)
        self.player.setVideoOutput(videoWidget)

        # Connect control buttons/slides for media player.
        self.playButton.pressed.connect(self.player.play)
        self.pauseButton.pressed.connect(self.player.pause)
        self.stopButton.pressed.connect(self.player.stop)
        self.volumeSlider.valueChanged.connect(self.player.setVolume)

        self.viewButton.toggled.connect(self.toggle_viewer)
        self.viewer.state.connect(self.viewButton.setChecked)

        self.previousButton.pressed.connect(self.playlist.previous)
        self.nextButton.pressed.connect(self.playlist.next)

        self.model = PlaylistModel(self.playlist)
        self.playlistView.setModel(self.model)
        self.playlist.currentIndexChanged.connect(self.playlist_position_changed)
        selection_model = self.playlistView.selectionModel()
        selection_model.selectionChanged.connect(self.playlist_selection_changed)

        self.player.durationChanged.connect(self.update_duration)
        self.player.positionChanged.connect(self.update_position)
        self.timeSlider.valueChanged.connect(self.player.setPosition)

        self.open_file_action.triggered.connect(self.open_file)

        self.setAcceptDrops(True)

        self.show()

    def dragEnterEvent(self, e):
        if e.mimeData().hasUrls():
            e.acceptProposedAction()

    def dropEvent(self, e):
        for url in e.mimeData().urls():
            self.playlist.addMedia(
                QMediaContent(url)
            )

        self.model.layoutChanged.emit()

        # If not playing, seeking to first of newly added + play.
        if self.player.state() != QMediaPlayer.PlayingState:
            i = self.playlist.mediaCount() - len(e.mimeData().urls())
            self.playlist.setCurrentIndex(i)
            self.player.play()

    def open_file(self):
        path, _ = QFileDialog.getOpenFileName(self, "Open file", "",
                                              "mp3 Audio (*.mp3);mp4 Video (*.mp4);Movie files (*.mov);All files (*.*)")

        if path:
            self.playlist.addMedia(
                QMediaContent(
                    QUrl.fromLocalFile(path)
                )
            )

        self.model.layoutChanged.emit()

    def update_duration(self, duration):
        print("!", duration)
        print("?", self.player.duration())

        self.timeSlider.setMaximum(duration)

        if duration >= 0:
            self.totalTimeLabel.setText(hhmmss(duration))

    def update_position(self, position):
        if position >= 0:
            self.currentTimeLabel.setText(hhmmss(position))

        # Disable the events to prevent updating triggering a setPosition event (can cause stuttering).
        self.timeSlider.blockSignals(True)
        self.timeSlider.setValue(position)
        self.timeSlider.blockSignals(False)

    def playlist_selection_changed(self, ix):
        # We receive a QItemSelection from selectionChanged.
        i = ix.indexes()[0].row()
        self.playlist.setCurrentIndex(i)

    def playlist_position_changed(self, i):
        if i > -1:
            ix = self.model.index(i)
            self.playlistView.setCurrentIndex(ix)

    def toggle_viewer(self, state):
        if state:
            self.viewer.show()
        else:
            self.viewer.hide()

    def erroralert(self, *args):
        print(args)

if __name__ == '__main__':
    app = QApplication([])
    app.setApplicationName("Failamp")
    app.setStyle("Fusion")

    # Fusion dark palette from https://gist.github.com/QuantumCD/6245215.
    palette = QPalette()
    palette.setColor(QPalette.Window, QColor(53, 53, 53))
    palette.setColor(QPalette.WindowText, Qt.white)
    palette.setColor(QPalette.Base, QColor(25, 25, 25))
    palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
    palette.setColor(QPalette.ToolTipBase, Qt.white)
    palette.setColor(QPalette.ToolTipText, Qt.white)
    palette.setColor(QPalette.Text, Qt.white)
    palette.setColor(QPalette.Button, QColor(53, 53, 53))
    palette.setColor(QPalette.ButtonText, Qt.white)
    palette.setColor(QPalette.BrightText, Qt.red)
    palette.setColor(QPalette.Link, QColor(42, 130, 218))
    palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
    palette.setColor(QPalette.HighlightedText, Qt.black)
    app.setPalette(palette)
    app.setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }")

    window = MainWindow()
    app.exec_()

A: У вас неразбериха с макетами.
Я отметит строки, в которые внес изменения.
Я не проверял действия, которые выполняются по нажатию кнопок, кроме playButton.
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(484, 371)
        self.centralWidget = QtWidgets.QWidget(MainWindow)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.centralWidget.sizePolicy().hasHeightForWidth())
        self.centralWidget.setSizePolicy(sizePolicy)
        self.centralWidget.setObjectName("centralWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralWidget)
        self.horizontalLayout.setContentsMargins(11, 11, 11, 11)
        self.horizontalLayout.setSpacing(6)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setObjectName("verticalLayout")

        self.playlistView = QtWidgets.QListView(self.centralWidget)
        self.playlistView.setAcceptDrops(True)
        self.playlistView.setProperty("showDropIndicator", True)
        self.playlistView.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly)
        self.playlistView.setAlternatingRowColors(True)
        self.playlistView.setUniformItemSizes(True)
        self.playlistView.setObjectName("playlistView")
        self.verticalLayout.addWidget(self.playlistView)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setSpacing(6)
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.currentTimeLabel = QtWidgets.QLabel(self.centralWidget)
        self.currentTimeLabel.setMinimumSize(QtCore.QSize(80, 0))
        self.currentTimeLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.currentTimeLabel.setObjectName("currentTimeLabel")
        self.horizontalLayout_4.addWidget(self.currentTimeLabel)

        self.timeSlider = QtWidgets.QSlider(self.centralWidget)
        self.timeSlider.setOrientation(QtCore.Qt.Horizontal)
        self.timeSlider.setObjectName("timeSlider")
        self.horizontalLayout_4.addWidget(self.timeSlider)
        self.totalTimeLabel = QtWidgets.QLabel(self.centralWidget)
        self.totalTimeLabel.setMinimumSize(QtCore.QSize(80, 0))
        self.totalTimeLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
        self.totalTimeLabel.setObjectName("totalTimeLabel")
        self.horizontalLayout_4.addWidget(self.totalTimeLabel)

#        self.verticalLayout.addLayout(self.horizontalLayout_4)         # ---

        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setSpacing(6)
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.previousButton = QtWidgets.QPushButton(self.centralWidget)
        self.previousButton.setText("")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("images/control-skip-180.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.previousButton.setIcon(icon)
        self.previousButton.setObjectName("previousButton")
        self.horizontalLayout_5.addWidget(self.previousButton)
        self.playButton = QtWidgets.QPushButton(self.centralWidget)
        self.playButton.setText("")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("images/control.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.playButton.setIcon(icon1)
        self.playButton.setObjectName("playButton")
        self.horizontalLayout_5.addWidget(self.playButton)
        self.pauseButton = QtWidgets.QPushButton(self.centralWidget)
        self.pauseButton.setText("")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("images/control-pause.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pauseButton.setIcon(icon2)
        self.pauseButton.setObjectName("pauseButton")
        self.horizontalLayout_5.addWidget(self.pauseButton)
        self.stopButton = QtWidgets.QPushButton(self.centralWidget)
        self.stopButton.setText("")
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap("images/control-stop-square.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.stopButton.setIcon(icon3)
        self.stopButton.setObjectName("stopButton")
        self.horizontalLayout_5.addWidget(self.stopButton)
        self.nextButton = QtWidgets.QPushButton(self.centralWidget)
        self.nextButton.setText("")
        icon4 = QtGui.QIcon()
        icon4.addPixmap(QtGui.QPixmap("images/control-skip.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.nextButton.setIcon(icon4)
        self.nextButton.setObjectName("nextButton")
        self.horizontalLayout_5.addWidget(self.nextButton)
        self.viewButton = QtWidgets.QPushButton(self.centralWidget)
        self.viewButton.setText("")
        icon5 = QtGui.QIcon()
        icon5.addPixmap(QtGui.QPixmap("images/application-image.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.viewButton.setIcon(icon5)
        self.viewButton.setCheckable(True)
        self.viewButton.setObjectName("viewButton")
        self.horizontalLayout_5.addWidget(self.viewButton)
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_5.addItem(spacerItem)
        self.label = QtWidgets.QLabel(self.centralWidget)
        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap("images/speaker-volume.png"))
        self.label.setObjectName("label")
        self.horizontalLayout_5.addWidget(self.label)
        self.volumeSlider = QtWidgets.QSlider(self.centralWidget)
        self.volumeSlider.setMaximum(100)
        self.volumeSlider.setProperty("value", 100)
        self.volumeSlider.setOrientation(QtCore.Qt.Horizontal)
        self.volumeSlider.setObjectName("volumeSlider")
        self.horizontalLayout_5.addWidget(self.volumeSlider)

#        self.verticalLayout.addLayout(self.horizontalLayout_5)          # ---

        self.horizontalLayout.addLayout(self.verticalLayout)
        MainWindow.setCentralWidget(self.centralWidget)
        self.menuBar = QtWidgets.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 484, 22))
        self.menuBar.setObjectName("menuBar")
        self.menuFIle = QtWidgets.QMenu(self.menuBar)
        self.menuFIle.setObjectName("menuFIle")
        MainWindow.setMenuBar(self.menuBar)
        self.statusBar = QtWidgets.QStatusBar(MainWindow)
        self.statusBar.setObjectName("statusBar")
        MainWindow.setStatusBar(self.statusBar)
        self.open_file_action = QtWidgets.QAction(MainWindow)
        self.open_file_action.setObjectName("open_file_action")
        self.menuFIle.addAction(self.open_file_action)
        self.menuBar.addAction(self.menuFIle.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Failamp"))
        self.currentTimeLabel.setText(_translate("MainWindow", "0:00"))
        self.totalTimeLabel.setText(_translate("MainWindow", "0:00"))
        self.menuFIle.setTitle(_translate("MainWindow", "FIle"))
        self.open_file_action.setText(_translate("MainWindow", "Open file..."))

def hhmmss(ms):
    # s = 1000
    # m = 60000
    # h = 360000
    h, r = divmod(ms, 36000)
    m, r = divmod(r, 60000)
    s, _ = divmod(r, 1000)
    return ("%d:%02d:%02d" % (h, m, s)) if h else ("%d:%02d" % (m, s))

class ViewerWindow(QMainWindow):
    state = pyqtSignal(bool)

    def closeEvent(self, e):
        # Извлечь состояние окна, чтобы обновить кнопку переключения просмотра.
        self.state.emit(False)

class PlaylistModel(QAbstractListModel):
    def __init__(self, playlist, *args, **kwargs):
        super(PlaylistModel, self).__init__(*args, **kwargs)
        self.playlist = playlist

    def data(self, index, role):
        if role == Qt.DisplayRole:
            media = self.playlist.media(index.row())
            return media.canonicalUrl().fileName()

    def rowCount(self, index):
        return self.playlist.mediaCount()

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)

#        self.player = QMediaPlayer()
        self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface)        # +

        self.player.error.connect(self.erroralert)
        self.player.play()

        # Setup the playlist.
        self.playlist = QMediaPlaylist()
        self.player.setPlaylist(self.playlist)

        # Добавить просмотрщик для воспроизведения видео, отдельное плавающее окно.
        self.viewer = ViewerWindow(self)
        self.viewer.setWindowFlags(self.viewer.windowFlags() | Qt.WindowStaysOnTopHint)
        self.viewer.setMinimumSize(QSize(480, 360))

        videoWidget = QVideoWidget()
        self.viewer.setCentralWidget(videoWidget)

#        self.verticalLayout.addWidget(videoWidget)                  # -
        self.verticalLayout.addWidget(self.viewer)                   # +
        self.verticalLayout.addLayout(self.horizontalLayout_4)       # +
        self.verticalLayout.addLayout(self.horizontalLayout_5)       # +

        self.player.setVideoOutput(videoWidget)

        # Connect control buttons/slides for media player.
        self.playButton.pressed.connect(self.player.play)
        self.pauseButton.pressed.connect(self.player.pause)
        self.stopButton.pressed.connect(self.player.stop)
        self.volumeSlider.valueChanged.connect(self.player.setVolume)

        self.viewButton.toggled.connect(self.toggle_viewer)
        self.viewer.state.connect(self.viewButton.setChecked)

        self.previousButton.pressed.connect(self.playlist.previous)
        self.nextButton.pressed.connect(self.playlist.next)

        self.model = PlaylistModel(self.playlist)
        self.playlistView.setModel(self.model)
        self.playlist.currentIndexChanged.connect(self.playlist_position_changed)
        selection_model = self.playlistView.selectionModel()
        selection_model.selectionChanged.connect(self.playlist_selection_changed)

        self.player.durationChanged.connect(self.update_duration)
        self.player.positionChanged.connect(self.update_position)
        self.timeSlider.valueChanged.connect(self.player.setPosition)

        self.open_file_action.triggered.connect(self.open_file)

        self.setAcceptDrops(True)

        self.show()

    def dragEnterEvent(self, e):
        if e.mimeData().hasUrls():
            e.acceptProposedAction()

    def dropEvent(self, e):
        for url in e.mimeData().urls():
            self.playlist.addMedia(
                QMediaContent(url)
            )

        self.model.layoutChanged.emit()

        # If not playing, seeking to first of newly added + play.
        if self.player.state() != QMediaPlayer.PlayingState:
            i = self.playlist.mediaCount() - len(e.mimeData().urls())
            self.playlist.setCurrentIndex(i)
            self.player.play()

    def open_file(self):
        path, _ = QFileDialog.getOpenFileName(self, "Open file", "",
                    "mp3 Audio (*.mp3);;Video (*.mp4;*.avi);;Movie files (*.mov)")

        if path:
            self.playlist.addMedia(
                QMediaContent(
                    QUrl.fromLocalFile(path)
                )
            )

        self.model.layoutChanged.emit()

    def update_duration(self, duration):
        print("!", duration)
        print("?", self.player.duration())

        self.timeSlider.setMaximum(duration)

        if duration >= 0:
            self.totalTimeLabel.setText(hhmmss(duration))

    def update_position(self, position):
        if position >= 0:
            self.currentTimeLabel.setText(hhmmss(position))

        # Disable the events to prevent updating triggering a setPosition event (can cause stuttering).
        self.timeSlider.blockSignals(True)
        self.timeSlider.setValue(position)
        self.timeSlider.blockSignals(False)

    def playlist_selection_changed(self, ix):
        # We receive a QItemSelection from selectionChanged.
        i = ix.indexes()[0].row()
        self.playlist.setCurrentIndex(i)

    def playlist_position_changed(self, i):
        if i > -1:
            ix = self.model.index(i)
            self.playlistView.setCurrentIndex(ix)

    def toggle_viewer(self, state):
        if state:
            self.viewer.show()
        else:
            self.viewer.hide()

    def erroralert(self, *args):
        print(args)

if __name__ == '__main__':
    app = QApplication([])
    app.setApplicationName("Failamp")
    app.setStyle("Fusion")

    # Fusion dark palette from https://gist.github.com/QuantumCD/6245215.
    palette = QPalette()
    palette.setColor(QPalette.Window, QColor(53, 53, 53))
    palette.setColor(QPalette.WindowText, Qt.white)
    palette.setColor(QPalette.Base, QColor(25, 25, 25))
    palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
    palette.setColor(QPalette.ToolTipBase, Qt.white)
    palette.setColor(QPalette.ToolTipText, Qt.white)
    palette.setColor(QPalette.Text, Qt.white)
    palette.setColor(QPalette.Button, QColor(53, 53, 53))
    palette.setColor(QPalette.ButtonText, Qt.white)
    palette.setColor(QPalette.BrightText, Qt.red)
    palette.setColor(QPalette.Link, QColor(42, 130, 218))
    palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
    palette.setColor(QPalette.HighlightedText, Qt.black)
    app.setPalette(palette)
    app.setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }")

    window = MainWindow()
    app.exec_()


text:
Q: dot product and relationship to cosine of its angle In our class, we defined that the term  $$ \cos(\alpha)=\frac{\langle x,y \rangle}{\sqrt{\langle x,x\rangle \langle y,y \rangle}}$$ is equal to the cosine of the angle enclosed by $x$ and $y$. However, we restricted ourself to Euclidean vector spaces.
Now I am wondering: is this definition is reasonable for all unitary vector spaces too?

A: In a unitary vector space, you can certainly define this, but it is (1) not necessarily real, and therefore not necessarily the cosine of an angle, and (2) it isn't symmetric, since $\left<x,y\right>\neq \left<y,x\right>$ in general.
If you do define $$\cos(x,y)=\frac{\left<x,y\right>}{\sqrt{\left<x,x\right>\left<y,y\right>
}}$$ you get $|\cos(x,y)|\leq 1$ and $\cos(y,x)=\overline{\cos(x,y)}$, and $\cos(\alpha x, x)=\frac{\alpha}{|\alpha|}$ for $\alpha\in\mathbb C\setminus\{0\}$.
So you can use this as a generalized notion of the cosine function.
See: http://en.wikipedia.org/wiki/Inner_product_space for some other ideas. There, they define the "angle" between complex vectors in $[0,\pi/2]$ as:
$$\text{angle}(x,y)=\arccos |\cos(x,y)|$$
The real part of $\cos(x,y)$ plays the part of of $\cos$ in a unitary "law of cosines."
$$\|x+y\|^2 = \|x\|^2+\|y\|^2 + 2\|x\|\|y\|\Re \cos(x,y)$$
Indeed, if you take $\mathbb C^n$ and give it the "standard" complex inner product, the real part of this inner product is just that "standard" inner product on $\mathbb R^{2n}$.
The imaginary part of this dot product is the sum of the (oriented) areas of the parallelograms formed by the corresponding pairs of complex numbers.  That gives some intuition, perhaps, for the geometry of the "complex part" of the unitary dot product.


text:
Q: Is it ok to use 4k images as an Android-Layout background? I used a 4k image as my root layout's background, it was running fine in my phone but very slow on a tablet, my profiler's memory indicator was high, everything worked fine when i removed the 4k image But i wanna know why that happened and how to use 4k images more efficient ?

A: put image in asset then Try this code
rootview.setBackground(getDrawableFromAssets("my4k.jpg"));

public Drawable getDrawableFromAssets(String img_Name) {

    AssetManager assetManager = getAssets();
    InputStream str = assetManager.open(img_Name);
    Bitmap bitmap = BitmapFactory.decodeStream(str);
    return bitmap new BitmapDrawable(getResources(), bitmap);
}


text:
Q: FXG Editor for Flex The only FXG editor I've seen for Flex is by 7jigen, works online or
as a Flex app.
Does anyone know of a different one? It can be done in Illustrator I think, but that doesn't really offer a simple export to Flex type option, just gives coordinates.

A: I have used this process to generate a ton of FXG assets that I have imported into my Flex projects.

1. Draw the shape in Flash CS5
2. Break the shape apart (Ctrl+B)
3. Select the shape
4. File -> Export -> Export Selection
5. Save as FXG

You can then import them directly into Flex and voila! Good to go!

A: Use Inkscape SVG editor: it will allows you to convert svg to fxg starting version 0.49 thanks to the svg2fxg plug-in.
In the mean time (version 0.48) you can install the svg2fxg plug-in manually as explained by RIAGrande:

*

*Install Inkscape http://inkscape.org/download/

*Get the 2 svg2fxg plug-in files from here (from head repository):

http://bazaar.launchpad.net/~inkscape.dev/inkscape/trunk/view/head:/share/extensions/svg2fxg.inx
http://bazaar.launchpad.net/~inkscape.dev/inkscape/trunk/view/head:/share/extensions/svg2fxg.xsl

*and copy them in Inkscape extension folder (C:\Program Files (x86)\Inkscape\share\extensions on Windows 7)
You can now start Inkscape and will get a new "File -> Save As -> Flash XML graphics (*.svg)" entry.
I successfully tested it and used the fxg generated assets in on IPhone: it works fine :-)

A: As far as I know your best bet (if you don't want to use Illustrator) is to grab Inkscape and install the "save as FXG" plug-in. Hats off to JazzyNico for writing what is basically a monster SVG to FXG "XSL Transform" (i.e. XSLT).
How to install:

*

*Install Inkscape.

*Grab the plug-in files svg2fxg.inx and svg2fxg.xsl.

*Drop both files in your Inkscape "extensions" folder.

*

*In GNU/Linux: $HOME/.config/inkscape/extensions

*In Windows: C:\Documents and Settings\User\Application Data\Inkscape\extensions

*In OSX: /Applications/Inkscape.app/Contents/Resources/extensions

*Restart Inkscape and you'll find a new FXG entry in the "File > Save As" dialog.
This plugin has been a boon for me and my work, since I've become quite comfortable with Inkscape over the years.
Unfortunately (and this may just be my setup), I've found that whenever I save as FXG, a few minutes later Inkscape crashes out (I really should post a bug report). Just in case you have the same problem, make sure you go to the "Save" preferences and turn on auto-backup. Also, keep in mind that certain constructs in SVG have no equivalent in FXG. Don't ask me what they are, I honestly can't remember.

A: Firstly, RIAGrande's answer is correct. I followed his steps and they worked. Here is a little more information for future reference:
The Inkscape bug report for FXG with downloads available under Patches can be found at
https://bugs.launchpad.net/inkscape/+bug/625140. These files (when uncompressed) should be copied to the location mentioned by RIAGrande
I made my little icon, but he exported FXG file was not indented, so used http://xmlindent.com/ to fomat the file, Downloaded, copied to my project in Flash Builder and renamed as .fxg file.
To use the FXG file, did the following:
<s:Group>
    <local:fxgInkscapeIcon height="100" width="100" x="50" y="50"/>
</s:Group>

For posterity, here is the icon and resulting Inkscape FXG code:

<?xml version="1.0" encoding="UTF-8"?>
<Graphic xmlns="http://ns.adobe.com/fxg/2008" xmlns:fxg="http://ns.adobe.com/fxg/2008" xmlns:d="http://ns.adobe.com/fxg/2008/dt" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:svg="http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd" version="2.0" viewWidth="16" viewHeight="16">
    <mask>
        <Group>
            <Rect width="16" height="16">
                <fill>
                    <SolidColor color="#ffffff" alpha="1"/>
                </fill>
            </Rect>
        </Group>
    </mask>
    <!--Unknown tag: defs-->
    <!--Unknown tag: sodipodi:namedview-->
    <!--Unknown tag: metadata-->
    <Group id="layer1">
        <Group id="g3219">
            <Path data="m 3.4494939 4.7212002 2.7832822 -2.6455548 0 3.6343941 -2.7832822 1.0225951 z" winding="evenOdd" id="path3231">
                <fill>
                    <SolidColor color="#E9E9FF" alpha="1"/>
                </fill>
            </Path>
            <Path data="m 2.4777228 4.4673265 0 2.1671775 0.9717711 0.098131 0 -2.0114344 z" winding="evenOdd" id="path3221">
                <fill>
                    <SolidColor color="#353564" alpha="1"/>
                </fill>
            </Path>
            <Path data="M 2.4777228 4.4673265 4.7752476 1.1915748 6.2327761 2.0756454 3.4494939 4.7212002 z" winding="evenOdd" id="path3223">
                <fill>
                    <SolidColor color="#4D4D9F" alpha="1"/>
                </fill>
            </Path>
            <Path data="M 2.4777228 6.634504 4.7752476 5.3683167 6.2327761 5.7100395 3.4494939 6.7326346 z" winding="evenOdd" id="path3229">
                <fill>
                    <SolidColor color="#AFAFDE" alpha="1"/>
                </fill>
            </Path>
            <Path data="m 4.7752476 1.1915748 0 4.1767419 1.4575285 0.3417228 0 -3.6343941 z" winding="evenOdd" id="path3227">
                <fill>
                    <SolidColor color="#D7D7FF" alpha="1"/>
                </fill>
            </Path>
            <Path data="m 2.4777228 4.4673265 2.2975248 -3.2757517 0 4.1767419 -2.2975248 1.2661873 z" winding="evenOdd" id="path3225">
                <fill>
                    <SolidColor color="#8686BF" alpha="1"/>
                </fill>
            </Path>
        </Group>
        <Group id="g3233">
            <Path data="M 2.7930693 12.065864 4.7752475 14.951316 6.232776 14.048691 3.8532769 11.73947 z" winding="evenOdd" id="path3243">
                <fill>
                    <SolidColor color="#AFAFDE" alpha="1"/>
                </fill>
            </Path>
            <Path data="m 2.7930693 9.5192088 0 2.5466552 1.0602076 -0.326394 0 -2.3422182 z" winding="evenOdd" id="path3235">
                <fill>
                    <SolidColor color="#353564" alpha="1"/>
                </fill>
            </Path>
            <Path data="m 3.8532769 9.3972518 2.3794991 0.8628392 0 3.7886 -2.3794991 -2.309221 z" winding="evenOdd" id="path3245">
                <fill>
                    <SolidColor color="#E9E9FF" alpha="1"/>
                </fill>
            </Path>
            <Path data="M 2.7930693 9.5192088 4.7752475 10.597357 6.232776 10.260091 3.8532769 9.3972518 z" winding="evenOdd" id="path3237">
                <fill>
                    <SolidColor color="#4D4D9F" alpha="1"/>
                </fill>
            </Path>
            <Path data="m 4.7752475 10.597357 0 4.353959 1.4575285 -0.902625 0 -3.7886 z" winding="evenOdd" id="path3241">
                <fill>
                    <SolidColor color="#D7D7FF" alpha="1"/>
                </fill>
            </Path>
            <Path data="m 2.7930693 9.5192088 1.9821782 1.0781482 0 4.353959 -1.9821782 -2.885452 z" winding="evenOdd" id="path3239">
                <fill>
                    <SolidColor color="#8686BF" alpha="1"/>
                </fill>
            </Path>
        </Group>
        <Group id="g3247">
            <Path data="M 4.7301981 10.623124 8.739604 12.846535 10.29713 11.806839 6.1815487 10.285313 z" winding="evenOdd" id="path3257">
                <fill>
                    <SolidColor color="#800080" alpha="1"/>
                </fill>
            </Path>
            <Path data="m 4.7301981 5.3683167 0 5.2548073 1.4513506 -0.337811 0 -4.5780822 z" winding="evenOdd" id="path3249">
                <fill>
                    <SolidColor color="#800080" alpha="1"/>
                </fill>
            </Path>
            <Path data="M 6.1815487 5.7072308 10.29713 4.18074 l 0 7.626099 -4.1155813 -1.521526 z" winding="evenOdd" id="path3259">
                <fill>
                    <SolidColor color="#800080" alpha="1"/>
                </fill>
            </Path>
            <Path data="M 4.7301981 5.3683167 8.739604 3.1376518 10.29713 4.18074 6.1815487 5.7072308 z" winding="evenOdd" id="path3251">
                <fill>
                    <SolidColor color="#800080" alpha="1"/>
                </fill>
            </Path>
            <Path data="m 8.739604 3.1376518 0 9.7088832 1.557526 -1.039696 0 -7.626099 z" winding="evenOdd" id="path3255">
                <fill>
                    <SolidColor color="#800080" alpha="1"/>
                </fill>
            </Path>
            <Path data="m 4.7301981 5.3683167 4.0094059 -2.2306649 0 9.7088832 -4.0094059 -2.223411 z" winding="evenOdd" id="path3253">
                <fill>
                    <SolidColor color="#800080" alpha="1"/>
                </fill>
            </Path>
        </Group>
        <Path data="M 6.7296153 11.713583 4.7609632 10.626386 4.7586994 8.0107245 4.7564356 5.3950627 4.88976 5.2964917 c 0.073328 -0.054214 0.1452487 -0.098571 0.1598229 -0.098571 0.021999 0 0.9221556 -0.4946803 1.1484369 -0.6311227 C 6.2351856 4.544388 6.5155757 4.3883429 6.8211089 4.2200312 7.1266421 4.0517194 7.4712708 3.8603428 7.5869505 3.7947497 7.8155129 3.6651495 8.0560806 3.5353764 8.3378713 3.3896691 8.4369802 3.3384223 8.5536701 3.2649336 8.5971821 3.226361 c 0.043512 -0.038573 0.089217 -0.060028 0.1015661 -0.047679 0.012349 0.012349 0.017293 2.1823735 0.010986 4.822276 l -0.011467 4.7998228 -1.968652 -1.087198 z" winding="nonZero" id="path3261">
            <fill>
                <SolidColor color="#FF00FF" alpha="1"/>
            </fill>
        </Path>
        <Path data="m 2.5039603 5.4963957 c 0 -0.6060218 0.015204 -1.1086152 0.033787 -1.1168743 0.052529 -0.023346 0.2815594 -0.3415436 0.2815594 -0.3911774 0 -0.024366 0.015204 -0.051058 0.033787 -0.059318 0.052529 -0.023346 0.2815594 -0.3415436 0.2815594 -0.3911774 0 -0.024366 0.015204 -0.051059 0.033787 -0.059318 C 3.2209698 3.455185 3.45 3.1369877 3.45 3.0873539 c 0 -0.024366 0.015204 -0.051058 0.033787 -0.059318 0.052529 -0.023346 0.2815594 -0.3415435 0.2815594 -0.3911773 0 -0.024366 0.01689 -0.051059 0.037534 -0.059318 0.020644 -0.00826 0.2131642 -0.26842 0.4278232 -0.5781353 0.214659 -0.3097154 0.4207638 -0.6027185 0.4580106 -0.6511181 0.060562 -0.078696 0.067721 0.1266999 0.067721 1.942875 0 1.5702733 -0.012771 2.0412475 -0.056312 2.0766116 C 4.6691522 5.3929299 4.2485024 5.6303359 3.7653465 5.8953434 3.2821906 6.1603507 2.800724 6.4269177 2.6954207 6.4877142 l -0.1914604 0.1105394 0 -1.1018579 z" winding="nonZero" id="path3263">
            <fill>
                <SolidColor color="#00FF00" alpha="1"/>
            </fill>
        </Path>
        <Path data="M 3.7705821 13.453243 2.8195554 12.06797 2.8194311 10.814691 2.8193069 9.5614117 3.1684406 9.7516131 c 0.1920235 0.1046107 0.5473426 0.2988019 0.789598 0.4315359 0.2422554 0.132735 0.4644582 0.246219 0.493784 0.252187 0.055299 0.01126 0.1254459 0.05844 0.2386022 0.160481 0.056179 0.05066 0.066011 0.371061 0.066011 2.151114 0 1.150371 -0.00784 2.091584 -0.017413 2.091584 -0.00958 0 -0.4453754 -0.623373 -0.9684401 -1.385272 z" winding="nonZero" id="path3265">
            <fill>
                <SolidColor color="#FF0000" alpha="1"/>
            </fill>
        </Path>
        <Path data="m 2.5251337 5.4884758 0.033034 -1.06093 0.1780729 -0.256768 C 2.8341803 4.0295554 2.9845892 3.8126485 3.0704822 3.6887623 3.1563752 3.5648762 3.2921089 3.3701098 3.3721127 3.2559482 3.4521166 3.1417866 3.6000512 2.9289277 3.7008563 2.7829284 3.8016614 2.6369291 4.0652011 2.2657195 4.2864999 1.958018 l 0.4023615 -0.5594572 0.022525 0.942378 c 0.012389 0.5183079 0.012389 1.4067712 0 1.9743628 L 4.6888614 5.3472865 3.6144 5.9483464 C 3.0234462 6.2789291 2.5291749 6.5494059 2.5160193 6.5494059 c -0.013156 0 -0.00905 -0.4774184 0.00911 -1.0609301 z" winding="nonZero" id="path3267">
            <fill>
                <SolidColor color="#FF0000" alpha="1"/>
            </fill>
        </Path>
    </Group>
</Graphic>


text:
Q: Как проверить наличие русского или английского текста? Нужно добавить фильтр, чтобы отображать записи либо с русскими, либо с английскими заголовками.
Сейчас на ум приходит только проверка регулярным выражением:
([а-яА-ЯеЁ])
([a-zA-Z])

Нормальное ли это решение? Или есть какой-нибудь лучший (для Ruby) вариант? Или же даже можно как-то в SQL (PostgreSQL) запросе сделать проверку?

A: Очень даже можно прямо в PostgreSQL
Вот пример скоупа для ActiveRecord:
scope :title_matching_regex, -> (r) { where('title ~ :regex', regex: r) }

Решение на уровне Ruby может быть разве что пост-процессингом результатов из PostgreSQL, но поскольку оно будет делать примерно то же самое, проще отобрать нужные данные сразу до получения их из БД.
У PostgreSQL с кириллицей получше, чем у Ruby, но я всё равно не уверен, что с кириллицей оно отработает так же гладко. Проверьте.