text:
Q: Flask/SQLAlchemy: Incompatible collection type: None is not list-like I am confused. What's wrong?
I have two models, and a many to one relation.
I created form Boss_add for adding boss to database.
But, nothing works!
My models:
class User(UserMixin, db.Model):
  __tablename__ = 'users'

  id = db.Column(db.Integer, primary_key=True)
  username = db.Column(db.String(20), unique=True, nullable=False)
  boss_id = db.Column(db.Integer, db.ForeignKey('boss.id'))
  boss = db.relationship('Boss', back_populates='users')

class Boss(db.Model):
  __tablename__ = 'boss'

  id = db.Column(db.Integer, primary_key=True)
  short_name = db.Column(db.String(64))
  users = db.relationship('User', back_populates='boss')

My Forms:
from flask_wtf import FlaskForm
from wtforms import IntegerField, StringField, PasswordField, BooleanField, SubmitField, DateField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField
from app.models import User, Boss

class Boss_add(FlaskForm):
  short_name = StringField('Short name', validators=[DataRequired()])
  users = QuerySelectMultipleField('Users', query_factory=lambda: db.session.query(User), get_pk=lambda a: a.id, get_label=lambda a: a.username, allow_blank=True)
  button = SubmitField('Add')

My view:
@app.route('/boss_add/', methods=['GET', 'POST'])
@login_required
def boss_add():
  form = Boss_add()
  if request.method == 'POST' and form.validate():
    print("FIRST PRINT: ", type(form.users.data))   # DEBUG PRING 1
    print("SECOND PRINT: ", form.data)              # DEBUG PRING 2
    boss = Boss(short_name=form.short_name.data,
                users=form.users.data)
    db.session.add(boss)
    db.session.commit()
  return render_template('boss_edit.html', form=form)

My template:
<title>Boss add</title>

    <form action="" method="post" novalidate>
        {{ form.hidden_tag() }}

            {{ form.short_name.label }}

            {{ form.short_name }}

            {{ form.users.label }}

            {{ form.users }}

{{ form.button() }}

</form>

DEBUG PRINT:
If I select user in list
FIRST PRINT: <class 'list'>
SECOND PRINT: {'short_name': '1111', 'users': [<User 1>], 'button': True, 'csrf_token': 'IjYxNDFhYzYyOGNlMGMzYTliNGYxOTA2NDYxYmE1ZDZkZmVjMjVkNDUi.DqPGxg.63Z-bKn8dgRGLNLxgMLUEzKMa15'}

If I not select user in list
FIRST PRINT: <class 'list'>
SECOND PRINT: {'short_name': '1111', 'users': [], 'button': True, 'csrf_token': 'IjYxNDFhYzYyOGNlMGMzYTliNGYxOTA2NDYxYmE1ZDZkZmVjMjVkNDUi.DqPGxg.63Z-bKn8dgRGLNLxgMLUEzKMa15'}

TypeError: Incompatible collection type: None is not list-like
How is this possible? Type: list, but in error: None.
If this important, my libs:
alembic          1.0.0
Click            7.0
Flask            1.0.2
Flask-Login      0.4.1
Flask-Migrate    2.2.1
Flask-SQLAlchemy 2.3.2
Flask-WTF        0.14.2
itsdangerous     0.24
jdcal            1.4
Jinja2           2.10
Mako             1.0.7
MarkupSafe       1.0
pip              18.1
pkg-resources    0.0.0
python-dateutil  2.7.3
python-editor    1.0.3
setuptools       40.4.3
six              1.11.0
SQLAlchemy       1.2.12
Werkzeug         0.14.1
wheel            0.32.1
WTForms          2.2.1

Traceback:
Traceback (most recent call last):
  File "/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/lib/python3.7/site-packages/flask_login/utils.py", line 261, in decorated_view
    return func(*args, **kwargs)
  File "/src/app/routes.py", line 313, in client_add
    users=form.users.data)
  File "<string>", line 4, in __init__
  File "/lib/python3.7/site-packages/sqlalchemy/orm/state.py", line 424, in _initialize_instance
    manager.dispatch.init_failure(self, args, kwargs)
  File "/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__
    compat.reraise(exc_type, exc_value, exc_tb)
  File "/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 249, in reraise
    raise value
  File "/lib/python3.7/site-packages/sqlalchemy/orm/state.py", line 421, in _initialize_instance
    return manager.original_init(*mixed[1:], **kwargs)
  File "/lib/python3.7/site-packages/sqlalchemy/ext/declarative/base.py", line 747, in _declarative_constructor
    setattr(self, k, kwargs[k])
  File "/lib/python3.7/site-packages/sqlalchemy/orm/attributes.py", line 229, in __set__
    instance_dict(instance), value, None)
  File "/lib/python3.7/site-packages/sqlalchemy/orm/attributes.py", line 1042, in set
    given, wanted))
TypeError: Incompatible collection type: None is not list-like

A: Well, the problem is you are trying to fill in users on Boss model on with None value
Try this in your view:
boss = Boss(short_name=form.short_name.data)
if form.users.data:
    for each in form.users.data: boss.users.append(each)
db.session.add(boss)
db.session.commit()

It should work pretty well
There is a chance that this one works too
boss = Boss(short_name=form.short_name.data, users=form.users.data if form.users.data else [])


text:
Q: Proving absolutely convergence in the disc I want to solve the example below, but I can not.
Use the Hardy-Littlewood theorem to prove that the Taylor series about the orign for $(1-z)^{1/2}$ is absolutely convergent in the disc.
Please, you will be very grateful if someone would help resolve the communities in this example. Previously thank you.

A: I don't really know which theorem of Hardy and Littlewood you are supposed to use here. Maybe I use something of the sort below, maybe I don't.
Write $f(z)=(1-z)^{1/2}=\sum_{n=0}^\infty c_n z^n$.  Differentiating $f $ (or using the binomial formula) we notice that all coefficients $c_n$ with $n\ge 1$  are negative. (Indeed, $f'(z)=-\frac12 (1-z)^{-1/2}$, $f''(z)=-\frac34(1-z)^{-3/2}$, etc: the coefficient in front stays negative.) Therefore, we must show the convergence  of $\sum_{n=1}^\infty (-c_n)$. This amounts to the uniform boundedness of the partial sums of  $\sum_{n=1}^\infty (-c_n)$ from above.
Note that   for any $r\in (0,1)$ the sum $\sum_{n=1}^\infty (-c_n)r^n = 1-(1-r)^{1/2}$ is at most $1$.
Given $N$, pick $r\in (0,1)$ such that $r^N\ge \frac12$. Then
$$\sum_{n=1}^N (-c_n)\le  2 \sum_{n=1}^N (-c_n r^n) \le  2 \sum_{n=1}^{\infty} (-c_n r^n)
\le 2
$$
and we are done.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Select from two tables - sort result by foreign and primary key I have two tables:

*

*Section: _id, name

*Item: _id, name, section_id

I'm trying to sort result in a such way:
1 Section1
1 Item1 1
2 Item2 1
3 Item3 1
2 Section2
4 Item4 2
5 Item5 2

In other words - place items which belongs to section below the section itself.
Is it possible to achieve such result using just one query?
EDIT
For now I'm using INNER JOIN, but it's not completely suitable for my purposes: I need to know exact count of distinct sections inside query and it would be great if I'll be able to know the exact position of next section (for now I'm just sorting by section_id and looking for it changes)

A: Like this perhaps, here is some fiddle
select
        s._id sid,
        s.name,
        null iid
    from
        section s
union all
select
        i.section_id sid,
        i.name,
        i._id iid
    from
        item i
    order by
        sid, iid

A: It can be done like
select section._id as sectionId,section.name, 0  as itemId
from section
union
select item.section_id as sectionId, item.name, item._id as itemId
from item
order by sectionId, itemId


text:
Q: Map of all points below a certain time of travel? My question is very simple and can be understood in one line:
Is there a way, tool, etc. using Google Maps to get an overlay of all surface which is below a certain time of travel?
I hope the question is clear, but I coulnd't find anything related on the web.
If you have any information, I'll take it!
Here is what I mean illustrated by an example:
I search for a new place to live. I know the precise address of my office.
I would in this case be able to overlay on Google Maps the surface which is under a certain time of travel (let's say 30 minuts by car).
We would have a long surface colored around motorways (because you get faster), and colors around roads.

A: Other than the ones in @BioGeek answer, here are some more:
Nokia Here Maps API can give you the exact shape of the output. They call it time-based isoline. See here: Requesting a time based isoline

For travel times under 10 minutes, Isoscope is available at this address.
Also this looks promising: Route360
Update:
Route360 can be used for free in the following places:

*

*Africa

*Austria

*Australia and New Zealand

*British Isles

*British Columbia

*Czech Republic

*Denmark

*France

*Germany

*Italy

*Malaysia, Singapore, and Brunei

*Mexico

*Norway

*Portugal

*Spain

*Sweden

*Switzerland

*USA

A: I think you are looking for the Google Distance Matrix API. It returns not routes, but duration and distance for each pair of origin and destination. It has a usage limit of 100 elements per 10 seconds.
So you can make an educated guess about the distance that matches the desired time of travel, choose six or eight equally distributed points on a circle of that radius, and query the corresponding durations. Then refine the distances according to the results and calculate intermediary points. This way you can get a (quite rough) map in a few iterations.

A: I think you are looking for something like Mapnificient: it shows you areas you can reach with public transportation in a given time (video).

A similar site with even more options is How Far Can I Travel. Here you can choose between inputting your speed of travel and a travel time OR a distance. Optionally, you can also specify how accurate you want the results to be.

Now, how to create such examples yourself? See this related question where the accepted answer explains step-by-step, how you can get travel time data from the Google Maps API.
Finally, for $8.75, you can buy the article Stata utilities for geocoding and generating travel time and travel distance information by  Adam Ozimek and Daniel Miles that describes traveltime, a command that uses Google Maps to provide spatial information for data.

The traveltime command takes latitude and longitude information and
  finds travel distances between points, as well as the time it would
  take to travel that distance by either driving, walking, or using
  public transportation.

A: I don't think there is a simple way of doing this, but here's an idea:
You'd need to first get the long/lat coordinates of your start position. You will then need to work out say, 50 coordinates around that start position that are say, 1 kilometer away from it (the answer here can help). You'd then need to traverse around each of these points and ask for the driving time to get there from your start position using Google Driving Directions API.
You'd then need to traverse the points again to find the points that are below the time of travel allowed (e.g. 30 mins in your question), move these points another kilometer or so away (in the same direction that the point originally moved from the start position) and repeat the driving time request until all are above the time of travel allowed. Finally you end up with 50 coordinates which you can plot onto a Google Maps image as a polygon using the Google Javascript API for mapping polygons.
This method requires a lot of requests to Google so you'll need to think about Google's limit on the number of requests you can do a day.

A: You can use the GraphHopper Directions API - this API part is also open source.
As we've added public transit and this feature recently it currently does not work together. But this is planned and until then you can enjoy road network isochrones :)
Disclaimer: I'm one of the GraphHopper founders.

A: You can draw a circle around your current position and check for a road at an angle every X degrees.
Another idea is to use a contour plot and isolines.


text:
Q: partial eta squared Would it please be possible to help me with a statistics query. I have asked for the partial eta squared on the output of a one-way within subjects ANOVA from SPSS and it has given me the value .137. According to Cohen (1992) the classifications for effect sizes should be; r=.10 small, r=.30 medium and r=.50 large (I am unsure whether these classifications can be attributed to partial eta squared?)
I appreciate this is a basic question but please may I clarify my value falls in the small effect category? Additionally, does this suggest that the proportion of variance explained by the IV on the DV and not explained by other variables in the analysis is 13.7%?
Any help would be greatly appreciated!! Thank you!

A: According to Richardson (2011), Cohen (1969, pp.278-280) provides partial eta squared values of .0099, .0588, and .1379 as benchmarks for small, medium, and large effect sizes, respectively.
Literature:
Richardson, J.T.E. (2011). Eta squared and partial eta squared as measurements of effect size in educational research. Educational Research Review, 6, 135-147.
Cohen, J. (1969). Statistical power analysis for the behavioural sciences. New York: Academic Press.


text:
Q: tkinter setting default checkbox to being checked returns value as "checked" This is my code:
master = Tk()
var1 = IntVar(master)
var1.set(1)
Checkbutton(master, text = 'check', variable = var1)
Button(text = 'submit', command = master.quit')
check = var1.get()

It sets the default to being checked, but even when I uncheck it on the GUI and hit submit, the value of check is still 1.
Why is the action of unchecking the checkbox not being registered?

A: First off the code yo have shown us will not work for a few reason.
You have a ' just after master.quit you also are trying to create a button without assigning it to a window or frame. You have not  used pack(), grid() or place() to place the widgets into a window. You do not need to assign the value of master inside if IntVar().
Most likely the reason you think the value of IntVar() is not changing is because you have assigned the value of IntVar() to the variable check when the program is instantiated.
With the code you have shown us nothing is changing or updating the value of check.
Instead you should use something that can be called on to check the current value of var1 like a function.
Here is a simple program that shows what happens each time you check or uncheck the box.
import tkinter as tk

master = tk.Tk()
var1 = tk.IntVar()
var1.set(1)

tk.Checkbutton(master, text = 'check', variable = var1).pack()

def print_var1():
    print(var1.get())

tk.Button(master, text = "Print Var1", command = print_var1).pack()
tk.Button(master, text = 'Close', command = lambda: master.destroy()).pack()

master.mainloop()


text:
Q: C++/SDL threading - events break down I have a Snake game in-development (up at https://github.com/RobotGymnast/Gingerbread/tree/eventThreaded). Initially, everything (graphics, events, game logic update, physics) were called from a "main" thread. Then I started multithreading (using boost threads). It's been pretty straightforward, but I recently split the graphics display logic into a new thread, which allocated the screen object in its local stack space. Then I split my event-detection and event-handling logic into a new thread. Then my screen stopped appearing. Judging by my command-line output, everything still worked fine, just the screen stopped appearing. It turned out it was hanging on my SDL_SetVideoMode() call.
I fixed this by allocating my screen object in the "main" thread, and passing in a reference to the graphics thread. For some reason, allocating the screen object in a new thread from the event logic was creating problems.
Since this fix, the event-detection and event-handling no longer works. The event checks are still being made, e.g. SDL_PollEvent(), but they're not picking up any events at all (keyboard, mouse, etc.).
My suspicion is that SDL might do some behind-the-scenes thread syncing, but I've been using boost threads. Could this be a problem? SDL threads are rather restrictive, and I'd rather not switch.
Anybody had this issue before? Any recommendations?

A: I'm not sure about SDL, but on several windowing subsystems (I believe on both X and Win32), you cannot modify ANYTHING related to a graphics object or widget, except from the thread which initially created that graphics object/widget.
It doesn't look like (to my limited 10 second google search) SDL abstracts that bit from you -- you'd need to only modify graphics related objects from the thread that created them. To do otherwise is to invite strange behavior.

A: Graphics display logic should almost always be in the main thread, due to some technical considerations on various platforms.
Similarly, the event handling (at least at the low level) should be in the main thread, as events can be posted to specific threads rather than processes.
For the most part I would recommend not calling any SDL functions from anything other than the main thread apart from ones that don't operate on shared state.


text:
Q: PNG truecolor, 8 bit depth, how to read IDAT chunk I have a question regarding a PNG file that I am trying to read (I have attached it in this question)
The file size 328750 bytes
Width 660
Height 330
Color type - truecolor
Bit depth - 24 bits
So here's my question. If it's true color, I assume it's RGB, which is 24 bits. But you do the math, the number doesn't add up. 660 (width) * 330 (height) * 3 bytes (from 24 bits) = 653400 bytes, which is double the actual file size.
Why is that?
I tried to read the IDAT chunk, pretending that each pixel is 3 bytes, and I tried to check the colour and it doesn't match what is displayed.

A: PNG is a compressed image format, so the IDAT chunk(s) contain a zlib-compressed representation of the RGB pixels.  Probably the easiest way for you to access the pixel data is to use a converter such as ImageMagick or GraphicsMagick to decompress the image into the Netpbm "PPM" format.
 magick image.png image.ppm

or
 gm convert image.png image.ppm

Then read the "image.ppm" in the same way you tried to read the PNG.  Just skip over the short header, which in the case of your image is
P   6  \n   6   6   0       3   3   0  \n   2   5   5  \n

where "P6" is the magic number, 660 and 330 are the dimensions, and 255 is the image depth (maximum value for R,G,and B is 255, or 0xff).  The remainder of the file is just the R,G,B values you were expecting.


text:
Q: Cypher Conditional `ORDER BY` clause (same property, differ ASC/DESC) I have two queries:
MATCH (n:Node)
RETURN n.value
ORDER BY n.value DESC
LIMIT 5

MATCH (n:Node)
RETURN n.value
ORDER BY n.value ASC
LIMIT 5

I would like to combine them both by adding an additional parameter. I tried different approaches with CASE statement, but it looks like the CASE statement allows me to change the property of the sort, not the type of the sort...
This is a pseudo-code that does what I'm trying to achieve (But this one obviously doesn't work):
WITH "ASC" AS sortType
MATCH (n:Node)
RETURN n.value
ORDER BY n.value (CASE WHEN sortType = "ASC" THEN ASC ELSE DESC END)
LIMIT 5

So the final question is:

*

*How can I perform a conditional OrderBy clause on the same property (DESC/ASC difference)?

A: You can add a column with a sortValue like this
RETURN  n.value,
        CASE WHEN sortType = 'DESC' THEN n.value * -1 ELSE n.value END AS sortValue
ORDER BY sortValue

Adding the sortValue in your RETURN statement makes that you get either
| value | sortValue |
|     1 |          1|
|     2 |          2|
|     3 |          3|

OR
| value | sortValue |
|     3 |         -3|
|     2 |         -2|
|     1 |         -1|

You can use this mechanism also in case you want to have flexibility with regard to which column you want to sort, as long as you make sure that you put the right value in the sortValue column.

A: You can add 2 expressions for ORDER BY:
     CASE WHEN sortType = "ASC" THEN n.value ELSE null END ASC,
     CASE WHEN sortType = "ASC" THEN null ELSE n.value END DESC

They will be both applied, but the first one won't do anything when sortType is not "ASC" and the second won't do anything when the sortType is "ASC".


text:
Q: mysql order by hour starting from 22:00 I have a table with a time field. The time format is HH:mm.
The hours only go from 22:00 to 06:00.
I want to sort the rows so they look like this:
Hour
22:00
22:30
23:15
00:15
01:30
03:50
05:30

But in my current query:
select * from events order by hour

they look like this:
Hour
00:15
01:30
03:50
05:30
22:00
22:30
23:15

Is it possible? thanks!

A: Try this:
SELECT
    *
FROM
    events
ORDER BY CASE
    WHEN SUBSTR(hour, 1, 2) >= '22' THEN 0
    ELSE 1
END , hour;


text:
Q: is_email gives me error As you can see on this link:
https://cixme.deniz-tasarim.site/video-upload/
after click submit button, wp says me e-mail is invalid but I enter valid e-mail.
Array ( [email_valid] => Email has no valid value )

related code:
  if(is_email($email)) {
            $error['email_valid'] = "Email has no valid value";
        }

full code:
<?php
/* Template Name: Video Upload */

get_header();

    global $wpdb;

    if ($_POST) {

        $username = $wpdb->escape($_POST['txtUsername']);
        $email = $wpdb->escape($_POST['txtEmail']);
        $password = $wpdb->escape($_POST['txtPassword']);
        $ConfPassword = $wpdb->escape($_POST['txtConfirmPassword']);

        $error = array();
        if (strpos($username, ' ')!==FALSE) {
            $error['username_space'] = "Username has Space";
        }
        if(empty($username)) {
            $error['username_empty'] = "Needed Username must";
        }
        if(username_exists($username)) {
            $error['username_exists'] = "Username already exists";
        }
        if(is_email($email)) {
            $error['email_valid'] = "Email has no valid value";
        }
        if(email_exists($email)) {
            $error['email_existence'] = "Email already exists";
        }
        if (strcmp($password, $ConfPassword) !==0) {
            $error['password'] = "Password didn't match";
        }
        if (count($error) == 0) {
            wp_create_user($username,$password,$email);
            echo "User created successfully";
            exit();
        }
        else print_r($error);
    }

?>

        <form method="post">

            Enter Username

            <input type="text" id="txtUsername" name="txtUsername" placeholder="Username"/>

        Enter Email

        <input type="email" id="txtEmail" name="txtEmail" placeholder="Email"/>

        Enter Password

        <input type="password" id="txtPassword" name="txtPassword" placeholder="Password"/>

        Enter Confirm Password

        <input type="password" id="txtConfirmPassword" name="txtConfirmPassword" placeholder="Confirm Password"/>

        <input type="submit" name="btnSubmit"/>
</form>

<?php get_footer(); ?>

A: I was just missing the "not" operator (!) in my conditional (if(is_email($email))), which in turn resulted in valid email addresses being treated as invalid. So I added the ! and that solved the problem:
// code before; incorrect - missing the !
if(is_email($email)) {
    $error['email_valid'] = "Email has no valid value";
}

// code after; working as expected after I added the !
if(! is_email($email)) { // if email is invalid, add the error message
    $error['email_valid'] = "Email has no valid value";
}


text:
Q: Using Torch trained VGG face Is there any way I can pass existing images in my system through a trained VGG with torch? I am using Ubuntu 14.04 and unfortunately do not have a GPU. I have searched quite extensively but all the ones I have found require a GPU. Are there other ways to use VGG without torch? I'm open to suggestions but the method should not require a GPU.

A: While running the network using a GPU will make things a lot faster, you can run the network in CPU mode only.
Once you load the model, pretrained on a GPU you can simple convert it to CPU as follow:
model = model:float()

You can easily load an image from your computer with the help of the image library and then do a forward pass
local img = image.load(imagefile,3,'byte')
 local output = model:forward(img)


text:
Q: C++/CLI. Обновить данные в форме Добрый вечер, есть вопрос, являющийся продолжением этого C++/CLI, глобальный экземпляр формы
Но сейчас проблема в следующем, подобную операцию (обновление данных в форме) мне нужно совершать из обеих форм (Coachs, Visitors).
Подключить обе формы друг в друге я не могу, он ругается, а именно если в Coachs пишу #include "Visitors.h" и в Visitors пишу #include "Coachs.h".
Вопрос в том, как сделать, чтобы я мог обращаться из обеих форм друг к другу. Либо подключить их как написал выше. Либо я попробовал написать метод в статическом классе, но там почему-то вылезает ошибка error C2027: использование неопределенного типа "ооп::xCoachs" Ругается на строке form3->CoachInfo();
Вот собственно, как я модифицировал класс из вопроса, ссылка на который указана в начале.
namespace ооп
{
    ref class Visitors;
    ref class xCoachs;
    ref class GlobalForm abstract sealed
    {
    public:
        static Visitors^ form2;
        static xCoachs^ form3;
        static void CoachsReview()
        {
            form3->CoachInfo();
        }
    };
}

Надеюсь, что здесь меня снова выручат, извиняюсь за свою тупость. Дело в том, что надо обязательно этот проект сдать на C++/CLI.

A: Стандартное решение проблемы перекрёстных зависимостей, что в чистом C++, что в C++/CLI: попробуйте вынести имплементацию в .cpp-файл.
// .h
namespace ооп
{
    ref class Visitors;
    ref class xCoachs;
    ref class GlobalForm abstract sealed
    {
    public:
        static Visitors^ form2;
        static xCoachs^ form3;
        static void CoachsReview();
    };
}

// .cpp
#include "Visitors.h"
#include "xCoachs.h"
#include "GlobalForm.h"

namespace ооп
{
    void GlobalForm::CoachsReview()
    {
        form3->CoachInfo();
    }
}


text:
Q: Unity Text turning black after UR I recently updated my 2D project to use URP. I setuped the global light, canvas is set to world space. Everything is fine but when I assign sprite-lit-default material to the text, it turns BLACK. It works on everything except the text(well it sort of works, but turns it black). Does anyone know what the is issue ? Version is 2019.4.25f1. Thank you
I tried using TextTMPro and the issue is the same....


text:
Q: Using Perl Regex Multiline to reformat file I have the file with the following format:

(Type 1 data:1) B B (Type 1 data:2) B B B
  (Type 1 data:3) B ..

Now I want to reformat this file so that it looks like:

(Type 1 data:1) B B (Type 1 data:2) B B B (Type 1 data:3) B
   ...

My approach was to use perl regex in command line,
cat file | perl -pe 's/\n(B)/ $1/smg'

My reasoning was to replace the new line character with space.
but it doesn't seem to work. can you please help me? Thanks

A: The -p reads a line at a time, so there is nothing after the "\n" to match with.
perl -pe 'chomp; $_ = ($_ =~ /Type/) ? "\n".$_ : " ".$_'

this does almost what you want but puts one extra newline at the beginning and loses the final newline.

A: If the only place that ( shows up is at the beginning of where you want your lines to start, then you could use this command.
perl -l -0x28 -ne's/\n/ /g;print"($_"if$_' < file

*

*-l causes print to add \n on the end of each line it prints.

*-0x28 causes it to split on ( instead of on \n.

*-n causes it to loop on the input. Basically it adds while(<>){chomp $_; to the beginning, and } at the end of what ever is in -e.

*s/\n/ /g

*print "($_" if $_ The if $_ part just stops it from printing an extra line at the beginning.

A: It's a little more involved as -n and -p fit best for processing one line at a time while your requirement is to combine several lines, which means you'd have to maintain state for a while.
So just read the entire file in memory and apply the regex like this:
perl -lwe ^
"local $/; local $_ = <>; print join q( ), split /\n/ for m/^\(Type [^(]*/gsm"

Feed your file to this prog on STDIN using input redirection (<).
Note this syntax is for the Windows command line. For Bash, use single quotes to quote the script.


text:
Q: How to decide whether to store fields in indexes in RavenDB? In the RavenDB 3.x docs, there are multiple articles that touch on the concept of storing field values in indexes, so that transformers can fetch this data from the index itself rather than having to load the document.
However, the exact implications of doing this are not mentioned and it's unclear to me in which situations that this is going to give benefits vs. too much overhead.
The documentation basically says this about it:

Projections and Stored fields
If projection function only requires fields that are stored, then document will not be loaded from storage and all data will come from index directly. This can increase query performance (by the cost of disk space used) in many situations when whole document is not needed.

(Indexes/Querying/Projections and more or less the same in indexes/storing data in indexes)
When reading I read it, it doesn't really feel worth looking in to, but when reading the Query Flow I get more convinced about using this.
If I understand correctly, you could make queries not retrieve the document from storage at all, when using projection + indexes with storage, at the cost of disk space?
Assuming that is correct:

*

*Regarding the extra usage of disk space, how much can I expect? Can anyone stick some numbers on this?

*How much more performant is this? How are these values stored in indexes anyway? How expensive is it to read that stored data vs. a stored document?

What I think intuitively is, that if your document contains 10 numeric fields, and you store 4 of these in an index, you need roughly 40% more disk space? But you also need to read only 40% of your document when querying it using that index?

A: In general, don't bother.
This is appropriate for very specific situations, and it is usually not worth it. Unless you have very large documents (hundreds of KB), it is easier to use projections without using index store or using a transformer.


text:
Q: With FirebaseAuth, can I generate an ID token without a logged-in user? I'm trying to customize my Firebase Functions server using the code sample here: https://github.com/firebase/functions-samples/tree/master/authorized-https-endpoint. In my Angular client, I have succeeded in getting a fresh idToken by manually signing in a 'background' super-user:
constructor(private firebaseAuth: AngularFireAuth) {}
...
this.firebaseAuth.auth
  .signInAndRetrieveDataWithEmailAndPassword(
    environment.firebaseSuperUser,
    environment.firebaseSuperUserPass
  )
  .then((credential: UserCredential) => {
    credential.user.getIdToken().then(token => {
      this.storeTokenInDb(token)
      this.callApi(token)
    })
  })

This is required because the Auth middleware on my server is restricting access to all functions based on this token value:
admin
  .auth()
  .verifyIdToken(idToken)
  .then(decodedIdToken => {
    if (decodedIdToken.uid === 'D1akN6puCwYbkUMJAExTqOEx5fg4') {
      console.log('Token matches admin user')
      return next()
    } else {
      console.error('Failed to match token with admin user.')
      return next('403 Unauthorized')
    }
  })

However, this strikes me as a problematic approach long-term, because I don't want to log-in and log-out my super user every time I want to refresh his token. So my question is, is it possible to get an ID token for a user without logging that user in?
I was hoping for a function like this: FirebaseAuth.getIdToken({uid: 'D1akN6puCwYbkUMJAExTqOEx5fg4'}) that returns an ID token corresponding to any user, whether they're logged in or not. I would like to generate a Firebase ID token for any user any time.
The reason I want this is because my client is sending HTTP GET requests to my Functions server as a "super user" with full access to my api/endpoints (through Bearer token authorization) and write access to the DB:
{
  "rules": {
    ".read": false,
    ".write": "auth.uid === 'D1akN6puCwYbkUMJAExTqOEx5fg4'"
  }
}

Maybe I'm approaching this in the wrong way, but right now I have an ordinary logged-in user, and a second super-user firing off all my API requests. Bottom line is I want to restrict access to my api/endpoint routes to the super user, exclusively. Those routes should only be accessible internally, to the client sending the request. Hope this makes senses, and I'm all ears to a better approach.


text:
Q: Add id to input I have this input: <input type="text" name="1">.
Using vanilla JS how can I assign an id to it? To make it look like this: <input type="text" name="1" id="2">.
Have this so far, does not work, and I cannot find out why...
var xyz = document.getElementsByName(1");
xyz.setAttribute("id", "2");

A: getElementsByName returns array. You need set attribute to single element. Hack: xyz[0].setAttribute...

A: As VeroLom said,

getElementsByName returns array.

So you have to return only one element :
var xyz = document.getElementsByName(1")[0]; // there, I pick the first element of the array
xyz.setAttribute("id", "2");

A: var xyz = document.getElementsByName("myName");
xyz[0].id = "myId";

or
xyz[0].setAttribute("id", "myId");

Please notice that IDs and names can't start wit a number.

A: They function .getElementsByName(1) returns an array of HTML DOM object with the name 1.
To access the first element try this:
xyz = document.getElementsByName("1")[0];
xyz.setAttribute("id", "2");

and by the way, ID's should start with a letter.

A: var xyz = document.getElementsByName(1");
xyz.setAttribute("id", "2");

This gives you an array of elements by name "1". So you need to traverse and give id to each element.
So, if you are sure you have only one element with this name you can do
 var xyz = document.getElementsByName("1")[0];
 xyz.setAttribute("id", "2");


text:
Q: adding a custom link to a wordpress site I have a wordpress menu plugin that comes with a theme, unfortunately the theme was limited in that, it did only provide on menu, I wanted to add another menu to it. I have found where I wanted to add my link in the theme. I found that one menu provided by the theme

    <a href="<?php echo esc_url(cs_users_profile_link($cs_page_id, 'gallery', $uid)); ?>" <?php echo force_balance_tags($data_toogle); ?>> <?php _e('gallery', 'thematic'); ?>

And duplicated that twice, but the problem if the link takes me to a page http://foo.bar/?author=1
Is there anyway I can modify this link so it takes me to a page found http://foo.bar/playground ?

A: Can you change the href attribute of the link?

     <?php _e('gallery', 'thematic'); ?>


text:
Q: How you read PDF with python 3.x using only default libraries? I need to read information from PDF file using, python or robotframework, however I can not install any external libraries due to my company rules. Is it possible and how I could do that?

A: Of course it is!
You'll just have to write the parser for PDFs from scratch. You can find the PDF 1.7 file specification over here at Adobe.com, it's only 756 pages.
On a more serious note, not being able to use any external libraries in any circumstances is idiotic – that company rule is misguided, and those who enacted it probably are using oodles of unvetted external code anyway.
(If you are allowed to install system packages, though, pdftotext from Poppler might help you a bit.)

A: I have used this one: https://github.com/euske/pdfminer/blob/master/tools/pdf2txt.py.
Used the script to convert PDFs to strings and then tested the contents.


text:
Q: Adding element from a list to a class object I've got a class Animal, with attributes Name, Age, Gender and Species. I've got a list with split elements like this:
li = ['George', '23', 'Monkey', 'Male', 'Mike', '31', 'Racoon', 'Male']

Now I want to take four elements at a time, and add to new Animal objects.
I really can't figure out how to. Can someone help me with this?

A: This may help you get started:
class Animal(object):
    def __init__(self, Name, Age, Species, Gender):
        self.name = Name
        self.age = Age
        self.species = Species
        self.gender = Gender

li = ['George', '23', 'Monkey', 'Male', 'Mike', '31', 'Racoon', 'Male']

first_animal = Animal(*li[0:4])
second_animal = Animal(*li[4:])

print("""
First Animal is:
gender: {0.gender}
age: {0.age}
name: {0.name}
species: {0.species}""".format(first_animal))

Outputs:
First Animal is:
gender: Male
age: 23
name: George
species: Monkey

A brief explanation, "chunking of the list" can be done many ways, I just chose to use the *, splat operator, and slice the contents.
Instantiating objects from the class was borrowed from this tutorial Learn Python the Hard Way, bottom of the page "A First Class Example".
I didn't put these new class objects into a new list, but as everything in python is an object, and you know how to create lists as you did in your question, I'll leave that trivial part out.
Hope this helps.


text:
Q: Angular 5 Ngrx State lost during browser page refresh I am new to angular 5 and Ngrx, some how i managed to implement a login functionality, once login is success i am taking the user to dashboard. But if I refresh the page the user state seems to be lost. How to make the user state persistent even the page reloads ?

A: local-storage and sessions-storage introduce security risks (user info can be manipulated) and I think there is a better answer to how to address the underlying issue of how to survive a browser refresh.
In general, you're probably better off putting some code into the app component's onInit method to reload data that needs to survive a browser refresh.

A:
How to make the user state persistent even the page reloads?

as @user184994 Mentioned NGRX state is only held in memory. If you want it to persist between page refreshes Go for LocalStorage or sessionStorage
localStorage and sessionStorage accomplish the exact same thing and have the same API, but with sessionStorage the data is persisted only until the window or tab is closed, while with localStorage the data is persisted until the user manually clears the browser cache or until your web app clears the data.
I would suggest you to go for @ngx-pwa/local-storage Async local storage for Angular
For Angular 5:
npm install @ngx-pwa/local-storage@5

Register it in your RootModule
import { LocalStorageModule } from '@ngx-pwa/local-storage';

@NgModule({
  imports: [
    BrowserModule,
    LocalStorageModule,
    ...
  ]

Inject and use it
import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable()
export class YourService {

  constructor(protected localStorage: LocalStorage) {}

}

Usage
let user: User = { firstName: 'Henri', lastName: 'Bergson' };

this.localStorage.setItem('user', user).subscribe(() => {});


text:
Q: Understanding more about Telerik Platform We are coming from .NET developers and trying to figure out this sample application Telerik Platform work utilizing Cordova (hybrid mode) especially for JavaScript.
The code is what we believe is Model for handling the activities. Is this correct? The syntax is a bit weird. It looks different from what we know. Can't figure out which one is method and which one is property.
It seems there is no more information about this type of Javascript. Where can I find more about this info beside Telerik site.
 /**
 * Activities view model
 */

var app = app || {};

app.Activities = (function () {
    'use strict'

    // Activities model
    var activitiesModel = (function () {

        var activityModel = {

            id: 'Id',
            fields: {
                Text: {
                    field: 'Text',
                    defaultValue: ''
                },
                CreatedAt: {
                    field: 'CreatedAt',
                    defaultValue: new Date()
                },
                Picture: {
                    fields: 'Picture',
                    defaultValue: null
                },
                UserId: {
                    field: 'UserId',
                    defaultValue: null
                },
                Likes: {
                    field: 'Likes',
                    defaultValue: []
                }
            },
            CreatedAtFormatted: function () {

                return app.helper.formatDate(this.get('CreatedAt'));
            },
            PictureUrl: function () {

                return app.helper.resolvePictureUrl(this.get('Picture'));
            },
            User: function () {

                var userId = this.get('UserId');

                var user = $.grep(app.Users.users(), function (e) {
                    return e.Id === userId;
                })[0];

                return user ? {
                    DisplayName: user.DisplayName,
                    PictureUrl: app.helper.resolveProfilePictureUrl(user.Picture)
                } : {
                    DisplayName: 'Anonymous',
                    PictureUrl: app.helper.resolveProfilePictureUrl()
                };
            },
            isVisible: function () {
                var currentUserId = app.Users.currentUser.data.Id;
                var userId = this.get('UserId');

                return currentUserId === userId;
            }
        };

        // Activities data source. The Backend Services dialect of the Kendo UI DataSource component
        // supports filtering, sorting, paging, and CRUD operations.
        var activitiesDataSource = new kendo.data.DataSource({
            type: 'everlive',
            schema: {
                model: activityModel
            },
            transport: {
                // Required by Backend Services
                typeName: 'Activities'
            },
            change: function (e) {

                if (e.items && e.items.length > 0) {
                    $('#no-activities-span').hide();
                } else {
                    $('#no-activities-span').show();
                }
            },
            sort: { field: 'CreatedAt', dir: 'desc' }
        });

        return {
            activities: activitiesDataSource
        };

    }());

    // Activities view model
    var activitiesViewModel = (function () {

        // Navigate to activityView When some activity is selected
        var activitySelected = function (e) {

            app.mobileApp.navigate('views/activityView.html?uid=' + e.data.uid);
        };

        // Navigate to app home
        var navigateHome = function () {

            app.mobileApp.navigate('#welcome');
        };

        // Logout user
        var logout = function () {

            app.helper.logout()
            .then(navigateHome, function (err) {
                app.showError(err.message);
                navigateHome();
            });
        };

        return {
            activities: activitiesModel.activities,
            activitySelected: activitySelected,
            logout: logout
        };

    }());

    return activitiesViewModel;

}());

A: Yes this are javascript objects. They seem a little different because they are being created using what is known as the Functional Pattern. One of its principles is to emulate private data as everything in javascript is declared in the global scope except whatever you declared inside a function, which creates a new scope hence it cannot be seen from the outside. You can google it or if your willing to document yourself i suggest you to read "Javascript: The Good Parts from Douglas Crockford" as it contains almost everything to be considered best practices for javascript these days.


text:
Q: Fabric raise error if grep results returned I am using Fabric to deploy Django (of course). I want to be able to run a local command which greps a string, and if returns any results, raises an exception and halts deploy.
Something like:
local('grep -r -n "\s console.log" .')

So if I get > 0 results, I want to halt progress.
What is the best way to handle this?

A: Run it like this:
with settings(warn_only=True):
  local('grep -r -n "\s console.log" .')

This will prevent Fabric from aborting the script execution in case the call returns anything different to zero.


text:
Q: cvc4 mkconst from std::string in C++ api I need to change "123" into a const in c++
what I coded as
ExprManager em;

Rational i = Rational("123",10);

Expr expri = em.mkConst(i);

or
Integer i = Integer("123", 10);

Expr epri = em.mkConst(Rational(i,1));

but I got some error

Undefined symbols for architecture x86_64:
    "___gmpq_canonicalize", referenced from:
        __gmp_expr<__mpq_struct [1], __mpq_struct [1]>::canonicalize() in ex1-4f9d4d.o
    "___gmpq_clear", referenced from:
        __gmp_expr<__mpq_struct [1], __mpq_struct [1]>::~__gmp_expr() in ex1-4f9d4d.o
    "___gmpz_clear", referenced from:
        __gmp_expr<__mpz_struct [1], __mpz_struct [1]>::~__gmp_expr() in ex1-4f9d4d.o
    "___gmpz_init_set", referenced from:
        __gmp_expr<__mpq_struct [1], __mpq_struct [1]>::__gmp_expr(__gmp_expr<__mpz_struct [1], __mpz_struct [1]> const&, __gmp_expr<__mpz_struct [1], __mpz_struct [1]> const&) in ex1-4f9d4d.o
    "___gmpz_init_set_si", referenced from:
        __gmp_expr<__mpz_struct [1], __mpz_struct [1]>::init_si(long) in ex1-4f9d4d.o
  ld: symbol(s) not found for architecture x86_64

A: The problem above is caused by lack of GMP library.
Installed GMP with "brew install gmp" on Mac.
compile the program with "-lgmp" flag
Problem solved.


text:
Q: JavaScript: Pushing a list to a new list with repeating values in original using a for loop I have a list List = [Boy, Boy, Boy, Girl, Boy, Key, Girl] how do I grab only the each of these values and push it on to another new array in JavaScript using a for loop?
Input = [Boy, Boy, Boy, Girl, Boy, Key, Girl]
Output = [Boy, Girl, Key]


text:
Q: Can I automate files being added to my solution explorer in VS15? I'm working in Visual Studio 15, and have a project that constantly has assets being added to it. The problem is forgetting to add the new/updated assets to the solution and set up their properties each time one is added.
Is there a way to have VS recursively check a certain directory for new/changed files, import them to the Solution Explorer, and change their build properties?
The properties I'm referring to are "Build Action", "Copy to Output Directory", etc.


text:
Q: How do you tell which tombstones are weaponized? The Blade bike drops 'weaponized tombstones' which temporarily blind opponents who collect them.  As seen in video below.
Is there a way to see these coming before hitting them?

A: Weaponized tombstones flash a bright whiter tone rapidly, you can actually see it in the video above once you know what you're looking for.


text:
Q: Apache server not listening on IPv4 but listening on IPv6 We are facing one weird problem on one of our RHEL apache server.
Actually, it is not listening on port 80 from remote hosts. When we locally browse http://localhost it is opening default page. When we checked listening port through netstat, we found that only tcp6 interface was listening at :::80.
And there was no entry for tcp, and that entry should be present there like
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN

I have tried searching many forums for this issue, but none of the solution suggested worked. In httpd.conf, we change Listen 80 to Listen 0.0.0.0:80and Listen 127.0.0.0:80
but it did not open 80 port to access from remote hosts. IPtables is disabled from the beginning.
How can we set the server to listen on IPv4?

A: assiduus@localhost:~/httpd-2.4.34$ ./configure --help | grep IPv6

--enable-v4-mapped      Allow IPv6 sockets to handle IPv4 connections

assiduus@localhost:~/httpd-2.4.34$

This is enabled by default when you compile Apache httpd from source. If you used your distribution binary package then apparently this option is enabled.

A: Use something similar to this configuration:
<VirtualHost *:80>
   ServerName www.domain.com
   ServerAlias domain.com

   DocumentRoot /path/to/your/webroot/
   ...

</VirtualHost>

The ":80" allows your web server to listen on all ip address on port 80; however this will not take effect until this newly created virtualhost configuration file is enabled and web server is restarted.
Enable your new virtualhost configuration:
a2ensite domain.com.conf

Restart the webserver
service apache2 restart

To verify that web server listens on both ipv4 and ipv6, check with:
netstat -plunt |grep ":80"

Let me know if this help :)


text:
Q: Connect a CentOS 6 server to the internet without a router I have a CentOS 6 web server. My ISP gave me one public IP/mask/gateway/DNS.
I entered these parameters on my Windows laptop where I get internet. I can ping outside and etc. Then I entered these parameters on my web server, which doesn't see internet, and can't ping (as I can't ping it from outside too). The firewall is off.
How can I connect it to the internet with a public IP? Should I write additional routes?

A: It does sound like you may be missing your default gateway. Try a 'route add default gw ' to manually specify a gateway.

A: I found out what the problem was. I added my physical NIC in the server, my eth0 became wan and eth1 became lan.
I tried all my settings with the LAN interface which didn't have access to the outside. Thanks everyone for the help.


text:
Q: A point charge near a conducting cylinder As we could figure out the point charge induced image charge on a conducting sphere in Jackson's book. Is there any way to figure out the point charge induced image charge form on a conducting cylinder/rod?
Please give me some suggestions, references, literature on how to solve this.
Most of the papers I found are charge inside a cylinder, however, I'd like a cylinder sensing the point charge influence while the charge is moving.
ps. On conducting sphere Jackson Sec. 2.2 to 2.4


text:
Q: jQuery accordion grouping I have a list of a model to a view with an accordion:

        @for (int i = 0; i < Model.Count; i++)
        {

@Model[i].user.FullName&nbsp
                @Model[i].ReasonDescription
                @Model[i].ProgramSite&nbsp-&nbsp @Model[i].Location

                @Html.HiddenFor(x=>Model[i].user.ID, new { @id = "txtId" + @Model[i].ID})
                @Html.HiddenFor(x=>Model[i].user.userSSN, new { @id = "txtSSN" + @Model[i].ID})
                @Html.HiddenFor(x=>Model[i].user.DODID, new { @id = "txtDodid" + @Model[i].ID})

      //////etc

They are all in a sorted order.  Is there a way to create groups of this list so that the there are several accordions?  Do I have to create groups in the model first?  Any ideas?


text:
Q: Best way (Or workaround) to specialize a template alias I'm currently implementing a tiny metaprogramming-based compile-time computations library.
If have defined a base class for operators, which has a result typedef (I have decided to use integral wrappers like std::integral_constant as values instead of raw integral values, to provide an uniform interface along the library), and a n-ary operator base class, that checks if the operators has at least one operand:
template<typename RESULT>
struct operator
{
    using result = RESULT;
};

template<typename RESULT , typename... OPERANDS>
struct nary_operator : public operator<RESULT>
{
    static_assert( sizeof... OPERANDS > 0 , "An operator must take at least one operand" );
};

So I defined alias for unary and binary operators:
template<typename OP , typename RESULT>
using unary_operator = nary_operator<RESULT , OP>;

template<typename LHS , typename RHS , typename RESULT>
using binary_operator = nary_operator<RESULT , LHS , RHS>;

That operator interfaces are used to define custom operators as alias, like comparison operators below:
template<typename LHS , typename RHS>
using equal = binary_operator<LHS,RHS,bool_wrapper<LHS::value == RHS::value>>;

template<typename LHS , typename RHS>
using not_equal = logical_not<equal<LHS,RHS>>;

template<typename LHS , typename RHS>
using less_than = binary_operator<LHS,RHS,bool_wrapper<LHS::value < RHS::value>>;

template<typename LHS , typename RHS>
using bigger_than = less_than<RHS,LHS>;

template<typename LHS , typename RHS>
using less_or_equal = logical_not<bigger_than<LHS,RHS>>;

template<typename LHS , typename RHS>
using bigger_or_equal = logical_not<less_than<LHS,RHS>>;

Now suppose we want to implement our custom equality operator for our own class. For example:
template<typename X , typename Y , typename Z>
struct vec3
{
    using x = X;
    using y = Y;
    using z = Z;
};

If the equality operator was made upon inheritance, instead of aliasing, this could be easily done through template specialization:
//Equality comparator implemented through inheritance:
template<typename LHS , typename RHS>
struct equal : public binary_operator<LHS,RHS,bool_wrapper<LHS::value == RHS::value>> {};

//Specialization of the operator for vec3:

template<typename X1 , typename Y1 , typename Z1 , typename X2 , typename Y2 , typename Z2>
struct equal<vec3<X1,Y1,Z1>,vec3<X2,Y2,Z2>> : public binary_operator<vec3<X1,Y1,Z1>,vec3<X2,Y2,Z2> , bool_wrapper<X1 == X2 && Y1 == Y2 && Z1 == Z2>> {};

I know that template alias cannot be specialized.
My question is: Is there a way, that is not to use inheritance design instead of template aliases, to specialize this kind of template aliases?

A: The pattern I use to specialize template aliases (or provide recursive aliases) is to have a corresponding _impl struct. For example:
template <typename T>
struct my_alias_impl { /* def'n */ };

template <>
struct my_alias_impl<int> { /* alternate def'n */ };

template <typename T>
using my_alias = my_alias_impl<T>;

Users would have to specialize on my_alias_impl instead, but the rest of the public interface remains clean.

A: I know this is an old question, but it's a common problem and there's no satisfying answer in this thread up to now ... so I'll try to give one -- which addresses the general problem rather than the specific question (note that C++14 is required).
namespace impl
{
    template<typename ... Args> struct A;
    template<typename T> struct A<T>
    {
        A() {std::cout<<"I'm an A"<<std::endl;}
    };

    template<typename ... Args> struct B;
    template<typename T, typename V> struct B<T, V>
    {
        B() {std::cout<<"I'm a B"<<std::endl;}
    };
}

template<typename ... Args>
using C = std::conditional_t<sizeof...(Args)==1
                          , typename impl::A<Args ...>
                          , typename impl::B<Args ...> >;

int main()
{
    C<double> a;            //prints "I'm an A"
    C<double, int> b;       //prints "I'm a B"
}

DEMO
The code should be self-explaining: the main idea is to statically choose the type based on the number of arguments. The variadic declarations of A and B are necessary, otherwise the compiler complains that it can't instantiate a B with a single parameter or an A with two parameters, resp.
This approach is surely not completely general -- just think of default arguments or specializations of B -- but maybe it can be extended also to handle such situations. Nevertheless I found it sometimes useful in my coding.

A: Type-alias cant be specialized but if your aim is to simplifiy traits syntactically then you can do it as I do. I combine related traits together in a blob which is anit-pattern but then I use inheritence on the blob itself instead of specialization to override a trait
#define DEFINE_TRAIT(TraitClass,TraitName)                             \
template<typename... T> using TraitName = typename TraitClass<T...>::TraitName

DEFINE_TRAIT(BinaryOpTrait, equal);
DEFINE_TRAIT(BinaryOpTrait, not_equal);
...
...

template<typename LHS , typename RHS>
struct BinaryOpTraitBase
{
    using equal = binary_operator<LHS,RHS,bool_wrapper<LHS::value == RHS::value>>;
    using not_equal = logical_not<::equal<LHS,RHS>>;
    ...
    ...
};
template<typename LHS , typename RHS>
struct BinaryOpTrait : BinaryOpTraitBase <LHS, RHS> {};

typename<>
struct BinaryOpTrait<vec3, vec3> : BinaryOpTraitBase<vec3, vec3>
{
    using equal = /* custom op */
};

//Usage:
    if(equal<int,int>(1,1))
        ...
    if(equal<vec3,vec3>(v1,v1)  //uses specialized
        ...


text:
Q: Options menu not appearing in Sony Xperia Z I have an Android application where an options menu is essential for setting up some preferences values.
Here minimum SDK version is 8 and the xml for the menu is like below.

<item
    android:id="@+id/mainmunu_setting"
    android:icon="@android:drawable/ic_menu_preferences"
    android:title="@string/settings">
</item>

In Samsung devices I can open the menu as there is a menu button, but in Xperia Z there is no menu button and the the menu is not visible on the ActionBar either as the ActionBar is not customizable for SDK version 11 or below according to this:
How do I change the background color of the ActionBar of an ActionBarActivity using XML?
How can I have a menu appearing on Sony Xperia Z.
On Xperia Z device

On Samsung Galaxy S Duos 2 device

Thank you!

A: If your app is targeting API level 11+ then the menu dots will disappear. By targeting API 8 then you should find the overflow menu appears on the navigation bar of the Xperia Z. I'd highly suggest though targeting a higher level API and actually increasing your minimum SDK since a small percentage of devices now use SDK level 8 or less.


text:
Q: Comments counter only for Authors Posts I am building a blog website with many authors. So i have been trying to keep privacy for each author in the back end admin area.
I have been using a nice plugin (https://wordpress.org/plugins/view-own-posts-media-only/) that give to the author only his own posts result in the backend, and also in the edit-comments.php the comments that are related with the authors post only, which is great.
The only problem or malfunction of the plugin is the comments counter in admin area. The plugin is not actually filtering the comments number for author posts criteria.
I have been trying to find some snippet to use just for this reason only. I found this post https://bnks.xyz/showing-an-author-only-their-comments-in-wordpress/ and tried only the comments counter part, but didn't gave me correct results.
Is there any snippet for this problem? How to give to the author the correct counter results, only related to his own posts?
I was trying even if possible to hide just the counter, from the admin with css but i couldn't, as i find the same css also hides other counters. (I don't want to disable the entire comments counter nor to hide the edit-comments.php from author)
Any suggestions would be appreciated.

A: For the moment just for hiding the comments counter from an author role, i made a small code like that
 /*
 * Hide Comments Counter for Author Hook
 */
 if ( ! current_user_can( 'manage_options' ) ) { add_filter(
'comment_status_links', function( $status_links )
{

// Override the original links:
$status_links['trash'] = sprintf(
  "%s ",
  esc_url( admin_url( 'edit-comments.php?comment_status=trash') ),
  __( 'Trash' )
);
$status_links['spam'] = sprintf(
  "%s ",
  esc_url( admin_url( 'edit-comments.php?comment_status=spam') ),
  __( 'Spam' )
);
$status_links['approved'] = sprintf(
  "%s ",
  esc_url( admin_url( 'edit-comments.php?comment_status=approved') ),
  __( 'Approved' )
);
$status_links['moderated'] = sprintf(
  "%s ",
  esc_url( admin_url( 'edit-comments.php?comment_status=moderated') ),
  __( 'Pending' )
);
$status_links['all'] = sprintf(
  "%s ",
  esc_url( admin_url( 'edit-comments.php?comment_status=all') ),
  __( 'All' )
);
return $status_links;
} ); }

if ( ! current_user_can( 'manage_options' ) ) { add_action('admin_menu',
'hide_notification_bubble_in_admin_menu'); }

function hide_notification_bubble_in_admin_menu() {
global $menu;
// Override the original links:
$menu[25][0]    = sprintf( __( 'Comments %s' ), '' );
}


text:
Q: Found two getters or fields with conflicting case sensitivity for property: s however, I don't have an "s" property of the classes nor Firebase I don't have an "s" property of the classes or in Firebase and line 12 of FeedService points to: import android.os.IBinder; and no cause in the code of class FeedService. This only happens in the minified and obfuscated version published on the PlayStore for testing.
I've read all the questions and answers on the topic and nothing solves my problem.
Good to know: all variables and attributes are in CamelCase PRIVATE, both in Firebase and in POJO Classes and the corresponding getters and setters are PUBLIC.
Does anyone have an idea how to solve it?
    buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: br.com.site.app, PID: 18293
    d.d.c.m.d: Found two getters or fields with conflicting case sensitivity for property: s
        at d.d.c.m.x.b1.q.a$a.a(Unknown Source:40)
        at d.d.c.m.x.b1.q.a$a.<init>(:5)
        at d.d.c.m.x.b1.q.a.e(Unknown Source:12)
        at d.d.c.m.x.b1.q.a.b(:4)
        at br.com.site.app.service.FeedService.z(:12)
        at d.d.c.m.x.b.d(:11)
        at d.d.c.m.x.c1.d.a(Unknown Source:2)
        at d.d.c.m.x.c1.h.run(:6)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7397)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)

A: Finally, I came up with a solution to my problem:
Make sure your POJO follows the coding STYLE STANDARDS for attributes, methods, and constants; put TRANSIENT on everything inside the POJO that shouldn't be SERIALIZED; the Attributes in Firebase must be EXACTLY the same as in POJO; DO NOT USE, for example: myAtributteURI or executeMyAtributteURI(), but myAtributteUri and executeMyAtributteUri(). Remember that it will run in Debug, but it will bug in the minified, obfuscated version. Therefore, follow the Proguard rules specific to FIREBASE. In this link:
https://firebase.google.com/docs/database/android/start#proguard


text:
Q: Deploy angular playground sandbox app within a shared library codebase I have a common shared library which houses buttons, input components, datepicker etc. this library is shared across many other applications. Now the shared library also has a sandbox playground code for developers to see which components the library has. I have a need to deploy the sandbox playground code to an internal server. How do i go about it? Should i have two package.json in the same repo or it would be better to have a separate repo for sandbox playground code. Please let me know my options here.
Below is the structure for both apps: (Image attached below)
> projects
      component
      src
          assets
          lib
      package.json
      tsconfig.lib.json
      tsconfig.lib.prod.json
> src
      app
         components
      tsconfig-app.json
      polyfills.ts
> package.json (on root folder)
> tsconfig.json
> Jenkinsfile
> Dockerfile

projects/component/src/lib ------> shared library code
src/app ---------------> sandbox playground code
my-project-structure image
below is the package.json on root level:

{
  "name": "shared-lib",

  "version": "1.0.0",

  "scripts": {

    "ng": "ng",

    "start": "ng serve",

    "build_lib": "ng build component && scss-bundle -e ./projects/component/src/assets/_index.scss -d ./dist/component/assets/main.scss && npm run copy && npm run copy_themes",

    "copy": "cpx \"./projects/component/src/assets/scss/{_variables.scss,_mixins.scss}\" dist/component/assets",

    "copy_themes": "cpx \"./projects/component/src/assets/themes/*\" dist/component/assets/themes",

    "npm_pack": "cd dist/component && npm pack",

    "package": "npm run build_lib && npm run npm_pack",

    "test": "ng test",

    "lint": "ng lint",

    "precommit": "lint-staged",

  },
}


text:
Q: Why do we want maps to be measurable (in countably-additive setting) When I have to explain things that I am doing to people who did not do (or even did not learn) measure-theoretical probability, I think of getting a question in the title, and I am not sure I have arguments strong enough to convince that measurability is indeed the must.
Let me focus on a particular case of stochastic optimization in discrete time, in the setting of countably-additive probabilities. Being it formulated as a dynamic programming, or a gambling problem, one requires the decision to be Borel (universally, analytically) measurable with respect to the current state. Such requirement further leads to known issues as non-existence of measurable selectors. I do understand, that if the selection is not measurable, then it is not possible to define a probability measure over the space of state trajectories in a formal way. However I am no sure whether such explanation is convincing enough, since one can further argue that formal definition of probability requires measurability just in this particular framework, and perhaps the framework is something to be fixed.
It seems that Dubins and Savage used the finitely-additive framework at least for the reason to escape the measurability issues (as it written in Section 1.3 "Gambles"). So does it mean, that this question can be reduced to whether to deal with $\sigma$-additive probability or finitely-additive one?
Edited: in the edit I wanted to address the point raised by Yuri in his answer. I do know that measurability serves at least for the two goals: to define the regularity (nice sets, nice functions) and the information/dependence structure which follows from the following theorem:

If $X$ and $Y$ are measurable maps such that $Y$ is $X$-measurable, then there exists a measurable map $f$ such that $Y = f(X)$.

Note, however, that $X$-measurability of $Y$ guarantees the existence of a measurable map $f$. If we are just interested in a non-meaurable one, then a necessary and sufficient condition would be that level sets (pre-images) of $Y$ are saturated w.r.t. level sets of $X$. As far as I know, the dependence/information structures e.g. in game theory may be defined just based on such partitions, and serve equally well for that goal as much as $\sigma$-algebras. On the other hand, the use of the latter comes with an expense of dealing with measurable maps exclusively, which appears to be unnecessary at least for the particular of defining information structures.
The regularity task seems to be more in the need of measurability, but the only reason I could see here is the ability to measure nice sets or, more generally, to integrate nice functions. Indeed, if we fix a $\sigma$-algebra, and define a $\sigma$-additive finite measure on it, we can integrate any bounded measurable functions (which is such a nice thing after I struggled on my first year with Riemann integrability). However, yet again - is it just a nice, neat and beautiful way of doing this, or is it the way and this is way the requirements on the measurability of maps are not just due to the (relative) simplicity of dealing with them.
Perhaps, there is also a possible reason for the need of measurability besides the information structure modeling or integrating nice functions, but I don't know what could it be. I must say that I love measure-theory a lot, and found it extremely beautiful - I just want to understand myself (and also to be able to convince others) why shall we deal with measurable structures.

Summary: in a view of the answer by Alexander, comments of Yuri and a conversation I had with Michael Greinecker, being asked the entitling question, I would argue that indeed on can define integration and probability without the notion of measurability - but in such a case one may loose many intuitive properties (e.g. LLN) which would make the interpretation of the result harder. In a particular case of the optimal control, I guess the argument could be: applying a non-measurable strategy is permitted, yet may no be able to which value would it yield, and what does this value mean (e.g. without LLN).

A: Regarding measurability: Depending on the audience, it may help to say that standard limit theorems (LLN, CLT, etc.) require measurability (here's something very simple I wrote recently on what you can say in the way of LLN without measurability--basically nothing, except for what you get by applying the standard W/S LLN to the measurable minorant/majorants).  Most of the practical applications of probability theory depend in some way on limit theorems: e.g., statistics and CLT, stochastic algorithm convergence, Bayesian convergence, etc.
Regarding finite additivity: On the bright side, if one replaces countable with finite additivity one gets to keep some limit theorems (at least those that give explicit bounds on convergence of distributions: just approximate r.v.'s on a finitely additive space with simple ones, and apply the standard theorems to the simple ones).
On the dark side, replacing countable additivity with finite additivity will not make all sets measurable in dimensions $n\ge 3$, due to Banach-Tarski issues.  In situations where there are rotational symmetries, one will still have to have non-measurable sets, assuming AC.

A: You can do many more things with measurable functions than with nonmeasurable ones, so the theory is richer and has more applications. There's much less trouble with integrals, for example, right?
In fact, if in the beginning the measurability seems a necessary evil, in the end it becomes a blessing and helps interpreting things. E.g., if a random variable $Y$ is measurable with respect to a sigma-algebra generated by a random variable $X$ then $Y$ can be expressed in terms of $X$, i.e., $Y=f(X)$ for some $f$. Similarly, many concepts of dependence like the Markov property, martingale property, notions from stochastic control, etc. are natural to formulate in terms of measurability w.r.t. appropriately chosen sigma-algebras.


text:
Q: Using web worker for api calls I'm trying to figure out a clean way for using web workers in order to perform api calls, so far I have this going in client side:
worker-client.js
export const workerFetch = (method = "get", url = "/", data = {}) =>
  new Promise((resolve, reject) => {
    const listener = `worker_fetch_${url}_${new Date()}`;
    window.lootWorker.postMessage({
      cmd: "worker_fetch",
      payload: { method, url, data, listener }
    });
    window.addEventListener(
      "message",
      ({ data }) => {
        if (data.cmd === listener) {
          if (data.success) resolve(data.data);
          else reject(data.data);
        }
      },
      false
    );
  });

so this function can be called from the client and given some parameters.
inside web worker itself
worker-thread.js
const workerFetch = ({ method = "get", url = "", data = {}, listener = "" }) => {
  fetch({ method, url, data })
    .then(({ data }) => {
      self.postMessage({ cmd: `worker_fetch_${listener}`, success: true, data });
    })
    .catch(error => {
      self.postMessage({ cmd: `worker_fetch_${listener}`, success: false, data: error });
    });
};

self.addEventListener(
  "message",
  ({ data }) => {
    switch (data.cmd) {
      case "worker_fetch":
        workerFetch(data.payload);
        break;
      default:
        return null;
    }
  },
  false
);

In theory this works, but I am concerned about bubbling up those event listeneres in client side, hence this question to see if there is a common way of achieving this functionality that focuses on performance? As after all we are doing this to offload some things from the main thread.

A: I'd have a few reservations about this pattern:

*

*Remember that only the processing of the response is happening on another thread so you'd need to be sure processing your payload is a bottleneck before offloading all fetch requests.

*If you are concerned about bubbling, you should set useCapture in addEventListener to true and use stopPropagation to prevent bubbling to children

*You are assuming that all fetch calls return in sequence. Now that you're offloading to a worker this can no longer be guaranteed. So you'd need to tag each request with some sort of identifier.
How you implement #3 would be up for debate. If you are focusing on performance, you might want to research some performance UUID generators.
And finally, there appears to be a npm package achieving this functionality: fetch-worker


text:
Q: Allow multiple values with SSRS I want to use IN @Parameter while using dateadd function in below code
 declare @interval int
--set @interval
SELECT ROW_NUMBER() OVER (ORDER BY datetime) AS Row,
       RIGHT(LEFT(E.Name,  11), 8) AS Device, P.[DateTime],
       day(p.DateTime) AS Day,
       month(p.DateTime) AS Month,
       P.AverageValue, p.StandardDeviation
FROM [dbo].[vManagedEntity] AS E
INNER JOIN [Perf].[vPerfDaily] AS P ON E.ManagedEntityRowId = P.ManagedEntityRowId
INNER JOIN [dbo].[vPerformanceRuleInstance] AS I ON
P.PerformanceRuleInstanceRowId = I.PerformanceRuleInstanceRowId
INNER JOIN [dbo].[vPerformanceRule] AS R ON R.RuleRowId = I.RuleRowId
WHERE     right(left(e.name,6),3)  IN (@Site)
      AND R.CounterName = 'MPLS    Utilization % (Average)'
      AND p.DateTime >= DATEADD(MM, (@interval), GetUTCDate())

I want to use like
p.DateTime >= DATEADD(MM, IN (@interval), GetUTCDate())

but it is not allowing it.


text:
Q: WebBrowser control won't display an https site that IE8 on the same PC will In IE8, I get the follow warning, but if I choose to continue the site displays properly.
  There is a problem with this website's security certificate.

 The security certificate presented by this website was issued for a different website's address.

Security certificate problems may indicate an attempt to fool you or intercept any data you send to the server.
  We recommend that you close this webpage and do not continue to this website.
  Click here to close this webpage.
  Continue to this website (not recommended).
     More information

In the WebBrowser control, I get this at first:
  Navigation to the webpage was canceled

   What you can try:
     Refresh the page.

When I hit the refresh teh page, this time, I get the same wanting as I originally get in IE8, but when I click "Continue to this website (not recommended)", the page refresh again, displaying the same warning.
What can I do to get the site to display in the WebBrowser control as it does in IE8. I would've thought that the control would be using the same core logic and therefore expected the same result.
Specifically, the site that I am trying to access is a company Outlook Web Access site. Another issue that I have wit the web browser control when accessing this  site is that, when I click on an email, normally in IE the email opens in a new window. Using the web browser control, I am prompted for a password. Entering one makes the pop up go away but no email is displayed.
Are there any settings on the control that can make the web site behave like it does in IE8 or any other browsder?

A: Try display the certificate dialog so your user can choose to install the certificate to a trusted certificate store.
To detect if the current web site is showing a secure web site, handle the DWebBrowserEvents2::SetSecureLockIcon event.


text:
Q: How to make android app using WebView without lags? I'm just trying to build my first app using WebView for website wikidiy.org.
I've tried a lot approaches I found here, but the app is still very laggy. Is there any way how to make this app without laggs? When I open website in Chrome browser, it is smooth and correctly running, but in WebView app it is almost impossible tu use.
Edit: Is it make sense to do it with webview? Or I should learn how to do it with WP RestAPI as a native app?
Here is my code:
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.wikidiy.wikidiy">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.webkit.PermissionRequest" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:hardwareAccelerated="false"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Java
package org.wikidiy.wikidiy;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    String ShowOrHideWebViewInitialUse = "show";
    private WebView webview ;
    private ProgressBar spinner;
    SwipeRefreshLayout mySwipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mySwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);
        webview =(WebView)findViewById(R.id.webView);
        spinner = (ProgressBar)findViewById(R.id.progressBar1);
        webview.setWebViewClient(new CustomWebViewClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
        webview.loadUrl("https://wikidiy.org");

        mySwipeRefreshLayout.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        webview.reload();
                    }
                }
        );
    }

    // This allows for a splash screen
    // (and hide elements once the page loads)
    private class CustomWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView webview, String url, Bitmap favicon) {

            // only make it invisible the FIRST time the app is run
            if (ShowOrHideWebViewInitialUse.equals("show")) {
                webview.setVisibility(webview.INVISIBLE);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            ShowOrHideWebViewInitialUse = "hide";
            spinner.setVisibility(View.GONE);

            view.setVisibility(webview.VISIBLE);
            super.onPageFinished(view, url);

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (webview.canGoBack()) {
                        webview.goBack();
                    } else {
                        finish();
                    }
                    return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }
}

activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:layout_editor_absoluteY="25dp">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/app_name">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:accessibilityHeading="false"
        tools:layout_editor_absoluteX="45dp"
        tools:layout_editor_absoluteY="56dp">

    </WebView>
    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyle"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="144dp"
        android:visibility="visible"
        android:layout_gravity="center"
        tools:layout_editor_absoluteX="168dp"
        tools:layout_editor_absoluteY="347dp"
        tools:visibility="visible" />

    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

Styles
<resources>
    <style name="splashScreenTheme" parent="@android:style/Theme.DeviceDefault.Light.NoActionBar">
        <item name="android:windowBackground">@drawable/splash_screen</item>
    </style>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="android:windowBackground">@drawable/splash_screen</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

A: I use below code to create any WebView apk. It works fine without any lag so give it a try.
This will be the base code and then you can then add your swipeToRefresh and Loader in this code.
MainActivity.java :-
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private String url = "http://google.com/";

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

        webView = findViewById(R.id.webView);
        webView.setBackgroundColor(Color.TRANSPARENT);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl(url);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

activity_main.xml :-
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:foregroundGravity="center" />

</android.support.constraint.ConstraintLayout>


text:
Q: Single updates using tf.GradientTape with multiple outputs I defined the following model, which has two distinct outputs:
input_layer = keras.layers.Input(shape = (1, 20), name = "input_features")

# Shared layers
hidden_1 = keras.layers.Dense(32,
                            activation = "relu",
                            name = "LSTM_shared_l"
                            )(input_layer)

# Additional layers
hidden_2 = keras.layers.Dense(32,
                              activation = "selu",
                              name = "Forecasting_extra_layer_1"
                              )(input_layer)

hidden_3 = keras.layers.Dense(32,
                              activation = "selu",
                              name = "Forecasting_extra_layer_2"
                              )(hidden_2)

# Output layers
f_output = keras.layers.Dense(1,
                              name = "F_output")(hidden_1)

rl_output = keras.layers.Dense(32,
                               name = "RL_output")(hidden_3)

model = keras.Model(inputs = [input_layer], outputs = [f_output, rl_output])

model.summary()

and I would like to train it with GradientTape, performing single iterations; with only one output, I would use the following code:
with tf.GradientTape() as tape:

        predictions = model(inputs)
        pred_values = tf.reduce_sum(predictions, axis=1, keepdims=True)
        loss = tf.reduce_mean(loss_fn(target_pred, pred_values))

    grads = tape.gradient(loss, model.trainable_variables)
    optimizer.apply_gradients(zip(grads, model.trainable_variables))

How can I extend it to the multiple outputs scenario?

A: There are multiple strategies, the simplest one is to calculate the loss from both outputs and sum the results together:
predictions_1, predictions_2 = model(inputs)

predictions_1 = ...
predictions_2 = ... # any desired post-processing

loss = tf.reduce_mean(loss_fn(target_1, predictions_1)) + tf.reduce_mean(loss_fn(target_2, predictions_2))

and then you can safely descend:
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))


text:
Q: Compiler optimizations disabled. Functions from  won't work as designed I am working on Firebird 5 module. That has Atmega2560, I am trying to compile this code and getting this warning.
(base) pawansrinivas@Pawans-MacBook-Air Experiment-3 % mkdir -p build
(base) pawansrinivas@Pawans-MacBook-Air Experiment-3 % avr-gcc -g -Wall -O0 -mmcu=atmega328p -c Experiment-3.c -o build/Experiment-3.o
In file included from Experiment-3.c:25:
/opt/homebrew/Cellar/avr-gcc@9/9.3.0_3/avr/include/util/delay.h:112:3: warning: #warning "Compiler optimizations disabled; functions from <util/delay.h> won't work as designed" [-Wcpp]
  112 | # warning "Compiler optimizations disabled; functions from <util/delay.h> won't work as designed"
      |   ^~~~~~~
(base) pawansrinivas@Pawans-MacBook-Air Experiment-3 %

A: You are probably using AVRGCC with avr-libc?
See <util/delay.h>

In order for these functions to work as intended, compiler optimizations must be enabled, and the delay time must be an expression that is a known constant at compile-time. If these requirements are not met, the resulting delay will be much longer (and basically unpredictable), and applications that otherwise do not use floating-point calculations will experience severe code bloat by the floating-point library routines linked into the application.

A: ================================================================
At Embedded systems we use cross target complier if you use AVR the complier
"AVR-GCC Toolchain"
so if you want to use delay function you will include <avr/delay.h>
because you use compiler for AVR processor family .
I wish that my unswer help you.
================================================================


text:
Q: Running a script on a list of files I have a script which obtains a .vcf file, parses that and writes that in a .txt
grep -v "#" file.vcf | sed 's/chrM/MT/' | sed 's/chrX/X/' | sed 's/chrY/Y/' | awk '{print $1,$2,$2,$4"/"$5,"+"}' | sed 's/chr//g' > vcf_output.txt

I have 27 .vcf files on which I want to run this script at the same time and write the output of each .vcf in a .txt file by the name of that .vcf
I found this in google but nothing happens after running that
for f in *.vcf; do
    script "$f" > "${f%.*}.txt"
done

I adopted that like below
for f in *.vcf; do

grep -v "#" | sed 's/chrM/MT/' | sed 's/chrX/X/' | sed 's/chrY/Y/' | awk '{print $1,$2,$2,$4"/"$5,"+"}' | sed 's/chr//g' "$f" > "${f%.*}.txt"
    done

I also tried that
(base) loan-mac-13:Pre_Treatment fi1d18$ find -type f -name "*.vcf" | xargs grep -v "#" | sed 's/chrM/MT/' | sed 's/chrX/X/' | sed 's/chrY/Y/' | awk '{print $1,$2,$2,$4"/"$5,"+"}' | sed 's/chr//g' "$f" > "${f%.*}.txt"
find: illegal option -- t
usage: find [-H | -L | -P] [-EXdsx] [-f path] path ... [expression]
       find [-H | -L | -P] [-EXdsx] -f path [path ...] [expression]
sed: : No such file or directory
(base) loan-mac-13:Pre_Treatment fi1d18$

How I can push this to work for me?

A: You can use find and xargs for that.
Find will list all the files.
find -type f -name "*.vcf"

With xargs we can operate on every file that was found.
find -type f -name "*.vcf" | xargs grep -v "#" | sed 's/chrM/MT/' | sed 's/chrX/X/' | sed 's/chrY/Y/' | awk '{print $1,$2,$2,$4"/"$5,"+"}' | sed 's/chr//g' "$f" > "${f%.*}.txt"

should do the job?
greetings

A: Without altering any of your flow, the below should work. Notice that you weren't inputting anything to the first command grep in the pipeline. So nothing was moving.
for f in *.vcf; do

< "$f"  grep -v "#" | sed 's/chrM/MT/' | sed 's/chrX/X/' | sed 's/chrY/Y/' | awk '{print $1,$2,$2,$4"/"$5,"+"}' | sed 's/chr//g'  > "${f%.*}.txt"
    done

A: You converted script "$f" in your google output to grep -v "#" (i.e. missing the "$f") in your shell loop script and then you're using "$f" instead of {} and using it in the wrong place in your xargs script.
You never need a bunch of seds and greps in a pipleine when you're using awk anyway though. You didn't provide any sample input/output so the following awk script is just a straight translation of your existing pipeline and there's probably a better way to write it, but this one awk script is all you need, no shell loops or anything else:
awk '
    FNR == 1 {
        close(out)
        out = FILENAME
        sub(/\.vcf$/,".txt",out)
    }
    !/#/ {
        sub(/chrM/,"MT")
        sub(/chrX/,"X")
        sub(/chrY/,"Y")
        $0 = $1 OFS $2 OFS $2 OFS $4 "/" $5 OFS "+"
        gsub(/chr/,"")
        print > out
    }
' *.vcf

If you want to cram it onto fewer lines like you did with your grep+seds+awk pipeline you can just use semicolons everywhere there's a newline you want to get rid of except after each {, e.g.:
awk 'FNR==1{close(out); out=FILENAME; sub(/\.vcf$/,".txt",out)} !/#/{sub(/chrM/,"MT"); sub(/chrX/,"X"); sub(/chrY/,"Y"); $0=$1 OFS $2 OFS $2 OFS $4 "/" $5 OFS "+"; gsub(/chr/,""); print > out}' *.vcf


text:
Q: Can I create my own formula for calculated field in Sharepoint 2010 using C# I want to create a programmatically calculated field for Sharepoint 2010 using Visual Studio 2010 in C# language.
Is there a way to set a formula that will call to my own function and return a result back to the field?
My scenario:

*

*let's say I want to create a field that always returned the sum between two other fields,

*but I don't want to use something like "=sum([filed1],[field2])".

*I want to call to function "calc2Fields()" and return a result.

Is it possible?

A: No, it is not possible. By changing the formula you are not adding any internal logic, so the field will not know what to do with your function. You can however build a custom field and incorporate there any logic you need. Of course it is not going to be identical to the built-in calculate field, but then you can add your own functions.

A: You will have to create your own custom field with this logic in.
Customizing the User Experience of SharePoint: Custom fields deep dive


text:
Q: ConfigurationException filename is null From time-to-time, my users will get a ConfigurationException from a corrupt user.config file. I would like to automatically rest or delete the user.config so that the user can start over. I was hoping to obtain the filename (which has some hash in it), but the filename is null in the exception. How can I retrieve the correct configuration file so I can delete it?
Some hints found here - http://bytes.com/topic/c-sharp/answers/601193-how-do-i-restore-corrupted-user-config-file - but doesn't work because the filename is null.

A: To resolve this, you must add a reference to System.Configuration and catch ConfigurationErrorsException instead. Look in the inner exception for the filename.


text:
Q: Does AWS Neptune need internet access? I was starting a neptune database from this base stack
https://s3.amazonaws.com/aws-neptune-customer-samples/v2/cloudformation-templates/neptune-base-stack.json
However now i am wondering why a NAT Gateway and also an Internet Gateway are started in this stack? are they required for updates within Neptune? This seems like a huge security risk.
On top of that these gateways are not cheap.
I would be happy for an explanation on this

A: The answer is no, it's not required, AWS just sneaked some unecessary costly ressources into the template..
Anyways if you want to use the updated template without NAT and IG GWs use this one that i just created https://neptune-stack-custom.s3.eu-central-1.amazonaws.com/base.json


text:
Q: I have a conflict between my node version and firebase-functions I installed the latest version of firebase-functions, which is 4.2.1 and I'm running node version 19.6.0; however, when I set my node version in the package.json file, I'm getting an error when trying to run the firebase emulator that it wants version 10, 12, 14, or 16.  The error says: "functions: Failed to load function definition from source: FirebaseError: package.json in functions directory has an engines field which is unsupported. Valid choices are: {"node": 10|12|14|16}"
This is my package.json file:
{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "19"
  },
  "main": "index.js",
  "dependencies": {
    "firebase-admin": "^11.5.0",
    "firebase-functions": "^4.2.1"
  },
  "devDependencies": {
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}

I've tried changing my node version in the package.json file to 16; however, I then get an error that says it was expecting node version 16 but got node version 19.6.0.  So I'm stuck at this point.


text:
Q: PHPUnit color bars not showing on Windows 10 My PHPUnit tests output does not show colored bars (green /red) on Windows 10:

I already tried:
1) Installing ansicon;
2) Changing to older versions of PHPUnit (like 4.7.1 as in the screenshot above)
And I am using  colors="true" as you can see in phpunit.xml:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./tests/</directory>
        </testsuite>
    </testsuites>
</phpunit>

Any other ideas?
Thanks!


text:
Q: Match between lines while skipping pattern with Regex I've been trying to match between lines while skipping a pattern.
I'm using the re.DOTALL regex flag.
What i need to extract is
CHINTHAPUDI

CHINTHAPUDI

from between Electors Name and Father's Name.
What i have currently mustered up is this regex:
(?:^Elector\'s Name:.*?
)(.*?)^(?:Husband|Father)

But it matches the other Elector's Name lines beneath the first match.
Link to my regex101
Here's the document from which i want to match:
Elector's Name: ANANTH CHINTAPUDI

Elector's Name: THIRUPATHI

Elector's Name: SRINIVASH

CHINTHAPUDI

CHINTHAPUDI

Father's Name: POSHANNA

Father's Name: SHANKAR

Father's Name: SHANKAR

CHINTAPUDDI

CHINTHAPUDI

CHINTHAPUDI

How could i go about matching from the last Elector's Name till Father's Name?

A: Here's an option which works for your provided input:
(?:Elector\'s Name:.*?
\r?\n)+(.*?)(?:Husband|Father)
There is one potential issue that you should consider if you use this: If an Elector's Name appears earlier in the document, the first set will be used. See demo.
Additionally, as your Regex attempt required that Elector's Name and Husband or Father be at the beginning of the line, here's a version which maintains that requirement. If possible, I would avoid this as it results in a much slower (30x) check.
(?:\r?\nElector\'s Name:.*?
)+\r?\n(.*?)\r?\n(?=Husband|Father)