text:
Q: Difference in Cyrillic font series I would appreciate if someone could help me in solving a "font puzzle".
I am trying different ways  to typeset a text in cyrillic.
First example of code, compiled with pdfLaTeX:
\documentclass[14pt]{extreport}
\usepackage[T2A]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[russian]{babel}
%--------------------------------------
\begin{document}
    Еще недавно ему часто
\end{document}

Second example of code, compiled with LuaLaTeX:
\documentclass[14pt]{extreport}
\usepackage{fontspec}
\usepackage{polyglossia}
\usepackage{unicode-math}
\setmainlanguage{russian}
\setmainfont{CMU Serif}
%------------------------
\begin{document}
    Еще недавно ему часто
\end{document}

The output can be seen below:

The second fragment of code produces somewhat "thicker" type of font, whereas the first fragment, compiled with pdfLaTeX, gives a "thinner", more elegant letters(seen below in the picture).
My questions:
1) what are reasons for this difference?
2) Is it possible to obtain same "thin" font, albeit with LuaLaTeX-suitable code?

A: An image is worth a thousand words

What's the meaning of the image?
It's a tabular; the first column has a description, the second column images produces by the files described below.
The source is
\documentclass{article}
\usepackage{graphicx}

\begin{document}

\begin{tabular}{@{}ll@{}}
Optical: & \raisebox{-3pt}{\includegraphics{testcyro.pdf}} \\[3pt]
Scaled: & \raisebox{-3pt}{\includegraphics{testcyrs.pdf}} \\[3pt]
CMU: & \raisebox{-3pt}{\includegraphics{testcyru.pdf}}
\end{tabular}

\end{document}

In the "optical" line, the font used is larm1440, which is not just the font at 10pt scaled by 14.4% like in the "scaled" line.
Note that the "CMU" line is the same as the "scaled" line.
Optical sizes are not the same as scaling. CMU Serif is only available at 10pt design, the other sizes are obtained by scaling; conversely, larm is available at several optical sizes. The answer to your second question is no, I'm afraid: there's no free OpenType Cyrillic font supporting optical sizes, as far as I know.
The codes
testcyro.tex
\documentclass{standalone}
\usepackage[T2A]{fontenc}
\usepackage[utf8]{inputenc}
\begin{document}

\fontsize{14}{14}\selectfont
Еще недавно ему часто

\end{document}

testcyrs.tex
\documentclass{standalone}
\usepackage[T2A]{fontenc}
\usepackage[utf8]{inputenc}
\begin{document}

\font\test=larm1000 at 14pt \test

Еще недавно ему часто

\end{document}

testcyru.tex
\documentclass{standalone}
\usepackage{fontspec}
\setmainfont{CMU Serif}

\begin{document}

\fontsize{14}{14}\selectfont
Еще недавно ему часто

\end{document}


text:
Q: Flask-Migrate multidb foreign key to different bind can not find target table I am trying to use Flask-Migrate with multiple databases using the flask-sqlalchemy __binds__ feature. When trying to establish a foreign key between two different binds, flask db migrate fails with the error sqlalchemy.exc.NoReferencedTableError, i.e. can not find the table to establish the foreign key.
I am using Postgres databases with bind keys db1 and db2. Note that this error does not occur if the foreign key is to a table on the same bind (database).
Here is a sample app that demonstrates the problem:
app/models.py
from app import db

class People(db.Model):
    __bind_key__ = 'db1'

    id = db.Column(db.Integer, primary_key=True)

class Cats(db.Model):
    __bind_key__ = 'db2'

    id = db.Column(db.Integer, primary_key=True)
    people_id = db.Column(db.Integer, db.ForeignKey('people.id'))
    dogs_id = db.Column(db.Integer, db.ForeignKey('dogs.id'))

class Dogs(db.Model):
    __bind_key__ = 'db2'

    id = db.Column(db.Integer, primary_key=True)

app/init.py
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app,db)

from app import models

A config.py file is used to set the sqlalchemy binds from environment variables:
config.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
    SQLALCHEMY_BINDS = {
        'db1': os.environ.get('DATABASE_1_URL'),
        'db2': os.environ.get('DATABASE_2_URL')}

In this example, the foreign key in the Cats table to the Dogs table is established with no errors:
dogs_id = db.Column(db.Integer, db.ForeignKey('dogs.id'))
However doing the same thing to the People table,
people_id = db.Column(db.Integer, db.ForeignKey('people.id'))
results in the error when running flask db migrate:
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'cats.people_id' could not find table 'people' with which to generate a foreign key to target column 'id'

Threads, such as this one indicate the foreign key should be established by including the schema name, or bind key:
people_id = db.Column(db.Integer, db.ForeignKey('db1.people.id'))

however, this results in the same error:
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'cats.people_id' could not find table 'db1.people' with which to generate a foreign key to target column 'id'

Any suggestions for this would be greatly appreciated!

A: The problem is that you cannot define foreign keys across databases. If you can move all these tables into a single database, maybe putting them in different schemas, then you'll be fine.

A: You should set schema and set the foreignkey with it.
class People(db.Model):
    __bind_key__ = 'db1'
    __table_args__ = {'schema': 'db1'}

    id = db.Column(db.Integer, primary_key=True)

class Cats(db.Model):
    __bind_key__ = 'db2'
    __table_args__ = {'schema': 'db2'}

    id = db.Column(db.Integer, primary_key=True)
    people_id = db.Column(db.Integer, db.ForeignKey('db1.people.id'))
    dogs_id = db.Column(db.Integer, db.ForeignKey('db2.dogs.id'))

class Dogs(db.Model):
    __bind_key__ = 'db2'
    __table_args__ = {'schema': 'db2'}

    id = db.Column(db.Integer, primary_key=True)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Installed standalone Python 3.7 after Anaconda Python 3.7, how to access old/specific pip? I'm relatively new to Python. I installed 3.7 as part of Anaconda package, but it wasn't working with PowerBI since it wasn't able to execute a certain batch file that started the conda venv. A workaround I read about was to install a regular Python 3.7 outside of conda and use that interpreter instead.
It successfully installed, and it was added to path, and when I do pip-list in my command prompt I see only the packages for the new pip which makes sense. How do I access the old pip for my conda python where it had all the packages?

A: Do you mean how do you install packages in your default Python environment outside of Conda? To achieve this you'd just run pip install to install the packages fresh. If you want the list of previously install items you can use pip list.
conda activate myoldenv
pip freeze > requirements.txt

You can then open requirements.txt to see which packages that you want.
However if you want PBI to work well with Python the cleanest way in my opinion is to setup within a new conda env. The point of Conda is to have different envs for different use cases.
conda create --name VisualisationPBI python=3.7
conda activate VisualisationPBI
pip install seaborn #installs seaborn and dependencies including numpy, pandas and mpl

In PBI options set your Python home directory to "Other" then select your conda directory, probably:
C:\Users\YOURNAME.conda\envs\VisualisationPBI
Conda works with PBI, but you need to Pip install the key packages in the library, instead of conda install. As here: https://community.powerbi.com/t5/Desktop/Power-BI-Python-with-Anaconda-missing-dependency/td-p/665102


text:
Q: GIT - Reduce Size of Repo After Deleting stuff I removed tons of images from my GIT repository and yet my project size still the same. I only have one Branch.
How do I cleanup the size of the git repo but making sure I keep the commit history there?
My GIT is remote.


text:
Q: CodeIgniter 404 Page Not Found htaccess wamp I'm working on a CodeIgniter application that was previously developed.
The issue that I'm getting is a page not found and I have installed on wamp.
Here is the .htaccess file that I'm currently using for the app (not the wamp one).
    # Turn on URL rewriting
    RewriteEngine On

    # Allow these directories and files to be displayed directly:
    RewriteRule ^(index\.php|css|js|fonts|images|uploads|audio) - [PT,L]

    # Rewrite all other URLs to index.php/URL
    # RewriteRule .* index.php?/$0 [PT,L,QSA]

    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]

How do I go about fixing the 404 issue? Would I change the wamp .htaccess file?
Thank you,
Kevin Davis

A: # Turn on URL rewriting
RewriteEngine On
RewriteBase /FOLDERNAME/    #Add your foldername in place of FOLDERNAME

# Allow these directories and files to be displayed directly:
RewriteRule ^(index\.php|css|js|fonts|images|uploads|audio) - [PT,L]

# Rewrite all other URLs to index.php/URL
# RewriteRule .* index.php?/$0 [PT,L,QSA]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

A: Try using below .htacccess file.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Hope this can help you.


text:
Q: BitmapDrawable does not respect scaleType on view I want to display an image synchronously on a view, and I am using Universal Image Loader:
https://github.com/nostra13/Android-Universal-Image-Loader
On async call the library displays the image properly. Though, doing something like this:
myImageView.setBackground(new BitmapDrawable(getApplicationContext().getResources(), ImageLoader.getInstance().loadImageSync("path/to/image")));

The image gets displayed, ignoring my scaleType on layout, which is centerCrop. I want to do this without having to process the image which would increase the load time. I have been searching Google for 4 hours now without luck. I landed on some threads in here but they are not helpful.
Thank you for your time.

A: You should use setImageDrawable() instead of setBackground(). Using the image as a background will always ignore the scale type.
myImageView.setImageDrawable(new BitmapDrawable(getApplicationContext().getResources(), ImageLoader.getInstance().loadImageSync("path/to/image")));


text:
Q: Display name along with the count in descending order in Django I have two models within my models.py file as described below:
class Company(models.Model):
  company_name = models.CharField(max_length=100)

  def __str__(self):
    return f"{self.company_name}"

Class Jobs(models.Model):
  job_title = models.CharField(max_length=100)
  job_company = models.ForeignKey(Company, models.on_delete=CASCADE)
  job_location = models.CharField(max_length=50)
  job_salary = models.CharField(max_length=20)

  def __str__(self):
    return f"{self.job_title}"

The data present within these tables is as shown below:
  COMPANY
--------------------
|   COMPANY_NAME   |
--------------------
|   Google         |
|   Facebook       |
|   Microsoft      |
|   Amazon         |
--------------------

  JOBS
-------------------------------------------------------------------
|   JOB_TITLE   |  JOB_COMPANY  |   JOB_LOCATION   |  JOB_SALARY  |
-------------------------------------------------------------------
| ENGINEER      | GOOGLE        | SAN JOSE         |  5000        |
| MANAGER       | AMAZON        | NYC              |  8000        |
| DELIVERY MAN  | AMAZON        | WASHINGTON DC    |  2000        |
| ACCOUNTANT    | MICROSOFT     | SFO              |  4000        |
| SALES LEAD    | GOOGLE        | SFO              |  5000        |
| DESIGNER      | GOOGLE        | NYC              |  3500        |
| CHEF          | GOOGLE        | NYC              |  2500        |
-------------------------------------------------------------------

I would like to display the following output on my template:
COMPANY NAME ALONG WITH THE NUMBER OF JOBS BEING OFFERED AT THE COMPANY IN DESCENDING ORDER AS SHOWN BELOW.
GOOGLE (4)
AMAZON (2)
MICROSOFT (1)

Thank you so much for your time and help!

A: You can use Django's Count aggregation on a queryset to accomplish this. In your Views.py do something like this:
from django.db.models import Count

queryset = MyModel.objects.all().annotate(count = Count('Google'))
dict1= {}
for each in queryset:
   #print(each.my_charfield, each.count)
   context[each.my_charfield] = each.count

return render(request, 'some.html', context=dict1)

In the template access it like
{% for key, value in dict1.items %}
     {{key}} ({{value}})
{% endfor %}

A: Within the views.py file:
def company(request):
    comp_details = Company.objects.annotate(jobs=Count('job')).order_by('-jobs')[:10]
    return render(request, 'index.html', {'comp_details': comp_details})

Within the index.html file:
{% for company in comp_details %}
   {{ company.name }}
{% endfor %}

This would display the Top 10 companies, based on the number of jobs being offered by them.


text:
Q: A basic question about how to apply the gauge covariant derivative in Yang-Mills theory I am sorry if this question is too stupid...
We know that Yang-Mills equation (without source) can be written as
$$D^\mu F_{\mu\nu}=0,\tag{1}$$
where $$D^{\mu}=\partial^\mu-ig A^{\mu}$$
and $$A^\mu=A^{\mu a} T^a,\\
F_{\mu\nu}=F_{\mu\nu}^a T^a.$$
Here $T^a$ are the generators of the gauge group and satisfy
$$[T^a,T^b]=if^{abc}T^c. \tag{2}$$
So far, everything is fine. But usually, we also say that Eq. (1) can be written as (see, e.g.,
wikipedia)
$$\partial^\mu F_{\mu\nu}^a+g f^{abc}A^{\mu b}F^{c}_{\mu\nu}=0.$$
I was wondering how to derive this equation from Eq. (1). From Eq. (1), we have
$$(\partial^\mu-igA^{\mu a}T^a)(F^b_{\mu\nu}T^b)=0.$$
So we have
$$-igA^{\mu a}T^a F^b_{\mu\nu}T^b{\stackrel{?}{=}}g f^{abc} A^{\mu a}F^b_{\mu\nu} T^c.$$
Apparently, relation (2) has been used. But how can we use this relation? How can I see that the "a" and "b" are antisymmetric in $A^{\mu a} F^b_{\mu\nu}$ such that we can take $T^a T^b\rightarrow T^{[a}T^{b]}=[T^a,T^b]/2$? Also, what about the factor $1/2$ here?

A: *

*If an object, say, a field $\phi\in V$ lives in a Lie algebra representation $\rho: \mathfrak{g}\to {\rm End}(V)$, then it is implicitly understood that the gauge covariant derivative
$$D_{\mu}~=~\partial_{\mu}-ig~A_{\mu}\tag{1}$$
should be interpreted as
$$D_{\mu}\phi~=~\partial_{\mu}\phi-ig~\rho(A_{\mu})\phi.\tag{2}$$
If $\Phi\in {\rm End}(V)$ is (isomorphic to) a matrix-valued field, then the gauge covariant derivative is
$$D_{\mu}\Phi~=~\partial_{\mu}\Phi-ig~[\rho(A_{\mu}),\Phi]_C,\tag{3}$$
where $[\cdot,\cdot]_C$ denotes the commutator.

*In particular, since the field strength $F_{\nu\lambda}\in\mathfrak{g}$ is Lie algebra valued, the gauge covariant derivative is
$$\begin{align}D_{\mu}F_{\nu\lambda}
~=~&\partial_{\mu}F_{\nu\lambda}-ig~{\rm ad}(A_{\mu})F_{\nu\lambda}\cr
~=~&\partial_{\mu}F_{\nu\lambda}-ig~[A_{\mu},F_{\nu\lambda}],\end{align}\tag{4}$$
where ${\rm ad}:\mathfrak{g}\to {\rm End}(\mathfrak{g})$ denotes the adjoint representation.
In a Lie-algebra representation $\rho: \mathfrak{g}\to {\rm End}(V)$, this becomes
$$\begin{align}
D_{\mu}\rho(F_{\nu\lambda})
~=~&\partial_{\mu}\rho(F_{\nu\lambda})-ig~\rho([A_{\mu},F_{\nu\lambda}])\cr
~=~&\partial_{\mu}\rho(F_{\nu\lambda})-ig~[\rho(A_{\mu}),\rho(F_{\nu\lambda})]_C,\end{align}\tag{5}$$
where $[\cdot,\cdot]$ denotes the Lie bracket. Be aware that the representation map $\rho$ is often implicitly implied.


text:
Q: Match and extract the ID of only those Date rows that have at least one value outside of a specified range I have a data frame that has a few date columns.
    Index Measurement       Date Measure.1     Date.1 Measure.2     Date.2 Measure.3     Date.3
1       1        56.0 2018-03-16         2 2018-03-23        12 2018-03-29      22.0 2018-04-05
2       2        56.0 2018-03-16        78 2018-03-23     41234 2018-03-29      12.0 2018-04-05
3      12        65.0       <NA>        54 2018-03-23        35       <NA>     323.0 2018-04-05
4      15       129.1 2018-03-16        78 2018-03-23        12 2018-03-29       2.0 2018-04-05
5      22        56.0 2018-03-16       786 2018-03-23       234 2018-03-29      21.0       <NA>
6     567          NA 2018-03-16        34 2018-03-23         4 2018-03-29     545.0 2018-04-21
7      75         5.0 2018-03-16        52 2018-03-23         3 2018-03-29       5.0 2018-04-05
8     563        12.0 2018-03-16        43 2018-03-23        34 2018-03-29       5.0 2018-04-05
9     436        12.0 2018-03-16         3 2018-03-23       123 2018-03-29     213.0 2018-04-05
10  34533        56.0 2018-03-16        43 2018-03-23        32 2018-03-29       5.0 2018-04-25
11 234234        76.0 2018-03-16       234 2018-03-31       324 2018-05-06       5.0 2018-04-05
12   6643        76.0 2018-03-16        23 2018-03-23       123 2018-03-29       0.2 2018-04-11

Here is the code to load my data (small sample):
structure(list(Index = c(1L, 2L, 12L, 15L, 22L, 567L, 75L, 563L,
436L, 34533L, 234234L, 6643L), Measurement = c(56, 56, 65, 129.1,
56, NA, 5, 12, 12, 56, 76, 76), Date = structure(c(17606, 17606,
NA, 17606, 17606, 17606, 17606, 17606, 17606, 17606, 17606, 17606
), class = "Date"), Measure.1 = c(2L, 78L, 54L, 78L, 786L, 34L,
52L, 43L, 3L, 43L, 234L, 23L), Date.1 = structure(c(17613, 17613,
17613, 17613, 17613, 17613, 17613, 17613, 17613, 17613, 17621,
17613), class = "Date"), Measure.2 = c(12L, 41234L, 35L, 12L,
234L, 4L, 3L, 34L, 123L, 32L, 324L, 123L), Date.2 = structure(c(17619,
17619, NA, 17619, 17619, 17619, 17619, 17619, 17619, 17619, 17657,
17619), class = "Date"), Measure.3 = c(22, 12, 323, 2, 21, 545,
5, 5, 213, 5, 5, 0.2), Date.3 = structure(c(17626, 17626, 17626,
17626, NA, 17642, 17626, 17626, 17626, 17646, 17626, 17632), class = "Date")), .Names = c("Index",
"Measurement", "Date", "Measure.1", "Date.1", "Measure.2", "Date.2",
"Measure.3", "Date.3"), row.names = c(NA, -12L), class = "data.frame")

I need to look at the adjacent Date columns in a row-wise manner and the difference between each adjacent date cell should not be more than 9 days and not less than 3 days.
I can achieve this in the following way:
diffdate_table <- df[ , grep( "Date" , names( df ) ) ] %>% rowwise() %>% diff.Date

The output of the code above will be:
> diffdate_table
    Date.1  Date.2   Date.3
1   7 days  6 days   7 days
2   7 days  6 days   7 days
3  NA days NA days  NA days
4   7 days  6 days   7 days
5   7 days  6 days  NA days
6   7 days  6 days  23 days
7   7 days  6 days   7 days
8   7 days  6 days   7 days
9   7 days  6 days   7 days
10  7 days  6 days  27 days
11 15 days 36 days -31 days
12  7 days  6 days  13 days

QUESTION.
How can I extract the Index (a column in the above dataset) of those rows that have at least one difference that is more than 9 days and less than 3 as calculated in diffdate_table?

A: Interesting question, plus I'd never seen diff.Date before. Here's two dplyr ways to do it. Both get the same result, it's just a matter of whether you want to work with the data in long or wide shape to do the diffs.
The first version follows the way you set up, but I had to do a couple weird steps to make sure the index didn't get dropped. There might be a better way to do that.
The second gathers everything into a long shape from the beginning, uses lag and just a bare subtraction of dates.
Both then group by Index and count the number of differences with your criteria. Hope that helps!
library(tidyverse)

diffs1 <- df %>%
    column_to_rownames("Index") %>%
    select_at(vars(starts_with("Date"))) %>%
    diff.Date() %>%
    rownames_to_column("Index") %>%
    mutate(Index = as.integer(Index)) %>%
    gather(key = date, value = diff, -Index) %>%
    filter(diff %>% between(3, 9)) %>%
    count(Index) %>%
    ungroup() %>%
    arrange(Index)

diffs1
#> # A tibble: 10 x 2
#>    Index     n
#>    <int> <int>
#>  1     1     3
#>  2     2     3
#>  3    15     3
#>  4    22     2
#>  5    75     3
#>  6   436     3
#>  7   563     3
#>  8   567     2
#>  9  6643     2
#> 10 34533     2

diffs1$Index
#>  [1]     1     2    15    22    75   436   563   567  6643 34533

diffs2 <- df %>%
    select_at(vars(Index, starts_with("Date"))) %>%
    gather(key = obs, value = date, -Index) %>%
    group_by(Index) %>%
    mutate(prev_date = lag(date)) %>%
    mutate(diff = date - prev_date) %>%
    filter(!is.na(diff)) %>%
    filter(diff %>% between(3, 9)) %>%
    summarise(n = n())

Created on 2018-04-25 by the reprex package (v0.2.0).
Edit: Just realized you might not be interested in the counts of how many times each index had a diff in your range, only in the indexes that fit that criteria. In that case, you could just stop after filter(diff %>% between(3, 9)) and take the unique indexes with unique(diff1$Index).


text:
Q: Xcode codecompletion, just variables I am learing programming and using Xcode. I would like to trim the autocompletion a bit. I feel like this make me not remember syntax, I often just look it up in codecompletion. And I would for the time being be able to hardcode everything.
Is there a way to make it only complete variable names? This is useful for saving time. But i do not want all the extra.
I am programming in c++ for the record.
Thanks in advance!

A: You can press escape key when you want to complete names. The first word in the suggest list always the true word. then you just press Enter/return key.


text:
Q: woocommerce how to show min/max price of each category When calling the [product_categories] shortcode, I'd like to show in the category title the minimum price of the products belonging to each listed category.
I can

*

*customise the function woocommerce_template_loop_category_title() and insert a small db query like

$sql = 'SELECT min(min_price)
    FROM `wp_wc_product_meta_lookup`
    WHERE product_id IN (
        SELECT object_id
        FROM wp_term_relationships
        WHERE term_taxonomy_id = '.$category->term_id.')';
    $results = $wpdb->get_results($sql);
if (!$results) {
    ... mmhh ...
} else {
    ..display the result
}

or

*use a specific wc function or filter (not in my knowledge) and solve it in the wp/wc way

I was wandering not only to know a implementation of 2) but also to have an assessment about which one is the more efficient in terms of server execution time and resources.
thanks in advance


text:
Q: Marginal Density of X I need to find the marginal density of $x$ where
$$f(x, y) = xe^{-x-y}$$
Where the inputs must abide by: $x, y > 0$
My approach to solving the problem was:
$\int_0^\infty \int_0^\infty xe^{-x-y}dxdy$
$= \int_0^\infty \left[ (x+1)(-e^{-x-y})\right]_0^\infty dy$
$= \int_0^\infty 0 dy$
$= 0$
But that does not make sense at all. The density function should not and cannot be $0$.

A: Here's your error:
$$\begin{align}
\int_{0}^{\infty}{x e^{-x-y}dx} & = (x+1)(-e^{-x-y}) \bigg|_{0}^{\infty} \\
 & = \frac{x+1}{e^{x+y}} \bigg|_{\infty}^{0} \\
 & = e^{-y}
\end{align}$$
And then
$$\int_{0}^{\infty}\int_{0}^{\infty}{xe^{-x-y} dx dy} = 1$$

A: when you get to $$\int_0^\infty (L +1)(\frac{-1}{e^L+e^y})dy=\int_0^\infty e^{-y}dy=\lim_{L\to \infty} -1[e^{-L} - e^0] = -1\cdot-1= 1$$

A: This is quite easy. Everytime you have a joint density function (x,y), if you need to get the marginal density of x, just integrate the joint density function respect to y in its current interval.
Therefore, the marginal density of x is f(x) = Exp[-x]*x.
( Integrate[f[x, y], {y, 0, Infinity}] ;; Integrate[%, {x, 0, Infinity}] )


text:
Q: How to change values of a specific pandas dateframe column of rows with duplicate IDs, and put those multiple values into 1 value on 1 row with commas So my dataframe is pretty complex but i'll keep the important details.
This is the dataframe:
id     name     categorycode
0003F8 Car      A
0003F8 Car      A
0003F8 Car      A
0003F8 Car      AVB-A
0003F8 Car      B
0003F8 Car      B-T
0003F8 Car      BTH
0003U7 Bike     A
0003U7 Bike     A
0003U7 Bike     A-G
0003U7 Bike     ATH
0003U7 Bike     ATH
0003U7 Bike     AVB-A
0003U7 Bike     AVB-A
0003U7 Bike     AVB-A
0003U7 Bike     AVB-A

What I want it to look like is this:
id      name     categorycode
0003F8  Car      A, AVB-A, B, B-T, BTH
0003U7  Bike     A, A-G, ATH, AVB-A

So basically what i want is that only the categorycode values will be changed, and that the name values won't be changed. I'm not sure what the best practice is to use to achieve this. All the help would be greatly appreciated.


text:
Q: Python's struct.pack/unpack equivalence in C++ I used struct.pack in Python to transform a data into serialized byte stream.
>>> import struct
>>> struct.pack('i', 1234)
'\xd2\x04\x00\x00'

What is the equivalence in C++?

A: You'll probably be better off in the long run using a third party library (e.g. Google Protocol Buffers), but if you insist on rolling your own, the C++ version of your example might be something like this:
#include <stdint.h>
#include <string.h>

int32_t myValueToPack = 1234;  // or whatever
uint8_t myByteArray[sizeof(myValueToPack)];
int32_t bigEndianValue = htonl(myValueToPack);  // convert the value to big-endian for cross-platform compatibility
memcpy(&myByteArray[0], &bigEndianValue, sizeof(bigEndianValue));
// At this point, myByteArray contains the "packed" data in network-endian (aka big-endian) format

The corresponding 'unpack' code would look like this:
// Assume at this point we have the packed array myByteArray, from before
int32_t bigEndianValue;
memcpy(&bigEndianValue, &myByteArray[0], sizeof(bigEndianValue));
int32_t theUnpackedValue = ntohl(bigEndianValue);

In real life you'd probably be packing more than one value, which is easy enough to do (by making the array size larger and calling htonl() and memcpy() in a loop -- don't forget to increase memcpy()'s first argument as you go, so that your second value doesn't overwrite the first value's location in the array, and so on).
You'd also probably want to pack (aka serialize) different data types as well.  uint8_t's (aka chars) and booleans are simple enough as no endian-handling is necesary for them -- you can just copy each of them into the array verbatim as a single byte.  uint16_t's you can convert to big-endian via htons(), and convert back to native-endian via ntohs().  Floating point values are a bit tricky, since there is no built-in htonf(), but you can roll your own that will work on IEEE754-compliant machines:
uint32_t htonf(float f)
{
   uint32_t x;
   memcpy(&x, &f, sizeof(float));
   return htonl(x);
}

.... and the corresponding ntohf() to unpack them:
float ntohf(uint32_t nf)
{
   float x;
   nf = ntohl(nf);
   memcpy(&x, &nf, sizeof(float));
   return x;
}

Lastly for strings you can just add the bytes of the string to the buffer (including the NUL terminator) via memcpy:
const char * s = "hello";
int slen = strlen(s);
memcpy(myByteArray, s, slen+1);  // +1 for the NUL byte

A: There isn't one.  C++ doesn't have built-in serialization.
You would have to write individual objects to a byte array/vector, and being careful about endianness (if you want your code to be portable).

A: https://github.com/karkason/cppystruct
#include "cppystruct.h"

// icmp_header can be any type that supports std::size and std::data and holds bytes
auto [type, code, checksum, p_id, sequence] = pystruct::unpack(PY_STRING("bbHHh"), icmp_header);

int leet = 1337;
auto runtimePacked = pystruct::pack(PY_STRING(">2i10s"), leet, 20, "String!");
// runtimePacked is an std::array filled with "\x00\x00\x059\x00\x00\x00\x10String!\x00\x00\x00"
// The format is "compiled" and has zero overhead in runtime

constexpr auto packed = pystruct::pack(PY_STRING("<2i10s"), 10, 20, "String!");
// packed is an std::array filled with "\x00\x01\x00\x00\x10\x00\x00\x00String!\x00\x00\x00"

A: You could check out Boost.Serialization, but I doubt you can get it to use the same format as Python's pack.

A: I was also looking for the same thing. Luckily I found https://github.com/mpapierski/struct
with a few additions you can add missing types into struct.hpp, I think it's the best so far.
To use it, just define you params like this
DEFINE_STRUCT(test,
    ((2, TYPE_UNSIGNED_INT))
    ((20, TYPE_CHAR))
    ((20, TYPE_CHAR))
)

The just call this function which will be generated at compilation
pack(unsigned int p1, unsigned int p2, const char * p3, const char * p4)

The number and type of parameters will depend on what you defined above.
The return type is a char* which contains your packed data.
There is also another unpack() function which you can use to read the buffer

A: You can use union to get different view into the same memory.
For example:
union Pack{
   int i;
   char c[sizeof(int)];
};

Pack p = {};
p.i = 1234;
std::string packed(p.c, sizeof(int)); // "\xd2\x04\x00\0"

As mentioned in the other answers, you have to notice the endianness.


text:
Q: img src is making pdf generation too slow with codeigniter I am using mpdf library for pdf generation with codeigniter.
I have a png file that is given to generate a logo image in pdf. The generation is too slow. I need to speed up the pdf generation. Does anybody know how to solve this issue?

  <img src="<?php echo base_url();?>images/mws-logo.png" alt="mws admin">

A: You are prepending the site URL with the base_url() helper which causes an entire additional HTTP request via the "outside" web.
Try to use a "local" path to the file to prevent additional DNS lookups and HTTP requests.


text:
Q: MySQL error "right syntax to use near 'update" I am getting this error Unhandled Exception.

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'update, desc, indir, time) VALUES(?, ?, ?, ?, ?, ?, ?, 1392556810)' at line 1

whenever i submit the form. Here is source code
if(!is_admin())
{
header("Location: $config->url");
exit;
}
$cid = intval($_GET['id']);
if($_GET['act'] == 'add')
{
$db->bind(id,$cid);
$file = $db->row("SELECT * FROM `".PREFIX."category` WHERE `id`=:id");
if(!$file)
{
$file = new stdClass();
$file->path = "/files";
}
if(!is_dir("..".$file->path))
{
header("Location: $config->url");
exit;
}
if($_POST['save'])
{
$name=$_POST['name'];
$icon=$_POST['icon'];
if($db->count("SELECT COUNT(id) FROM `".PREFIX."category` WHERE `path` = '".$file->path."/".$name."'") == 0)
{
$path=''.$file->path.'/'.$name.'';
$desc=$_POST['desc'];
if(isset($_POST['new']))
$new=1;
else
$new=0;
if(isset($_POST['update']))
$update=1;
else
$update=0;
$time=time();
$insert=$db->query("INSERT INTO ".PREFIX."category(name, path, icon, new, update, desc, indir, time) VALUES(:name, :path, :icon, :new, :update, :desc, :id, $time)", array("name"=>"$name","icon"=>"$icon","new"=>"$new","update"=>"$update","path"=>"$path","id"=>"$cid","desc"=>"$desc"));
if($insert>0)
{
mkdir("..".$file->path."/".$name,0777);
header("Location: $config->url/cat/".$cid."/'".htmli(converturl($file->name)).".html");
}
}
echo 'already exixs';
}
else
echo '<form method="post" action="#">Name : <input type="text" name="name" />
Description : <input type="text" name="desc" />
Icon : <input type="text" name="icon" />
<input type="radio" name="new" value="1" /> New
<input type="radio" name="update" value="1" /> Update

<input type="submit" name="save" value="Add" /></form>';
}

A: This is your insert statement:
INSERT INTO ".PREFIX."category(name, path, icon, new, update, desc, indir, time)
    VALUES(:name, :path, :icon, :new, :update, :desc, :id, $time)

Several of the column names are reserved words in MySQL.  You need to escape them:
INSERT INTO ".PREFIX."category(name, path, icon, `new`, `update`, `desc`, indir, `time`)
    VALUES(:name, :path, :icon, :new, :update, :desc, :id, $time);

The list of reserved words is here.
In general, you should avoid using these words as identifiers.  They are already used in MySQL for other purposes.  But, if you have to use them, then you need to escape them each time.  (Note:  I also escaped "time".  You'll note at the end of the list of reserved words are a handful that are allowed, because they have been so commonly used.  But time is the name of both a type and function, so it should also be reserved.)

A: Check your query here
$insert=$db->query("INSERT INTO
".PREFIX."category(name, path, icon, new, update, desc

Here update/desc/new are all keyword/reserveword; so you will have to quote it like
$insert=$db->query("INSERT INTO
".PREFIX."category(name, path, icon, `new`, `update`, `desc`


text:
Q: Can a uniform circular motion be considered as simple harmonic motion? The acceleration in a circular motion is directed towards the centre and is directly proportional to the radius of circle if it has uniform angular velocity. Is circular motion with uniform angular velocity simple harmonic motion?

A:
Is circular motion with uniform angular velocity simple harmonic
  motion?

No. Simple harmonic motion is the 2-D projection of uniform circular motion on a plane.


text:
Q: How to realize the GPS cold start, warm start , hot start? How to realize the GPS cold start, warm start , hot start ?
Does anyone have any idea about it? Thanks for any help !

A: There is a technique described in about 5 minutes starting at 49:43 of this 2010 Google I/O session that starts multiple location listeners and then "backs off" the less accurate but immediately available listeners as the more accurate but more delayed listeners become available.


text:
Q: grunt-contrib- packages are officially supported by Grunt? I'm about to use the RequireJs plugin for Grunt. I found out that there are two plugins with the same functionality:

*

*grunt-contrib-requirejs (https://github.com/gruntjs/grunt-contrib-requirejs)

*grunt-requirejs (https://github.com/asciidisco/grunt-requirejs)

I am wondering if -contrib prefixed plugins are the trusted, maintained and officially supported ones by Grunt? Is this a pattern that developers should look for?
Thanks.

A: Yes, the grunt-contrib-* naming convention is for official grunt plugins.
See here: https://github.com/gruntjs/grunt-contrib


text:
Q: return value for timestamp difference I don't understand in what units does difference in timestamp returns answer.
when i select max(timestamp) and min(timestamp) from a colum, below are the values that i get.
max(timestamp)
2017-08-31 05:43:45

min(timestamp)
2017-08-31 05:36:13

However below query return 732.
select max(timestamp) - min(timestamp) from <TABLE NAME>

however if put the timestamp inside time_to_sec() it gives current answer in seconds i.e. 452.So what am i missing here?

A: When you do arithmetic with timestamps, it first converts them to numeric form YYYYMMDDHHMMSS. So that's 20170831054345 - 20170831053613 which is 732.
If you want the result as a time, use the TIMEDIFF function.
select TIMEDIFF(max(timestamp), min(timestamp)) from <TABLE NAME>

A: That's an interesting phenomenon and I'm curious to see if anybody comes up with a reason for why that's the case.
Generally, for calculating a timestamp difference, use TIMESTAMPDIFF:
TIMESTAMPDIFF(SECOND, min(timestamp), max(timestamp))


text:
Q: Create new post if not already exist I'm having a bit of a problem in WordPress. I'm looping through a set of data and creating new posts. I need a way to only create the post if its already not exists.
I tried this, but figured it was a quite stupid idea. But can i do something similar? I cant check the titles, since they in many cases will be the same. Can i do the check on import_id somehow? If i do $post_id->import_id its undefined..
Current code:
 for($i = 0; $i < count($postdata); $i++) { //array of data.

    $id = rand(1000, 9999);

    if(is_null(get_post($id))) {
      $post_id = wp_insert_post(array(
        'import_id' => $id, //number
        'post_status' => $post_status, //string
        'post_type' => $post_type, //string
        'post_title' => $post_title, //string
        'post_content' => $post_content //string
      ));
    }
  }

A: You can use the get_post_status() function to tell if a post exists. It will return false if the post does not exist:
if ( get_post_status( $id ) ) {
    // do stuff
}

With your example:
for($i = 0; $i < count($postdata); $i++) { //array of data.

    $id = rand(1000, 9999);

    if ( get_post_status($id) ) {
        $post_id = wp_insert_post(array(
          'import_id' => $id, //number
          'post_status' => $post_status, //string
          'post_type' => $post_type, //string
          'post_title' => $post_title, //string
          'post_content' => $post_content //string
        ));
    }
}

A: You can use post_exists() it will check based on title. check the code below.
for($i = 0; $i < count($postdata); $i++) { //array of data.

    $id         = rand(1000, 9999);
    $fount_post = post_exists( $post_title );

    if( !$fount_post ) {

        $post_id = wp_insert_post( array(
            'import_id'    => $id, //number
            'post_status'  => $post_status, //string
            'post_type'    => $post_type, //string
            'post_title'   => $post_title, //string
            'post_content' => $post_content //string
        ) );

    }

}

Update as per OP code.
$events       = json_decode($res,true);
$this->events = $events['Result'];
$postdata     = array();
$index        = 0;

foreach($this->events as $key=>$event) {
    $post_status = 'publish';
    $post_type = EVENTS_CALENDAR_POST_TYPE;
    $post_title = $event['Heading'];
    $post_content = $event['Description'];
    $post_image = $this->media_url . $event['ImageLarge']['Path'];
    $post_thumb = $this->media_url . $event['Image']['Path'];
    $post_event_id = $event['Id'];

    foreach($this->events[$key]['Dates'] as $date) {
        $post_date = substr($date['Date'], 0, 10);
        $post_arena = $date['Arena']['Name'];
        $postdata[$index]['id'] = $index;
        $postdata[$index]['status'] = $post_status;
        $postdata[$index]['posttype'] = $post_type;
        $postdata[$index]['date'] = $post_date;
        $postdata[$index]['arena'] = $post_arena;
        $postdata[$index]['heading'] = $post_title;
        $postdata[$index]['desc'] = $post_content;
        $postdata[$index]['image'] = $post_image;
        $postdata[$index]['thumb'] = $post_thumb;
        $index++;
    }
}

for($i = 0; $i < count($postdata); $i++) { //array of data.

    $id = rand(1000, 9999);

    $args = array(
       'meta_key' => 'post_event_id'
       'meta_query' => array(
           array(
               'key' => 'post_event_id',
               'value' => $post_event_id,
               'compare' => '=',
           )
       )
    );

    $event = new WP_Query( $args );

    if( !$event->have_posts() ) {

        $post_id = wp_insert_post( array(
            'import_id'    => $id, //number
            'post_status'  => $post_status, //string
            'post_type'    => $post_type, //string
            'post_title'   => $post_title, //string
            'post_content' => $post_content, //string
            'meta_input'   => array(
                'post_event_id' => $post_event_id,
            )
        ) );

    }

}


text:
Q: NoClassDefFound when running a jar I built a jar using IntelliJ, setting the main class properly.
When I run "java -jar foo.jar" from the command line (Windows), I get an exception that claims the main file is missing. The main class looks something like:
package mypackage;

public class LockUtil {
  public static void main(String[] args) {
  ...

I'm getting the following exception:
Exception in thread "main" java.lang.NoClassDefFoundError: mypackage/LockUtil
Caused by: java.lang.ClassNotFoundException: mypackage.LockUtil
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Could not find the main class: mypackage.LockUtil. Program will exit.

The manifest file contains:
Manifest-Version: 1.0
Created-By: IntelliJ IDEA
Main-Class: mypackage.LockUtil

And the jar contains the appropriate directory structure with the .class file.

A: If you do jar -tf foo.jar, do you see something like this?
META-INF/
META-INF/MANIFEST.MF
mypackage/
mypackage/LockUtil.class

Could it be that there is another directory level in there somewhere?
You can be sure that Java knows the main file is there by building the jar file with something like this:
jar cfe foo.jar mypackage.LockUtil mypackage/LockUtil.class

A: You're trying to execute mypackage.LockUtil, but you should use mypackage.locking.LockUtil (note the package statement at the beginning of the class.).
Another possibility is that you have moved the class and forgot the update the package statement.

A: Does LockUtil have a dependency on another class that is not resolvable, thereby not allowing LockUtil to load?

A: It seems that the name of your package is mypackage.locking and not only mypackage

A: It appears that your main-class definition in your manifest is pointing at mypackage/LockUtil rather than mypackage/locking/LockUtil.
-Rick


text:
Q: How would I find the cost of a neural network without knowing the target output like for a game? For example,
I want to create an AI that plays Ticktacktoe, this is how I would go about it.
I have 9 input nodes which is for each space on the board, 3 nodes for one hidden layer (which I'm guessing would somehow benefit the AI by having it select a row or column with 3 spaces), and then 9 output nodes to see where the AI would put its mark on the entire board.
I'm lost on how I would find the cost of this neural network because I don't know how I would judge its prediction and affect its weights and biases.
If I wanted the AI to play a guessing game, it would make sense since I have the correct answer and I can teach it to be more accurate based on how off it was to the actual answer.
(NOTE: I am very new to neural networks, so there may be a simple answer that I've missed somewhere)

A: So, I did some digging around and found a good introduction to reinforcement learning. This is the method that is used to train neural networks to achieve a goal without knowing an exact target like which move is good in a certain scenario. Backpropagation is not the only learning method, but so many sources only used this method without letting the viewer know of any other methods which confused me.
Going through this playlist right now: https://www.youtube.com/watch?v=2pWv7GOvuf0&index=1&list=PL7-jPKtc4r78-wCZcQn5IqyuWhBZ8fOxT
Hope this will help someone getting started with neural networks!


text:
Q: Expected value of correlated stochastic integrals I do not understand the following result:
Suppose $dz_\chi$ and  $ dz_\xi$ are correlated increments of standard Brownian motion with $dz_\chi dz_\xi=\rho dt$ you have the following expectation giving the following result:
$\mathbb{E} [\int_{t}^{T}e^{\kappa s} dz_\chi \int_{t}^{T}dz_\xi] = \rho \int_{t}^{T}e^{\kappa s} ds$
I really do not get it. This equation is justified by the Itô's isometry. In the book that I am reading the author just passes by saying that is easy to see, but if someone could show more explicit the steps that are taking to get this equation.


text:
Q: CSS Hover Events, How to Trigger a Parent's Effect I have a dropdown menu
 which displays a second list
 when hovered on.
Hence:

News & Press Releases

OCPO Home

Press Releases

Ocean County Government

When you hover on the "News & Press Releases" anchor tag, the following effect takes place:
#NavBar > li > a:hover {
    -moz-border-radius: 5px 5px 0px 0px;
    -webkit-border-radius: 5px 5px 0px 0px;
    border-radius: 5px 5px 0px 0px;
    background: #F4F4F4;
    background: -moz-linear-gradient(top, #EEEEEE, #BBBBBB);
    background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#EEEEEE), to(#BBBBBB));
    color: #000;
}

However, the second you move to any of the child links, such as "OCPO Home", the effect of the above hover disappears. Obviously I would have to force it to stay using another CSS tag, but I don't know what I'm doing wrong. This is my attempt:
.NavBar_drop:hover #NavBar > li > a {
    -moz-border-radius: 5px 5px 0px 0px;
    -webkit-border-radius: 5px 5px 0px 0px;
    border-radius: 5px 5px 0px 0px;
    background: #F4F4F4;
    background: -moz-linear-gradient(top, #EEEEEE, #BBBBBB);
    background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#EEEEEE), to(#BBBBBB));
    color: #000;
}

A: Technically you can't trigger an effect on a parent element. However, you don't actually need to do that given the problem you've stated. When you move to the child links you are moving OFF the ; hence the hover effect stopping. Change the selector so that it's triggered when you hover on the parent
 instead:
#NavBar > li:hover {
    /* CSS Styles here... */
}

A: Alternatively to Dre's answer, if you just want to highlight your  when over the entire
, try using this css rule instead:
#NavBar > li:hover > a {

See working demo

A: You cannot select parent element in cascading style sheets so what you are trying is not possible


text:
Q: Decimal Value not accepted on MySQL insert When trying to do a simple insert in PHP to MySQL database, a value of '.5' is entered into the hours variable and is being ignored and set to 0 in the database. I've tried with the db datatype set to float or decimal. Neither work.
Here is my insert code:
$sql ="INSERT INTO timecarddetails (timecardId, tdate, hours, ot, ticketNumber, km, details)
            VALUES (?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);
if($stmt === false){
    trigger_error('Wrong SQL: ' .$sql. ' Error: ' . $conn->error, E_USER_ERROR);
}
$stmt->bind_param('isiisis',$tcId,$JOBDATE[$key],$HOURS[$key],$OT[$key],$TICKET[$key],$KM[$key],$DETAILS[$key]);
$stmt->execute();

When I do a print of the sql statement it comes out like this:
INSERT INTO timecarddetails (timecardId, tdate, hours, ot, ticketNumber, km, details) VALUES (24,2019-11-04,.5, , 2019450202,,Dispatched ticket)
Below is my table structure:

Is there anything wrong with my syntax? If you need any further information, please let me know. Thanks in advance for helping!

A:
$stmt->bind_param('isiisis', ...

i stands for integer values. For decimals, you need d.
Considering your table structure, you likely want:
$stmt->bind_param(
    'isddsds',
    $tcId,
    $JOBDATE[$key],
    $HOURS[$key],
    $OT[$key],
    $TICKET[$key],
    $KM[$key],
    $DETAILS[$key]
);


text:
Q: CodeIgniter on live site not loading controller class I'm trying to setup my site on a production server, and it's basically crashing at line 291 in /system/core/CodeIgniter.php:
//instantiate the requested controller

// Mark a start point so we can benchmark the controller
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');

$CI = new $class();

The class is 'auth' (from the tank_auth library), so it's crashing on '$CI = new auth();'
It doesn't produce an error (why??), just displays a blank page. This all works fine locally.
Has anyone had any similar issues?

A: I had the same problem, I fixed that by installing the php-mysql package:
$ sudo yum install php-mysql

A: Have you checked if error reporting is enabled? If not, try adding
ini_set('display_errors',1);
error_reporting(E_ALL);

to the beginning of index.php.

A: Check this thread for similar issue: CodeIgniter project loads blank webpage
Also, in case you don't have mysql installed and/or a database set up for your site, TankAuth does need the database. Be sure to follow all the installation instructions and create the tables that the module needs (you'll see a .sql dump in the downloaded folder).

A: see the include_path in php on your production server and/or make other frontend with development environment to see error

A: i had the same problem, in my case i needed install de lib php-pgsql(because i use postgresql) on my server. After that, the problem was solved

A: My solution was the same than the others, install mysql compatibility to php. In my case the platform is ubuntu on Amazon AWS (Using mysql on RDS, not local):
$sudo apt-get install php5-mysql
$sudo apt-get install mysql-client
$sudo service apache2 restart
And thats is all, Greetings!

A: Add same issue on Cpanel , moving a CI project from php 5.3 to 5.4
Blank page or 500 internal server error
This resolve the issue :
Enable the "mysqli" extension in PHP (v5) via EasyApache, using the Exhaustive Options List (Cpanel).

A: In my case it was fixed by doing this:
   yum install php-mysqli

on Centos 8


text:
Q: Leitura de dados sobre arquivo .csv Possuo um sistema em PHP realizando a leitura de dados de um arquivo csv. Ele apresenta o número do código de barras onde irei relacionar ao banco de dados para atualização de acordo com o arquivo enviado no sistema. Exemplo:
Usuário envia arquivo CSV com dados: 'Barras' => 7896603803918, 'qtd' => '1'
Ao fazer a leitura do arquivo recebo o valor de barras: "7,8966E+12" o qual não é o mesmo apresentado no valor correto.
Ao abrir o arquivo .csv no excel, encontro realmente o texto sendo exibido como "7,8966E+12", porem quando clico para verificar o valor da função, recebo o número correto de 7896603803918.
Meu problema se resume a: O arquivo .csv me envia um número exponencial que não representa o número real, impossibilitando a importação. Qual seria a solução correta para que eu pudesse retirar esses valores de forma correta do arquivo .csv ou se é um problema que todos enfrentam.
Código sendo utilizado no momento:
<?php
$csv = str_getcsv(file_get_contents('data.csv', 'r'), ';');
var_dump($csv);

A: Provavelmente você está tentando passar barras para int, sendo que o maior valor para int32 é 2^32-32, tente passar o valor para string ou então tente usar uma versão 64 bits do php, que aceita int64


text:
Q: how to force a polynomial regression to be very flexible for big sharp turns while reducing flexibility for small turns Is it possible to force a polynomial regression to be very flexible for big sharp turns while reducing flexibility for small turns?
The reason is that I have a variabele y which depends on x for which I am sure there is a positive correlation, although my dataset contains some noise. This is why I do not want a wiggly line for x between 1 and 75 as in the graph below.
library(ggplot2)
library(dplyr)

x <- c(1:100)
y <- c(1,3,6,12,22,15,13,11,5,1,3,6,12,22,11,5,1,3,6,12,22,11,5,5,9,10,1,6,12,22,15,13,11,5,-1,-12,-23,6,12,22,11,5,1,3,6,12,22,11,5,-11,-22,-9,12,22,11,5,9,10,18,1,3,6,12,22,15,13,11,5,-5, -9, -12,6,12,22,11,5,1,3,6,12,22,11,5,1,3,6,12,22,11,5,9,10,18,28,37,50,90,120,150,200)
y <- y + x

df <- data.frame(x, y)

model <- lm(y ~ poly(x, 6, raw = TRUE), data = df)

predictions <- model %>% predict(df)
df <- cbind(df, predictions)

ggplot() +
  geom_point(data = df, aes(x = x, y = y), size = 0.1) +
  geom_line(data = df, aes(x = x, y = predictions), colour="blue", size=0.1)

I can alter the model to:
model <- lm(y ~ poly(x, 2, raw = TRUE), data = df)

Which gives this graph:

In this case the model is without wigglyness for x between 0 and 90 although it is missing the flexibility to make the turn around x is 90.
I am not looking for a specific solution for this example dataset. I am looking for a solution to have a polynomial regression flexible enough to make sharp (big) turns, although reducing wigglyness for small turns at the same time. (Maybe this can be solved by a limit to make a maximum of n turns?)
I want to use it automated at several datasets. For this reason I do not want to specify different ranges of x for different models.
Thank you!
I have also tried using gam from mgcv, although this gives similar results:
mygam <- gam(y ~ s(x, k = 7), data = df)

mygam <- gam(y ~ s(x, k = 3), data = df)

This graph is based on pmax(p1, p2) where p1 and p2 are two polynomials:


text:
Q: Does Heroku Support Lombok? I have an application which reads Json data using WebClient. I have deployed the same on Heroku.
So I used lombok library to parse Json to Java Object.
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class member {

//properties
}

If I use lombok and deploy the same on heroku, I'm not receiving data whereas If remove lombok and use normal Getters and Setters, then it is working as expected!
Is that mean heroku is not supporting lombok? I couldn't find anywhere in the official document. Or Do i need anything to support lombok on Heroku?

A: You need to add lombok plugin into your gradle configuration like this
plugins {
   id "io.freefair.lombok" version "5.1.0"
}

so that the annotations will be processed properly.


text:
Q: how to possible private variable accessible in child class? I made a programme in oops concenpt there happening a private variable accessing in child class how it is possible. code entered below.....
here uis my code please help me how is it possible private variable in child class or please identify this code is correct or not.
<?php
class student

{
    private $sname,$srollno; //private variable
    public function Getdata($name,$rollno){

        $this-> sname=$name;
        $this-> srollno=$rollno;
    }

    public function Showdata(){

        echo "Name :".$this-> sname."
";
        echo "Rollno:".$this-> srollno."
";
    }
}

    $obj1 = new student;
    $obj1-> Getdata("Sandeep","26");
    $obj1-> Showdata();

    $obj2 = new student;
    $obj2 -> Getdata("Vivek","45");
    $obj2 -> Showdata();

class teacher extends student
{
    //private $tname,$troll;

    public function teach(){
        $this-> sname="tillu"; //here access private variable
        $this-> srollno="12";
    }

    public function teachShow(){
        echo  "tname :".$this-> sname."
";
        echo "troll : ".$this-> srollno."
";
    }

}

$obj3 = new teacher;
$obj3-> teach();
$obj3-> teachShow();

?>


text:
Q: Information required related to service kubernetes My question is that if a client let's say kubectl has to access a cluster for various get/delete/edit operations, it uses .kube/config file and there we specify API endpoint as DNS entry. Shown below is our DNS Entry for NLB.
$ cat config |grep 6443
server: https://ac1poc-20210407164708-kube-api-f5082ea18c7584ad.elb.us-east-1.amazonaws.com:6443

*And if kubelet needs to talk to API endpoint, it has similar entry in its configuration file /etc/kubernetes/kubelet

*Same for kube-proxy as well.
So all these three external APIs have Network Load Balancer entry configured in their respective configuration files. That means all these send Packets to NLB whenever they want to communicate with API backend.

But then I've this service also as shown below. I wanted to ask when does this service comes into play. Which API uses this service?
$ kubectl describe svc kubernetes
Name:              kubernetes
Namespace:         default
Labels:            component=apiserver
                   provider=kubernetes
Annotations:       <none>
Selector:          <none>
Type:              ClusterIP
IP Family Policy:  SingleStack
IP Families:       IPv4
IP:                10.96.0.1
IPs:               10.96.0.1
Port:              https  443/TCP
TargetPort:        6443/TCP
Endpoints:         172.36.11.131:6443,172.36.12.131:6443,172.36.13.131:6443
Session Affinity:  None
Events:            <none>

A:
My question is that if a client let's say kubectl has to access a cluster for various get/delete/edit operations
2)And if kubelet needs to talk to API endpoint

Correct, those two interactions are solving the same problem: how does a process that is external to the kubernetes cluster reach the control-plane. One could imagine that it would be restricted to (for example) just the corporate VPN for kubectl operations, or just the worker subnets for kubelet.
kubelet actually doesn't need to use the NLB (meaning traffic going out of the VPC through any Nat GW/Internet GW to the NLB and back into the VPC), it is perfectly safe and effective to point kubelet's configuration at the "internal" side of that NLB, so long as the control-plane certificates have sufficient Subject Alternative Name entries to satisfy the TLS handshake. That's usually why people don't bother distinguishing those two cases, but if it is a security (or cost!) concern for your organization, it's 100% possible to split those two interactions

Which API uses this service?

The CNI Service points at the same control-plane but that traffic travels within the cluster, and that kubernetes.default.svc.cluster.local Service is available to all Namespaces all the time, and is how any in-Pod kubernetes client uses the built-in ServiceAccount token to reach the kubernetes API. That way, anything running inside the cluster does not need to have any configuration whatsoever in order to reach the API -- including Internet access -- because that in-cluster traffic does not leave the CNI network


text:
Q: ocg: problem using keyval Trying to build expandable macros using ocg layers, I am facing quite disturbing issue that I am not able to figure out and so turn here for some help of specialists...
I am using a macro to insert some tikzpicture content. The visibility of this content is controlled using ocmd from the ocgx2 package. In the main file I want to declare once layers from which the object may stay hidden. For that purpose I created a list of layers using expl3 in order to use it in the macro.
Problem: As far as the list of layers is given by hand everything works well, however as soon as I am passing the list through the expl3 list (and keyval value) it breaks.
Here is a minimal exemple, from which I really need to keep the structure:
\documentclass{article}
\usepackage[tikz]{ocgx2}
\usepackage{keyval}

\makeatletter

\define@key{hidencircle}{trigger}{\def\hidencircle@trigger{#1}}

\newcommand{\hidencircle}[2][]{%
\setkeys{hidencircle}{#1}% Set the keys

\begin{tikzpicture}[overlay,shift={(2.75,1)}]
%%%%%%%%%%%%%% Not Working
\tikzstyle{HCocmd}=[ocmd={visibility=\Not{\Or{\hidencircle@trigger}}}]
%%%%%%%%%%%%%% Does Work
%\tikzstyle{HCocmd}=[ocmd={visibility=\Not{\Or{test1,test2}}}]

\begin{scope}[HCocmd]
\node[circle,fill=red,text=white,text width=1cm]{\bf #2};
\end{scope}
\end{tikzpicture}
}
\makeatother

\ExplSyntaxOn

\NewDocumentCommand{\createlist}{mm}
{\seq_new:c { g_#1_seq }
\seq_gset_from_clist:cn { g_#1_seq } { #2 }}

\NewDocumentCommand{\ocglist}{m}
{\seq_use:cn {g_#1_seq} {,}}

\ExplSyntaxOff

\begin{document}

\createlist{trig}{test1,test2}

\hidencircle[trigger=\ocglist{trig}]{Here I am!}

\tikz{
\begin{scope}[ocg={ref=test1,status=on}]
\node[red](I1){\small circle set invisible};
\end{scope}
\begin{scope}[ocg={ref=test2,status=on}]
    \node[blue,anchor=west](I2)at(I1.east){\small circle set invisible};
\end{scope}

\node[switch ocg={test1},fill=green,text=red] (I3)at([yshift=-.5cm]I1.south) {show it: step 1};
\node[switch ocg={test2},fill=green,anchor=west,text=blue] at([xshift=.25cm]I3.east) {show it: step 2};
}

\end{document}

The output is the following:

whereas the circle may not be displayed!
I am very new in using ocgx and expl3 and would be gratefull for any help.
PS: I am so curious of what you can do further with ocgx. Any other exemple would be very cool.

A: You are trying very hard to hide your values behind different layers of (in part not expandable) commands. If one expand everything it works:
\documentclass{article}
\usepackage[tikz]{ocgx2}
\usepackage{keyval}

\makeatletter

\define@key{hidencircle}{trigger}{\edef\hidencircle@trigger{#1}}%<-- edef

\newcommand{\hidencircle}[2][]{%
\setkeys{hidencircle}{#1}% Set the keys

\begin{tikzpicture}[overlay,shift={(2.75,1)}]
\tikzstyle{HCocmd}=[ocmd={visibility=\expandafter\Not\expandafter{\expandafter\Or\expandafter{\hidencircle@trigger}}}] %<--
%%%%%%%%%%%%%% Does Work
%\tikzstyle{HCocmd}=[ocmd={visibility=\Not{\Or{test1,test2}}}]

\begin{scope}[HCocmd]
\node[circle,fill=red,text=white,text width=1cm]{\bf #2};
\end{scope}
\end{tikzpicture}
}
\makeatother

\ExplSyntaxOn

\NewDocumentCommand{\createlist}{mm}
{\seq_new:c { g_#1_seq }
\seq_gset_from_clist:cn { g_#1_seq } { #2 }}

\NewExpandableDocumentCommand{\ocglist}{m} %<---
{\seq_use:cn {g_#1_seq} {,}}

\ExplSyntaxOff

\begin{document}

\createlist{trig}{test1,test2}

\hidencircle[trigger=\ocglist{trig}]{Here I am!}

\tikz{
\begin{scope}[ocg={ref=test1,status=on}]
\node[red](I1){\small circle set invisible};
\end{scope}
\begin{scope}[ocg={ref=test2,status=on}]
    \node[blue,anchor=west](I2)at(I1.east){\small circle set invisible};
\end{scope}

\node[switch ocg={test1},fill=green,text=red] (I3)at([yshift=-.5cm]I1.south) {show it: step 1};
\node[switch ocg={test2},fill=green,anchor=west,text=blue] at([xshift=.25cm]I3.east) {show it: step 2};
}

\end{document}

A: Yet another possibility: The three new commands \nxAnd, \nxOr, \nxNot allow us to define TikZ styles for visibility setting that are based on arbitrary boolean expressions as in
\defVisibilityStyle{HCocmd}{\nxNot{\nxOr{\hidencircle@trigger}}}

Full example:
\documentclass{article}
\usepackage[tikz]{ocgx2}
\usepackage{keyval}

\makeatletter

\define@key{hidencircle}{trigger}{\def\hidencircle@trigger{#1}}%

\newcommand{\hidencircle}[2][]{%
\setkeys{hidencircle}{#1}% Set the keys

\begin{tikzpicture}[overlay,shift={(2.75,1)}]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\defVisibilityStyle{HCocmd}{\nxNot{\nxOr{\hidencircle@trigger}}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{scope}[HCocmd]
\node[circle,fill=red,text=white,text width=1cm]{\bf #2};
\end{scope}
\end{tikzpicture}
}
\makeatother

\ExplSyntaxOn

\NewDocumentCommand{\createlist}{mm}
{\seq_new:c { g_#1_seq }
\seq_gset_from_clist:cn { g_#1_seq } { #2 }}

\NewExpandableDocumentCommand{\ocglist}{m} %<---
{\seq_use:cn {g_#1_seq} {,}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\cs_new_nopar:Nn\defVisibilityStyle:nn{ \tikzstyle{#1}=[ocmd={visibility=#2}] }
\cs_generate_variant:Nn\defVisibilityStyle:nn{nx}
\cs_set_eq:NN\defVisibilityStyle\defVisibilityStyle:nx
\cs_new_protected_nopar:Npn\nxNot{\Not}
\cs_new_protected_nopar:Npn\nxAnd{\And}
\cs_new_protected_nopar:Npn\nxOr{\Or}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\ExplSyntaxOff

\begin{document}

\createlist{trig}{test1,test2}

\hidencircle[trigger=\ocglist{trig}]{Here I am!}

\tikz{
\begin{scope}[ocg={ref=test1,status=on}]
\node[red](I1){\small circle set invisible};
\end{scope}
\begin{scope}[ocg={ref=test2,status=on}]
    \node[blue,anchor=west](I2)at(I1.east){\small circle set invisible};
\end{scope}

\node[switch ocg={test1},fill=green,text=red] (I3)at([yshift=-.5cm]I1.south) {show it: step 1};
\node[switch ocg={test2},fill=green,anchor=west,text=blue] at([xshift=.25cm]I3.east) {show it: step 2};
}

\end{document}


text:
Q: Как json-данные \u0413\u0440... преобразовать в русский текст Здравствуйте. Возникла проблема с кодировкой. Получаю JSON и не могу его декодировать в Русский текст.
Данные такого формата: \u0413\u0440\u0430\u0439\u0440.
Как преобразовать их в русский текст? decode("utf-8") не работает, unichr и char тоже... Использую python 2.7
Получаю данные так:
response = urllib.urlopen('Ссылка') #получение json
data = json.loads(response.read()) #Обработка JSOn запроса

A: Ничего не надо делать. data уже Юникодные строчки с русским текстом содержит.
#!/use/bin/env python2
import json
from urllib2 import urlopen

data = json.load(urlopen(url))
print data['text']

Наиболее вероятной причиной, по которой вы видите \u0440 вместо р в Питоне 2, является печать контейнера вместо строки. К примеру если type(data['text']) == list:
>>> print [u'\u0440']
[u'\u0440']
>>> print repr(u'\u0440')
u'\u0440'
>>> print [u'\u0440'][0]
р
>>> print u'\u0440'
р

Связано:

*

*Как вывести в консоль русские символы c выполняемой программы на python?

*Removing u in list.

Если type(data['text']) является unicode, но вы всё равно видите \u0413\u0440 на экране вместо Гр, то либо данные неверно генерируются (посмотрите на print repr(urlopen(url).read())—не должны \\u видеть, правильно только один слэш, а не два), либо печать Unicode в вашем окружении так сконфигурирована (проверьте значение PYTHONIOENCODING переменной окружения—ascii:backslashreplace может Г в \u0413 превратить). Вот примеры ввода/вывода Unicode в Питоне 2.
О \u в json cм. ещё ответ на связанный вопрос: Json ответ в "неправильной кодировке" отображает русские символы.
\u экранирование используется для представления Unicode символов как в JSON формате так и в текстовом представлении unicode строк в Питоне.

A: Я делал так, используя opener.
Это кусочек из проекта на Python 3, так что не уверен, но в основном оно выглядит так:
# -*- coding: utf-8 -*-
import urllib.request, http.cookiejar, requests, json
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
content = json.loads(opener.open(urllib.request.unquote("ссылка")).read().decode('utf-8'))

В итоге json должен содержать кириллицу.

A: попробуйте так:
>>> print '\u0413\u0440\u0430\u0439\u0440'.replace('\u','\\u').decode('unicode-escape')
Грайр


text:
Q: What is the best approach to passing third party objects into constructor I have a class that takes in an argument and then popluate a private hashmap from the argument.
Public class Table {
  private Map<String, String> map = new HashMap<String, String>();
  private Workbook workbook;
  // approach 1
  Public Table(Workbook workbook) {
    this.workbook = workbook;
    // populate map using workbook
  }

  // approach 2
  Public Table(InputStream is) {
    this.workbook = WorkbookFactory.create(is)
    // Populate map
  }

 // approach 3
 Public Table(File file) {
   this.workbook = WorkbookFactory.create(file)
   // populate map
 }
}

Workbook is an Apache Poi Workbook.
What would be the best approach with consideration to junit and mockito also.
I'm leaning towards approach 1, because according to this, http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/ I should avoid new keyword in constructor. But I don't want the client to have knowledge of Apache POI to use this class.
Approach 2 and 3 are pretty similar. With this I can pass in a file or input stream and not worry about the underlying implementation. But mocking would be hard as I can't mock the workbook with this approach?

A: You can make a Factory method and your constructor be protected. Would be something like this:
public class Table {

    private final Map<String, String> map = new HashMap<String, String>();
    private final Workbook workbook;

    // not private for testing.
    Table(Workbook workbook) {
       this.workbook = workbook;
    }

    public static Table create(File file) {
         return new Table(WorkbookFactory.create(file));
    }
}

this way you can test your Table class with a mocked Workbook and still don't expose to your user that you're using it ;)
@Runwith(MockitoJunitRunner.class)
public class TableTest {
    @Mock
    private Workbook workbook;
    @InjectMocks
    private Table table;

    // do some sweet testing ;D
}

A: consider this:
public class Table {
  private Map<String, String> map = new HashMap<String, String>();
  private Workbook workbook;

  Table(Workbook workbook) {
    this.workbook = workbook;
    // populate map using workbook
  }

  public Table(InputStream is) {
       this(WorkbookFactory.create(is)) ;
  }

 public Table(File file) {
     this(new FileInputStream(file);
 }
}

note that the Workbook specific constructor is declared as package protected so normal clients won't be able to call it, but if your unit cases share the same package as your library, you'll have no problems calling that constructor directly from your unit test.  This would also allow you to write separate unit tests for the other two constructors.


text: Q: Read slide mode and spell check option Do we have an option in python to check the slide mode (fit mode) and what type of spellcheck used in the presentation??? I am developing a code in python which requires me to check all these parameters. Please let me know if there is a way...


text:
Q: Does uniform integrability plus convergence in measure imply convergence in $L^1$?
Does uniform integrability plus convergence in measure imply convergence in $L^1$?

I know this holds on a probability space. Does it hold on a general measure space? I have tried googling. It returned very few results on UI on measure spaces, and none of them mentioned a result like the one in the title. This comes from a discussion about another question.
The proof i have seen for a probability space breaks for a general measure space.
By UI, i mean
$\sup_{f}\int_{|f|>h} |f|d\mu $ goes to $0$ as $h$ goes to infinity.

A: As David Mitra showed, the result does not hold with this definition of uniform integrability. The main reason is that it is not adapted to infinite measure spaces: if $f$ is a bounded function, then $\{f\}$ is a uniformly integrable (UI) family but $f$ may be not integrable it self.
We rather use the definition

The family $\{f_i,i\in I\}$ is uniformly integrable if for each $\varepsilon\gt 0$, there is an integrable function $g$ such that
  $$\sup_{i\in I}\int_X(|f_i|-g)^+\mathrm d\mu\lt\varepsilon.$$

With this definition, we have the result

Let $(X,\mathcal A,\mu)$ be a measure space, $\{f_n,n\geqslant 1\}$ a UI sequence and $f$ such that $f_n\to f$ in measure. Then $f_n\to f\in\mathbb L^1$.

Proof: Considering $B_{n,k}:=\{|f_n|\geqslant k^{-1}\}$, that we rearrange into an increasing sequence $(A_k)_{k\geqslant 1}$, we have by an approximation argument that
$$\lim_{k\to \infty}\sup_n\int_{X\setminus A_k}|f_n|\mathrm d\mu=0.$$
Fix $(f_{n'})$ a subsequence of $(f_n)$. Using a diagonal argument, we can extract a further subsequence $(f_{n''})$ which converges almost everywhere to $f$. We thus have by Fatou's lemma: $\int_{X\setminus A}|f|\mathrm d\mu=0$ where $A:=\bigcup_kA_k$. We then conclude by dominated convergence.

A: On $\Bbb R$ with Lebesgue measure, the sequence $(f_n)$ defined by $f_n={1\over n}\cdot \chi_{[n,2n]}$ for each $n$ would furnish a counterexample. Here, $\chi_A$ is the indicator function on the set $A$.


text:
Q: How do I always display the Infowindow in Mapbox android without having to click on the marker? I am working on mapbox android. I need the infowindow to be shown on top of all markers when the activity is loaded, without having to click on the markers to see each info window.How do I acheive this functionality in mapbox?
Here is the code:-
  mapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(final MapboxMap map) {

                mapboxMap = map;
  mapboxMap.addMarker(new MarkerOptions()
                        .title("hello")
                        .snippet("I am here")
                .position(new LatLng(33.948,-118.08)));

                mapboxMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() {
                    @Nullable
                    @Override
                    public View getInfoWindow(@NonNull Marker marker) {
                   //What do I give here so that marker click is not at all needed to inflate the Infowindow.
                           return null;
                    }
                });
)
});

A: Use this code to open infowindow bydefault
Marker marker = myMap.addMarker(new MarkerOptions()
                 .position(latLng)
                 .title("Title")
                 .snippet("Snippet")
                 .icon(BitmapDescriptorFactory
                 .fromResource(R.drawable.marker)));
 marker.showInfoWindow();

but this working only for one marker,fOR multiple marker it opens infowindow for last marker.
Source From this Link

A: You can Call View.Performclick() when add marker to Map.
Check out this post.
Android call onClick method without Clicking


text:
Q: how to filter array with multiple properties in angular I have created a pipe in my angular 5 project, which will takes the input from html and filter array and will return filtered array. But currently I am passing the property name("firstName") from HTML file. Now i want that, it should filter from properties "firstName" and "lastName" both. Please tell me what should i change to do the same ???

search-filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'searchFilter'
})
export class SearchFilter implements PipeTransform {
    transform(data: any, search?: string, propertyName?: string): any {
        if (search === undefined) {
            return data;
        } else {
            return data.filter(obj => obj[propertyName].toLowerCase().includes(search.toLowerCase()));
        }
    }
}

user.component.html

   {{data.lastName}}, {{data.firstName}}

sample-data.ts

 datas: [
{ firstName: 'vipin', company: 'abc', lastName: 'sharma' },
{ firstName: 'kevin', company: 'abc2', lastName: 'xyz' },
{ firstName: 'Leos', company: 'abc3', lastName: 'abc' },
]

A: I got my answer and its working fine :
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'searchFilter'
})
export class SearchFilter implements PipeTransform {
    transform(data: any, search?: string, propertyName?: string, propertyName2?: string): any {
        if (search === undefined) {
            return data;
        } else {
            let filteredData = data.filter(obj => obj[propertyName].toLowerCase().includes(search.toLowerCase()));
            if (propertyName2) {
                filteredData = filteredData.concat(data.filter(obj => obj[propertyName2].toLowerCase().includes(search.toLowerCase())));
            }
            return filteredData;
        }
    }
}

A: What you can do is concat the properties you want to search on:
this.items.map((item) => {
  return {...item, searchTerms: item.firstname + item.lastname;
});

{{item.name}}

A: Can you try like this
 this.data.filter((element: datatype) =>element.firstName && element.lastName)


text:
Q: How to reuse class on ID definition? In the following code, is there a way to use the .center class in the CSS declaration rather than doing a class= in each div?  Each div should have a margin:0 auto.
CSS
.center {margin:0 auto;}
#first {width:400px; font-size:10px;}
#second{width:400px;text-align:center;}

HTML

This is the first line

This is the first line

http://jsfiddle.net/ayK3J/

A: If you want each div to have margin: 0 auto;, then use a simple element selector like
div {
    margin: 0 auto;
}

If you want to center the div having IDs ONLY, then use element[attr] selector like
div[id] {
    margin: 0 auto;
}

But beware before using these; they are too general, and will lead to inconsistent results if your layout gets broader, so it's better to wrap an element around these div elements you want to apply margin: 0 auto; on and assign an ID to that(say, #wrapper) and than use a selector like
#wrapper > div {
    margin: 0 auto;
}

Or, using
#wrapper {
    margin: 0 auto;
}

should suffice as well...

Don't want to use a wrapper element? Modify your IDs like #center-first, #center-second and so on, then you can use element[attr=val] selector like
div[id^=center-] {
    margin: 0 auto;
}

The above selector matches ANY IDS which start with a word center followed by a -
Demo

A: What about this?
#first,
#second {
  margin: 0 auto;
}


text:
Q: How to display the array index number in an editor template In my model I have a List property of a complex type called EventField.
I created an editor template, which works fine using:

@Html.EditorFor(e => e.EventField)

My question is, within that Editor template I want to pick out the index/sequence number on its own, as a number. This index will simply be added into the template as a data attribute so I can pick it up using javascript.
A couple of answer are out there that don't suffice:

*

*@html.IdFor - outputs the whole name e.g Name[0].other

*here - you can't pass through the model name "EventField" this way.

Is there a simple method/function/helper that will give me access to that Index, without having to change how I call the Editor template?

A: How about:
@using System
@using System.Text.RegularExpressions

var i = Convert.ToInt32(Regex.Matches(
         ViewData.TemplateInfo.HtmlFieldPrefix,
         @"\[([0-9]+)?\]")[0].Groups[1].ToString());


text:
Q: How to send a message without spamming it ? I'm having a problem since whenever I run this code it spams my cellphone with messaged with " Check In Success" I only want it to send it 1 time when the location coordinates is the same or almost the same with the lastknown coordinate.
Here's the code :
public class SmsReceiver extends BroadcastReceiver {

    private static final String TAG = "Message recieved";

    @Override
    public void onReceive(Context context, Intent intent) {
        if(isMyServiceRunning(context)) {
            Bundle pudsBundle = intent.getExtras();
            Object[] pdus = (Object[]) pudsBundle.get("pdus");
            SmsMessage messages = SmsMessage.createFromPdu((byte[]) pdus[0]);
            Log.i(TAG, messages.getMessageBody());

            LocationManager lm = (LocationManager) context
                    .getSystemService(Context.LOCATION_SERVICE);
            // Geocoder geocoder;
            String bestProvider;
            // List<Address> user = null;
            double lat;
            double lng;

            Criteria criteria = new Criteria();
            bestProvider = lm.getBestProvider(criteria, false);
            Location location = lm.getLastKnownLocation(bestProvider);

            if(location != location)
            {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage("09164232662", null, "You Have Successfully reached your target Location" , null, null);
            }

            /*else
            {
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage("09164232662", null, "Please Walk a few more meters in order to reach the designated location" , null, null);
            }*/

            /*Toast.makeText(
                    context,
                    "FROM: " + messages.getOriginatingAddress() + "time: "
                            + messages.getTimestampMillis() + "SMS Received : "
                            + messages.getMessageBody(), Toast.LENGTH_LONG).show();*/

            String date=String.valueOf(messages.getTimestampMillis());
            HashMap<String, String> data = new HashMap<String, String>();
            data.put("phone", messages.getOriginatingAddress());
            data.put("text", messages.getMessageBody());
            //data.put("quando", date);

            if(messages.getOriginatingAddress() == "09228387118")
            {
                abortBroadcast();

            }

            //AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);
            //asyncHttpPost.execute("http://10.0.0.2/smsreceive.php",messages.getOriginatingAddress());
            //abortBroadcast();
        }else{
            Bundle pudsBundle = intent.getExtras();
            Object[] pdus = (Object[]) pudsBundle.get("pdus");
            SmsMessage messages = SmsMessage.createFromPdu((byte[]) pdus[0]);
            Log.i(TAG, messages.getMessageBody());

            LocationManager lm = (LocationManager) context
                    .getSystemService(Context.LOCATION_SERVICE);
            // Geocoder geocoder;
            String bestProvider;
            // List<Address> user = null;
            double lat;
            double lng;

            Criteria criteria = new Criteria();
            bestProvider = lm.getBestProvider(criteria, false);
            Location location = lm.getLastKnownLocation(bestProvider);

/*          {
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage("09164232662", null, "Please Walk a few more meters in order to reach the designated location" , null, null);

            }*/

            String date=String.valueOf(messages.getTimestampMillis());
            HashMap<String, String> data = new HashMap<String, String>();
            data.put("phone", messages.getOriginatingAddress());
            data.put("text", messages.getMessageBody());
            //data.put("quando", date);
            data.put("servicestatus", "1");

            //09228387118

            if(messages.getOriginatingAddress() == "09164232662")
            {
                abortBroadcast();

            }

            //09989988910
            //AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);
            //asyncHttpPost.execute("http://10.0.0.2/smsreceive.php",messages.getOriginatingAddress());
            //abortBroadcast();
        }

    }
    boolean isMyServiceRunning(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (ServerService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}


text:
Q: How to avoid UnsupportedEncodingException in Junit I have the following code which needs the UnsupportedEncodingException to be handled by try-catch or throws declaration but I want to use neither of them.
  @Test
  public void serializeAndDeserializeUTF8StringValueExpectingEqual() {
    String stringValue = "\u0048\u0065\u006C\u006C\u006F";
    String deserializedStringValue = serialzeAndDeserializeStringValue(stringValue);
    assertThat(deserializedStringValue.getBytes("UTF-8")).isEqualTo(stringValue.getBytes("UTF-8"));
  }

For example I avoided NullPointerException by using assertThatNullPointerException().isThrownBy as following
  @Test
  public void serializeAndDeserializeNullStringValueExpectingEqual() {
    String stringValue = null;
    assertThatNullPointerException()
        .isThrownBy(() -> OutputStreamUtil.serializeString(stringValue, oStream));
  }

Is there any way to avoid using try-catch or throws declaration for UnsupportedEncodingException

A: Maybe should try like this:
 @Test
 public void serializeAndDeserializeUTF8StringValueExpectingEqual()  {
        String stringValue = "\u0048\u0065\u006C\u006C\u006F";
        String deserializedStringValue = new String(stringValue);

        Throwable thrown = catchThrowable(() -> deserializedStringValue.getBytes("UTF-8"));

        assertThat(thrown).isExactlyInstanceOf(UnsupportedEncodingException.class);
    }

A: If you are using Junit 4 and up you could use:
assertThrows(UnsupportedEncodingException.class, () -> {
    nameOfObjectThatThrows.nameOfMethodThatThrows();
});

This is similar to how you bypassed your null pointer with basically asserting that it was thrown from a specific method.


text:
Q: c++: how to read from and write to a folder I've found tons of examples on file IO, but nothing with folders?
anyone have a quick example?
Note: I'm on *.nix

A: You can take a look at Boost FileSystem

A: You shouldn't be reading and writing to folders - that's the file system's job.  If you want to read a directory, take a look at opendir and friends.

A: Take a look at opendir, readdir, closedir, etc. functions.


text:
Q: Creating threads on a loop I'm new to threading, so I want to understand what is happening behind the scenes when you create a bunch of Threads in a loop and the implications/better ways of doing it.
Here's an example:
for (Page page : book) {
    Thread t = new Thread(new Runnable() {
        public void run() {
            //http request to get page and put into concurrent data structure
        }
    });
    t.start();
    threads.add(t);
}
//wait for threads

As you can probably see, in my specific use case right now, I am paging through objects that I request via HTTP. I know there doesn't necessarily need to be threads here and instead I could make async requests, but how (with explanations) how this could be improved.

A: In your example your are creating and starting a new thread for each Page object you have in your book. This is not useful if you have many more pages than cores on your system.
It's also kinda low-level by now to directly create and start threads and keep track of them.
A better solution would be to use an ExecutorService and create a number of threads close, for example, to the number of cores there is on the system (for I/O bound tasks you may want to create more threads than that: you can check out the comments below this answer).
For example:
final ExecutorService e =
    Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

for (Page page : book) {
    e.submit( new Runnable() {
              //http request to get page and put into concurrent data structure}
}

You'd then wait on your ExecutorService to terminate its job.
Note that depending on the server you're fetching your information from, you may need to add, on purpose, delays as to not "hammer" the server too much.
Certain websites will tell you how often you can query them (for example the Bitstamp bitcoin exchange allows one query per second) and will ban your IP if you don't respect the delay. Others won't well you anything and simply ban your IP if they detect that you're leeching too fast.


text:
Q: $(q, t)$-binomial coefficients The $q$-binomial coefficients ${n + k \choose n}_q$ can be written as a sum
$${n + k \choose n}_q = \sum_{\lambda \subset (n^k)} q^{|\lambda|}\qquad (1)$$
where $(n^k) = (n, n, ..., n)$ is a partition of $k$ parts each part equal to $n$. For a proof see e.g. Theorem 2 of this book chapter.
Question: Is there a $(q, t)$-generalisation of (1) that is related to the Macdonald polynomials in whatever sense?
Below is what I've found after searching on the Internet:
arXiv:1001.3466 and arXiv:q-alg/9605004 both introduced certain $(q, t)$-analogues of the binomial coefficients. Do they satisfy any analogues of (1)?
Also, in this book chapter the $(q, t)$-Catalan numbers have a nice lattice path interpretation analogous to (1), see Formula (83) in that chapter. But there does not seem to be any $(q, t)$-binomial coefficients there.

A: In a paper entitled $(q,t)$-analogues and $GL_n(\mathbb{F}_q)$, V. Reiner and D. Stanton have some such formulas.
Caveat. The above-mentioned $(q,t)$-binomial coefficients are a tad bit different from what you would call a "natural" binomial analogue. They comment that it is not even a polynomial (almost). Yet, the authors achieved very interesting outcomes with right-hand side mimicking what you quoted in your question. I let you decide the rest for yourself.

A: Siddhartha Sahi has some stuff on binomial coefficients and interpolation Macdonald polynomials, see e.g., this paper, where the qt-binomial is a quotient of certain specializations of interpolating Macdonald polynomials.
I am not sure if these satisfy an analogue of (1) thought.


text:
Q: I am unable to install on json on python 3.7 (The error below is what I am facing) Error when trying to load data with module JSON
File "C:\Users\Harry Walia\Desktop\Python\json1.py", line 3, in <module>
    import json
  File "C:\Users\Harry Walia\Desktop\Python\json.py", line 13, in <module>
    json_obj = json.loads(data)
  AttributeError: partially initialized module 'json' has no attribute 'loads' (most likely due to a
   circular import)

A: The most common reason for this error is that you have a file in your current working directory named "json.py". Python already has the JSON module installed, so just make sure you haven't named any of your files "json.py"

A: Python already has a built-in Json module, so you do not need to install it. Just head into your shell and type:
import json

And you'll have the JSON module!


text:
Q: Creating a dummy variable in R using loan default data I'm working with Lending Club data set and I'm trying to create a dummy variable for the target variable loan_status. So my main goal is for Charged Off to be 0 and Fully Paid to be 1 and all else would be 'NA'. The variable loan status has several values: Current, Fully Paid, Late, Grace Period, Delinquent, Charged off, and Does not qualify due to credit profile. I just want to focus on Charged Off and Fully Paid. I've tried numerous times but still no success. For example:
Creating a new target variable
loan_status1 <- if(loan_status== 'Fully Paid'){'Yes'} else if
 (loan_status== 'Charged Off') {'No'} else 'NA'

Also I've tried this:
if(loan_status=='Fully Paid'){
   0} else if (loan_status=='Charged Off') {
   1} else (loan_status=='NA')

I would appreciate any guidance.

A: Basically you could try to run a for-loop over your data by executing this:
Don't set NAs as strings ('NA'), better set to data type NA
loan_status <- sample(rep(c('Fully Paid', 'Charged Off', "abc"), 100), 100, replace = FALSE)

for (i in seq_along(loan_status)){
  if (loan_status[i] == 'Fully Paid'){
    loan_status[i] <- as.integer(0)
  } else if (loan_status[i] == 'Charged Off'){
    loan_status[i] <- as.integer(1)
  } else {
    loan_status[i] == NA
  }
}

Maybe you want to do this the easy way with the factor() function:
For instance you could do:
factor(loan_status, levels = c('Fully Paid', 'Charged Off'), labels = c(0, 1))

A: The OP requested a 1:1 replacement, i.e., only one data field involved, of selected values. Besides the nested ifelse approach, this could be done by using factors or join for larger data.
If more than two or three values need to be replaced, the "hard-coded" nested ifelse approach easily gets unhandy.
Factor case 1: Yes, No
# create some data
loan_status <- c("Fully Paid", "Charged Off", "Something", "Else")
# do the conversion
factor(loan_status, levels = c("Fully Paid", "Charged Off"), labels = c("Yes", "No"))
#[1] Yes  No   <NA> <NA>
#Levels: Yes No

Or,
as.character(factor(loan_status, levels = c("Fully Paid", "Charged Off"), labels = c("Yes", "No")))
#[1] "Yes" "No"  NA    NA

if the result is expected as character.
Factor case 2: 0L, 1L as integers
If the result is expected to be of type integer, the factor approach can still be used but needs additonal conversion.
as.integer(as.character(factor(loan_status, levels = c("Fully Paid", "Charged Off"), labels = c("0", "1"))))
#[1]  0  1 NA NA

Note, that the conversion to character is essential here. Otherwise, the result would return the numbers of the factor levels:
as.integer(factor(loan_status, levels = c("Fully Paid", "Charged Off"), labels = c("0", "1")))
#[1]  1  2 NA NA

Join
In case of larger data and many items to be replaced using data.table join might be an alternative worth considering:
library(data.table)
# create translation table
translation_map <- data.table(
  loan_status = c("Fully Paid", "Charged Off"),
  target = c(0L, 1L))
# create some user data
DT <- data.table(id = LETTERS[1:4],
                 loan_status = c("Fully Paid", "Charged Off", "Something", "Else"))
DT
#   id loan_status
#1:  A  Fully Paid
#2:  B Charged Off
#3:  C   Something
#4:  D        Else

# right join
translation_map[DT, on = "loan_status"]
#   loan_status target id
#1:  Fully Paid      0  A
#2: Charged Off      1  B
#3:   Something     NA  C
#4:        Else     NA  D

By default (nomatch = NA), data.table does a right join, i.e, takes all rows of DT.


text:
Q: Setting value of boolean columns based on existence of value in set I have a SQL table of the format (INTEGER, json_array(INTEGER)).
I need to return results from the table that have two boolean columns. One is set to true iff a 1 appears in the json_array, and the other true iff a two appears in the array. Obviously there is not mutual exclusion.
For example, if the data were this:
-------------------------------
| ID       |   VALUES         |
-------------------------------
|  12      |  [1, 4, 6, 11]   |
_______________________________
|  74      |  [0, 1, 2, 5]    |
-------------------------------

I would hope to get back:
-------------------------------
| ID       |   HAS1  |  HAS2  |
-------------------------------
|  12      |  true   | false  |
_______________________________
|  74      |  true   | true   |
-------------------------------

I have managed to extract the json data out of the values column using json_each, but am unsure how to proceed.

A: If I recall correctly, SQLite max aggregate function supports boolean, therefore you can simply group by your data:
select
    t1.id,
    max(case json_each.value when 1 then true else false end) as has1,
    max(case json_each.value when 2 then true else false end) as has2
from
    yourtable t1,
    json_each(t1.values)
group by
    t1.id


text:
Q: Change the text of a  using $refs in Vue.js I have the following  element in my <template>.
my text

How do I change the content of this  from my text to my new text using $refs in my

          {{column}}

             {{rowItem}}


text:
Q: Handling MySQL Error 1104 in PHP with PDO I'm trying to figure out how to execute the MySQL statement SET SQL_BIG_SELECTS=1 in a PHP program using PDO but I can't find anything here or via google to show me how to do this. In fact, I'm not sure it can even be done in a PHP program.
I've started getting MySQL error 1104 (Sqlstate=42000) due to a UNION statement that combines two queries in my database. I've tried creating the only index that would help the statement perform better but it hasn't resolved the error.
[Edit: Here is the statement I am trying to execute:
SELECT Story.Type as Story_Type, Story.Author as Story_Author, Story.Title as Story_Title, Book.Format as Book_Format, Book.Type as Book_Type, Book.Title as Book_Title, Book.Author as Book_Author
    FROM `SciFic` Story inner join `SciFic` Book
    on (Story.Anthology_Number = Book.Year_Published and Story.Author = Book.Author)
    Where Story.Type = 'SHORT STORY'

    UNION

    SELECT Story.Type as Story_Type, Story.Author as Story_Author, Story.Title as Story_Title, Book.Format as Book_Format, Book.Type as Book_Type, Book.Title as Book_Title, Book.Author as Book_Author
    FROM `SciFic` Story inner join `SciFic` Book
    on (Story.Anthology_Name = Book.Title)
    Where Story.Type = 'SHORT STORY'

    Order by 3

I created a non-unique index on the type column and it has a cardinality of 18. There are 10982 rows in the table.]
I had hoped that this code would be sufficient:
$db->exec("SET SQL_BIG_SELECTS=1") or die(print_r($db->errorInfo(), true));

but it gives me this instead:
Error encountered while getting SciFic short stories: SQLSTATE[42000]: Syntax error or access violation: 1104 The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE and use SET SQL_BIG_SELECTS=1 or SET MAX_JOIN_SIZE=# if the SELECT is okay

I would dearly love to know how to overcome this problem if anyone can suggest something. This code worked fine a few months back but I'm using a hosting service and I think they must have updated their version of MySQL because the data has NOT changed.


text:
Q: Generate Word File in Laravel PHPWord - problem with add blade I am beginner in Laravel. I use in my project Laravel 5.8.
I have this code for generate Word file:
$phpWord = new \PhpOffice\PhpWord\PhpWord();
        $month = $request->input('month');
        if ($month == null) {
            $now = Carbon::now();
            $month = $now->month;
        }
        $events = $this->frontendGateway->getEventCalendarDownload($request, $month);
        $logo = public_path('assets/images/logo3.jpg');
        $view_content = View::make('psCMS.prints.events-view', ['events' => $events, 'logo' => $logo])->render();
        $section = $phpWord->addSection();
        $text = $section->addText('aaaaaaaa');
        $text = $section->addText('bbbbbbbbbb');
        $text = $section->addText('ccccccccccc');
        $text = $section->addText($view_content);

        //ob_clean();
        $fileName = 'Event_calendar' . '-' . now()->toDateString() . '.doc';
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save($fileName);

        header('Content-Type: application/octet-stream');
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Content-Disposition: attachment; filename=$fileName");
        ob_clean();
        readfile($fileName);

and this is my Blade file:

                my name

                street

    Kalendarz wydarzeń

                #
                Data
                Godzina
                Nazwa imprezy
                Miejsce

            @foreach($events as $event)
            @php
                $hourFromX = explode(":", $event->hour_from);
                $hourToX = explode(":", $event->hour_to);
                $hourFrom = $hourFromX['0'].":".$hourFromX['1'];
                $hourTo = $hourToX['0'].":".$hourToX['1'];
            @endphp

                {{ $loop->iteration }}
            {{ $event->date_from }}
            {{ $hourFrom }}-{{ $hourTo }}
            {{ $event->title }}
            @if(isset($event->localization)) {{ $event->localization->name }},
                {{ $event->localization->city }}
                {{ $event->localization->street }} @endif

            @endforeach

When I run this code, I have error: Word file is corrupted.
When I comment this line:
$text = $section->addText($view_content);

Word file is okey. Generated file was open in Word without any problems.
How can I repair it?

A: Can you try adding addHtml instead of addText
\PhpOffice\PhpWord\Shared\Html::addHtml($section, $view_content , false, false);


text:
Q: Html.EditorForModel and Hiding element from Edit I'm using the following code to render an editor for my model using ASP.NET MVC 3, it works perfect, except for I don't want the user to see or edit the "Id" field in my object.
<% using (Html.BeginForm())
   { %>
    <%: Html.ValidationSummary(true, "Your input has errors, please correct and try again") %>
    <%: Html.EditorForModel(Model)%>

    <input type="submit" value="Update" />
<% } %>

In my model for the ID Field I have the following
[Display(AutoGenerateField = false)]
public int Id{ get; private set; }

Which granted is what I thought would work based on the description of the "AutoGenerateField" parameter.  However this isn't working.  I don't want to have to build the whole editor just for this one little oddity....

A: Use [ScaffoldColumn(false)] to hide fields

A: You could use the [HiddenInput] attribute:
[HiddenInput(DisplayValue = false)]
[Display(AutoGenerateField = false)]
public int Id { get; private set; }