text:
Q: "'str' object has no attribute 'get'" when using Google Cloud Storage with ScrapingHub I'm trying to get Google Cloud Storage working with a Scrapy Cloud + Crawlera project so that I can save text files I'm trying to download.  I'm encountering an error when I run my script that seems to have to do with my Google permissions not working properly.
Error:
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/scrapy/pipelines/media.py", line 68, in from_crawler
    pipe = cls.from_settings(crawler.settings)
  File "/usr/local/lib/python3.7/site-packages/scrapy/pipelines/files.py", line 325, in from_settings
    return cls(store_uri, settings=settings)
  File "/usr/local/lib/python3.7/site-packages/scrapy/pipelines/files.py", line 289, in __init__
    self.store = self._get_store(store_uri)
  File "/usr/local/lib/python3.7/site-packages/scrapy/pipelines/files.py", line 333, in _get_store
    return store_cls(uri)
  File "/usr/local/lib/python3.7/site-packages/scrapy/pipelines/files.py", line 217, in __init__
    client = storage.Client(project=self.GCS_PROJECT_ID)
  File "/app/python/lib/python3.7/site-packages/google/cloud/storage/client.py", line 82, in __init__
    project=project, credentials=credentials, _http=_http
  File "/app/python/lib/python3.7/site-packages/google/cloud/client.py", line 228, in __init__
    Client.__init__(self, credentials=credentials, _http=_http)
  File "/app/python/lib/python3.7/site-packages/google/cloud/client.py", line 133, in __init__
    credentials, _ = google.auth.default()
  File "/app/python/lib/python3.7/site-packages/google/auth/_default.py", line 305, in default
    credentials, project_id = checker()
  File "/app/python/lib/python3.7/site-packages/google/auth/_default.py", line 165, in _get_explicit_environ_credentials
    os.environ[environment_vars.CREDENTIALS])
  File "/app/python/lib/python3.7/site-packages/google/auth/_default.py", line 102, in _load_credentials_from_file
    credential_type = info.get('type')
AttributeError: 'str' object has no attribute 'get'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/twisted/internet/defer.py", line 1418, in _inlineCallbacks
    result = g.send(result)
  File "/usr/local/lib/python3.7/site-packages/scrapy/crawler.py", line 80, in crawl
    self.engine = self._create_engine()
  File "/usr/local/lib/python3.7/site-packages/scrapy/crawler.py", line 105, in _create_engine
    return ExecutionEngine(self, lambda _: self.stop())
  File "/usr/local/lib/python3.7/site-packages/scrapy/core/engine.py", line 70, in __init__
    self.scraper = Scraper(crawler)
  File "/usr/local/lib/python3.7/site-packages/scrapy/core/scraper.py", line 71, in __init__
    self.itemproc = itemproc_cls.from_crawler(crawler)
  File "/usr/local/lib/python3.7/site-packages/scrapy/middleware.py", line 53, in from_crawler
    return cls.from_settings(crawler.settings, crawler)
  File "/usr/local/lib/python3.7/site-packages/scrapy/middleware.py", line 35, in from_settings
    mw = create_instance(mwcls, settings, crawler)
  File "/usr/local/lib/python3.7/site-packages/scrapy/utils/misc.py", line 140, in create_instance
    return objcls.from_crawler(crawler, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/scrapy/pipelines/media.py", line 70, in from_crawler
    pipe = cls()
TypeError: __init__() missing 1 required positional argument: 'store_uri'

__init__.py where I create the credentials file:
# Code from https://medium.com/@rutger_93697/i-thought-this-solution-was-somewhat-complex-3e8bc91f83f8

import os
import json
import pkgutil
import logging

path = "{}/google-cloud-storage-credentials.json".format(os.getcwd())

credentials_content = '<escaped JSON data>'

with open(path, "w") as text_file:
    text_file.write(json.dumps(credentials_content))

logging.warning("Path to credentials: %s" % path)
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = path

settings.py:
BOT_NAME = 'get_case_urls'

SPIDER_MODULES = ['get_case_urls.spiders']
NEWSPIDER_MODULE = 'get_case_urls.spiders'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Crawlera
DOWNLOADER_MIDDLEWARES = {'scrapy_crawlera.CrawleraMiddleware': 300}
CRAWLERA_ENABLED = True
CRAWLERA_APIKEY = '<crawlera-api-key>'
CONCURRENT_REQUESTS = 32
CONCURRENT_REQUESTS_PER_DOMAIN = 32
AUTOTHROTTLE_ENABLED = False
DOWNLOAD_TIMEOUT = 600

ITEM_PIPELINES = {
    'scrapy.pipelines.files.FilesPipeline': 500
}
FILES_STORE = 'gs://<name-of-my-gcs-project>'
IMAGES_STORE = 'gs://<name-of-my-gcs-project>'
GCS_PROJECT_ID = "<id-of-my-gcs-project>"

A: After looking at the code for _load_credentials_from_file it seems to me that I had not saved the JSON to a text file correctly: in __init__.py, rather than having text_file.write(json.dumps(credentials_content)), I should have had text_file.write(credentials_content) or text_file.write(json.dumps(json.loads(credentials_content))).


text:
Q: How can I add access to use here -1 (instead 0)? Vote negative url(r'^rate/(?P<id_obj>\d+)/(?P<rate>\d{-1,1})/', 'app.views.add_rate'),

How can I add access to use here -1:
(?P<rate>\d{-1,1})
This is negative Vote(-1) or positive (1)

A: If value is either 1 or -1 then you simply need (?P<rate>-1|1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python slice without dimension Why slicing one row or column produces "dimensionless array"? For example:
import numpy as np
arr = np.zeros((10,10))
print arr.shape
# (10, 10)

But when I want only one column or row, I get
print arr[:,0].shape
# (10,)
print arr[0,:].shape
# (10,)

instead of
print arr[:,0].shape
# (10, 1)
print arr[0,:].shape
# (1, 10)

A: For you example you getting np.arrays from 0 column and from 0 row which are numpy.array with 1 dimension. You could do a little trick with slicing like that:
In [103]: arr[:1,:].shape
Out[103]: (1, 10)

In [104]: arr[:,:1].shape
Out[104]: (10, 1)

EDIT
From docs:

An integer, i, returns the same values as i:i+1 except the dimensionality of the returned object is reduced by 1. In particular, a selection tuple with the p-th element an integer (and all other entries :) returns the corresponding sub-array with dimension N - 1. If N = 1 then the returned object is an array scalar. These objects are explained in Scalars.


text:
Q: multiple filters vs OR , ndb query What is the difference between these queries:

*

*With consequent filters:
qry1 = Account.query() # Retrieve all Account entitites
qry2 = qry1.filter(Account.userid >= 40) # Filter on userid >= 40
qry3 = qry2.filter(Account.userid < 50) # Filter on userid < 50 as well

*Using ndb.OR:
qry = Article.query(ndb.OR(Account.userid >= 40,
                       Account.userid < 50))

*Using ndb.AND:
qry = Article.query(ndb.AND(Account.userid >= 40,
                        Account.userid < 50))

A: The first query does an AND. Thus, only the entities that match both inequalities will be returned by the query. The second query does an OR. Thus, entities that match either of the filters will be returned. For more information about ndb queries, take a look at NDB Queries.

A: Third and the First query are exactly identical. But the second query is absurd, it may end up returning all Entities in the Kind.


text:
Q: Eclipse Luna Doesn't Display JFrames I'm using a Mac and for some reason Eclipse Luna won't run any of my programs that use a JFrame. The problem persists on a fresh installation of Luna but using Juno or Kepler, the frame displays just fine. I'm also using Java 8. My classmates can run the same code fine on Kepler as well (Windows and Mac). It also runs fine if I run it through Terminal. I have no clue why Luna won't display JFrames; does anyone know what the issue could possibly be?
EDIT: Any program that runs through the console runs just fine.


text:
Q: Join two tables on one column and if not possible on second column Preface
I have two tables
CREATE TABLE `permissions` (
  `id` int(11) NOT NULL,
  `user` int(11) DEFAULT NULL,
  `name` varchar(100) COLLATE utf8mb4_unicode_ci NULL,
  `orders_and_returns` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
  `transactions` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
  ...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `status` int(11) NOT NULL,
  `access_level` int(11) NOT NULL,
  `name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  ...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Permissions table have two kinds of rows, one is a profile
INSERT INTO permissions (`id`, `user`, `name`, `orders_and_returns`) VALUES (1, NULL, 'Admin', 1);

This means that there is a profile called Admin, which grants permissions to view orders. Any user with access_level = 1 is an admin and can view orders.
The table also have a second kind of row
INSERT INTO permissions (`id`, `user`, `name`, `orders_and_returns`) VALUES (2, 2, NULL, 0);

This is a user specific permission. The user (id = 2) may have access_level = 1 but there is an override for this user which revokes the access to orders. This is the row that must be used to determine their permission.
Problem
I need to load the permissions for all the users in my table. So when I'm joining permissions table on user, I basically want to see if I can join on users.id = permissions.user (meaning user specific override is present) and if not I want to join with users.access_level = permissions.id. I'm not sure how to do this.
It may be possible with two queries like below but excluding all the results from second query that are in first query
1. SELECT email FROM users u JOIN permissions p ON u.id = p.user
2. SELECT email FROM users u JOIN permissions p ON u.access_level = p.id

A: Updated 2022-03-20

hank will also have access_level = 1 meaning the profile is admin. But there is an override for it. The access_level value is not changed in the users table. With that change, your query returns 2 results for hank ; the profile and the override.

If records have both a profiled and access_level, you'll need to first rank the results (by overrides first) and then return the 1st result only:
WITH cte AS(
  SELECT
     email
     , IF(u.id = p.user
         , 'user specific override'
         , 'profile'
     ) AS PermissionType
     , ROW_NUMBER() OVER(
        PARTITION BY u.id
        ORDER BY IF(u.id = p.user, 0, 1)
     ) AS RowNum
  FROM users u
        INNER JOIN permissions p ON u.id = p.user OR u.access_level = p.id
)
SELECT *
FROM.  cte
WHERE RowNum = 1

Results:

email           | PermissionType         | RowNum
:-------------- | :--------------------- | -----:
john@examle.com | profile                |      1
hank@examle.com | user specific override |      1

db<>fiddle here

Original Answer
Have you tried a simple OR
SELECT email, IF(u.id = p.user, 'user specific override', 'profile')
FROM  users u
        INNER JOIN permissions p ON u.id = p.user OR u.access_level = p.id

Results:

email           | IF(u.id = p.user, 'user specific override', 'profile')
:-------------- | :-----------------------------------------------------
john@examle.com | profile
hank@examle.com | user specific override

db<>fiddle here


text:
Q: Replace keys in template string with object properties I have an object like this.
var obj = {Id:1,Rate:5,Price:200,Name:"History"}

And a template like this.
var templateString = '<option id="{Id}">{Name}</option>'

I want to replace the template values with object values. How can i do this. I am no expert of javascript regular expressions.
The desired output
var optionString = '<option id="1">History</option>'

Fiddle Sample

A: You can use replace with a callback :
var optionString = templateString.replace(/{(\w+)}/g, function(_,k){
      return obj[k];
});

Demonstration

A: Without using regex, this can be done by finding all the properties of the object using Object.keys and then replace each of them by it's value.
Try like this:
Object.keys(obj).forEach(key => {
  templateString = templateString.replace(`**${key}**`, `"${obj[key]}"`);
});

A: Just this will work for you if it has just one occurrence
var optionString = templateString.replace('{Id}',obj.Id).replace('{Name}',obj.Name)


text:
Q: Как написать функцию для перестановки столбцов матрицы, чтобы преобразовать ее в треугольную? Нужно написать функцию, которая на вход будет принимать двухмерный массив, а возвращать этот же массив, только с перестановленными столбцами, чтобы в результате получилась треугольная матрица.
Пример входных данных:
matrix = np.array([
    [3, 2, -5],
    [3, 0, 0],
    [0, 1, 0]])

На выходе нужно получить:
[[ -5.  3. 2.]
[ 0.  3.  0.]
[ 0.  0.  1.]]

A: попробуйте так:
res = matrix[:, ((matrix==0) * np.power(10, range(len(matrix)))
                                 .reshape(-1, 1))
                .sum(axis=0)
                .argsort()
                [::-1]
]

результат:
In [219]: res
Out[219]:
array([[-5,  3,  2],
       [ 0,  3,  0],
       [ 0,  0,  1]])

PS если у вас есть значения стремящиеся к нулю, тогда лучше воспользоваться np.isclose(matrix, 0, atol=1e-07) вместо строгого сравнения matrix==0.


text:
Q: Having many SVG DomMarkers in HERE maps causes lag I'm using HERE maps 3.0 (also tried 3.1 and have the same issue) with the default layers in an angular project. The map has DomMarkers using a complex SVG icon with many paths inside a div.
I noticed that adding many markers (over 200) causes a lag when zooming or moving around the map.
I'm using SVG instead of static image files to be able to change the colour and modify the shape of the icon before adding it to the map.
Using a dom icon with multiple divs shaped with CSS instead of the SVG, results in the same lag.
If I use a more simple SVG or a simple div, the lag is reduced significantly.
What's causing the lag? Is it caused by the complexity of the SVG, or the large and many paths it has?
Is there a way to have complex SVG markers and eliminate the lag?
My SVG:
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" id="Layer_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="-656 895.2 221.2 259.8" style="enable-background:new -656 895.2 221.2 259.8;" xml:space="preserve">
<g>
    <path fill="white" d="M-489.9,937.4c-15.8-16.3-36.6-25.3-58.5-25.3c-46.8,0-84.8,41.1-84.8,91.6c0,13.3,2.5,25.9,7.4,37.2
        c12.9,30.9,48.3,84.6,68,109.5c2.3,2.9,5.7,4.6,9.4,4.6c3.5,0,6.7-1.5,9.1-4.2l0.1-0.2l0.1-0.2c19.5-24.5,54.8-77.9,68-109.4
        c4.9-11.9,7.3-24.4,7.3-37.1C-463.6,978.7-472.9,954.9-489.9,937.4z M-478.3,1037.8c-12.5,29.9-47,82.5-66.8,107.4
        c-0.9,1-2,1.6-3.3,1.6c-1.3,0-2.5-0.6-3.3-1.6c-19.7-24.9-54.3-77.6-66.8-107.6c-4.5-10.5-6.7-21.9-6.7-34
        c0-46,34.5-83.5,76.9-83.5s76.9,37.4,76.7,83.7C-471.6,1015.9-473.9,1027.4-478.3,1037.8z"/>
    <path fill="#775DD0" d="M-548.3,920.4c-42.4,0-76.9,37.4-76.9,83.5c0,12,2.2,23.4,6.7,34c12.5,30,47.1,82.6,66.8,107.6
        c0.8,1,2,1.6,3.3,1.6c1.3,0,2.4-0.6,3.3-1.6c19.9-24.8,54.4-77.5,66.9-107.5c4.4-10.6,6.7-22.1,6.7-34
        C-471.4,957.7-505.9,920.4-548.3,920.4z"/>
</g>
<g>
    <path fill="white" d="M-454.5,1067.8h-47.8c-10.9,0-19.7,8.9-19.7,19.7v47.8c0,10.9,8.9,19.7,19.7,19.7h47.8
        c10.9,0,19.7-8.9,19.7-19.7v-47.8C-434.8,1076.7-443.6,1067.8-454.5,1067.8z M-444.8,1135.4c0,5.4-4.3,9.7-9.7,9.7h-47.8
        c-5.4,0-9.7-4.4-9.7-9.7v-47.8c0-5.4,4.3-9.7,9.7-9.7h47.8c5.3,0,9.7,4.4,9.7,9.7V1135.4z"/>
    <path fill="#775DD0" d="M-454.5,1077.8h-47.8c-5.4,0-9.7,4.4-9.7,9.7v47.8c0,5.4,4.3,9.7,9.7,9.7h47.8c5.4,0,9.7-4.4,9.7-9.7v-47.8
        C-444.8,1082.2-449.2,1077.8-454.5,1077.8z"/>
    <path fill="white" d="M-461.6,1094.7l-22,24.8l-11-12.4c-2-2.2-5.3-2.2-7.4,0c-2,2.2-2,6,0,8.3l14.7,16.5
        c2,2.2,5.3,2.2,7.4,0l25.7-29c2.1-2.3,2.1-6.1,0-8.3C-456.2,1092.4-459.5,1092.4-461.6,1094.7z"/>
</g>
<g>
    <path fill="white" d="M-478.1,941.6c-6.7,0-19.9,3.7-20,10.3c4.3,6.5,11.7,10.7,20,10.7s15.7-4.3,20-10.7
        C-458.2,945.2-471.5,941.6-478.1,941.6z M-478.1,952.6c-1.3,0-2.6-0.2-3.9-0.6c1.4-0.3,2.7-0.5,3.9-0.5s2.5,0.2,3.9,0.5
        C-475.5,952.4-476.8,952.6-478.1,952.6z"/>
    <path fill="white" d="M-478.1,895.2c-23.9,0-43.3,19.4-43.3,43.4s19.4,43.3,43.3,43.3s43.3-19.4,43.3-43.3S-454.2,895.2-478.1,895.2
        z M-478.1,971.9c-18.4,0-33.3-14.9-33.3-33.4c0-18.4,14.9-33.3,33.3-33.3s33.3,14.9,33.3,33.3C-444.8,957-459.7,971.9-478.1,971.9z
        "/>
    <path fill="white" d="M-478.1,935.2c5.5,0,10-4.5,10-10c0-5.5-4.5-10-10-10s-10,4.5-10,10C-488.2,930.7-483.7,935.2-478.1,935.2z"/>
    <path d="M-478.1,905.2c-18.4,0-33.3,14.9-33.3,33.3c0,18.4,14.9,33.4,33.3,33.4s33.3-14.9,33.3-33.4
        C-444.8,920.1-459.7,905.2-478.1,905.2z M-478.1,915.2c5.5,0,10,4.5,10,10c0,5.5-4.5,10-10,10s-10-4.5-10-10
        C-488.2,919.7-483.7,915.2-478.1,915.2z M-478.1,962.6c-8.4,0-15.7-4.3-20-10.7c0.1-6.6,13.4-10.3,20-10.3s19.9,3.7,20,10.3
        C-462.5,958.3-469.8,962.6-478.1,962.6z"/>
</g>
<g>
    <path fill="white" d="M-572.4,927.7c0.3-1,0.5-2.1,0.5-3.2c0-2.7-1.1-5.2-2.9-7.1l-4.8-4.7c-1.2-1.2-2.7-2-4.2-2.5
        c-0.5-1.5-1.3-3-2.5-4.2l-4.7-4.8c-1.9-1.9-4.4-2.9-7.1-2.9c0,0,0,0,0,0c-1.1,0-2.2,0.2-3.2,0.5c-1.8-2.2-4.6-3.6-7.7-3.6h-6.7
        c-3.1,0-5.9,1.4-7.7,3.6c-1-0.3-2.1-0.5-3.2-0.5c0,0,0,0,0,0c-2.7,0-5.2,1.1-7.1,2.9l-4.7,4.8c-1.2,1.2-2,2.7-2.5,4.2
        c-1.5,0.5-3,1.3-4.2,2.5l-4.8,4.7c-1.9,1.9-2.9,4.4-2.9,7.1c0,1.1,0.2,2.2,0.5,3.2c-2.2,1.8-3.6,4.6-3.6,7.7v6.7
        c0,3.1,1.4,5.9,3.6,7.7c-0.3,1-0.5,2.1-0.5,3.2c0,2.7,1.1,5.2,2.9,7.1l4.8,4.7c1.2,1.2,2.7,2,4.2,2.5c0.5,1.5,1.3,3,2.5,4.2
        l4.7,4.8c1.9,1.9,4.4,2.9,7.1,2.9c0,0,0,0,0,0c1.1,0,2.2-0.2,3.2-0.5c1.8,2.2,4.6,3.6,7.7,3.6h6.7c3.1,0,5.9-1.4,7.7-3.6
        c1,0.3,2.1,0.5,3.2,0.5c0,0,0,0,0,0c2.7,0,5.2-1.1,7.1-2.9l4.7-4.8c1.2-1.2,2-2.7,2.5-4.2c1.5-0.5,3-1.3,4.2-2.5l4.8-4.7
        c1.9-1.9,2.9-4.4,2.9-7.1c0-1.1-0.2-2.2-0.5-3.2c2.2-1.8,3.6-4.6,3.6-7.7v-6.7C-568.8,932.3-570.2,929.6-572.4,927.7z
         M-578.8,942.2h-14l10.9,10.9l-4.8,4.7l-15.6-15.6h-6.7v6.7l15.6,15.6l-4.7,4.8l-10.9-10.9v14h-6.7v-14l-10.9,10.9l-4.7-4.8
        l15.6-15.6v-6.7h-6.7l-15.6,15.6l-4.8-4.7l10.9-10.9h-14v-6.7h14l-10.9-10.9l4.8-4.7l15.6,15.6h6.7v-6.7l-15.6-15.6l4.7-4.8
        l10.9,10.9v-14h6.7v14l10.9-10.9l4.7,4.8l-15.6,15.6v6.7h6.7l15.6-15.6l4.8,4.7l-10.9,10.9h14V942.2z"/>
    <polygon points="-581.9,924.5 -586.7,919.8 -602.3,935.4 -609,935.4 -609,928.7 -593.4,913.1 -598.1,908.3 -609,919.2 -609,905.2
        -615.8,905.2 -615.8,919.2 -626.7,908.3 -631.4,913.1 -615.8,928.7 -615.8,935.4 -622.5,935.4 -638.1,919.8 -642.9,924.5
        -632,935.4 -646,935.4 -646,942.2 -632,942.2 -642.9,953.1 -638.1,957.8 -622.5,942.2 -615.8,942.2 -615.8,948.9 -631.4,964.5
        -626.7,969.3 -615.8,958.4 -615.8,972.4 -609,972.4 -609,958.4 -598.1,969.3 -593.4,964.5 -609,948.9 -609,942.2 -602.3,942.2
        -586.7,957.8 -581.9,953.1 -592.8,942.2 -578.8,942.2 -578.8,935.4 -592.8,935.4   "/>
</g>
<g>
    <path fill="white" d="M-537.3,987.5c-1.9,0-3.4,1.5-3.4,3.4c0,1.9,1.5,3.4,3.4,3.4c1.9,0,3.4-1.5,3.4-3.4
        C-533.9,989-535.4,987.5-537.3,987.5z"/>
    <path fill="white" d="M-557.5,987.5c-1.9,0-3.4,1.5-3.4,3.4c0,1.9,1.5,3.4,3.4,3.4s3.4-1.5,3.4-3.4
        C-554.2,989-555.7,987.5-557.5,987.5z"/>
    <path fill="white" d="M-513.8,997.6c0-6.7-2.1-13.3-5.8-18.8l0.3-0.3c3.9-3.9,3.9-10.2,0-14.1l-2.8-2.8c-1.9-1.9-4.4-2.9-7.1-2.9
        s-5.2,1.1-7.1,2.9l-3.3,3.3c-2.6-0.6-5.2-1-7.9-1c-2.7,0-5.3,0.3-7.9,1l-3.3-3.3c-2-2-4.5-2.9-7.1-2.9s-5.1,1-7.1,2.9l-2.8,2.8
        c-3.9,3.9-3.9,10.2,0,14.1l0.3,0.3c-3.7,5.5-5.8,12-5.8,18.8v3.4c0,0.6,0,1.1,0.1,1.7c-0.1,0.5-0.1,1.1-0.1,1.7v13.5
        c0,18.5,15.1,33.6,33.6,33.6s33.6-15.1,33.6-33.6v-13.5c0-0.6,0-1.1-0.1-1.7c0.1-0.5,0.1-1.1,0.1-1.7V997.6z M-523.8,1017.9
        c0,13.1-10.6,23.6-23.6,23.6c-13.1,0-23.6-10.6-23.6-23.6v-13.5h47.3V1017.9z M-523.8,1001H-571v-3.4c0-7.8,3.9-14.7,9.7-19
        l-7.1-7.1l2.8-2.8l7.8,7.8c3.2-1.6,6.7-2.5,10.5-2.5s7.3,1,10.5,2.5l7.8-7.8l2.8,2.8l-7.1,7.1c5.9,4.3,9.7,11.2,9.7,19V1001z"/>
    <path fill="#775DD0" d="M-571,1017.9c0,13.1,10.6,23.6,23.6,23.6c13.1,0,23.6-10.6,23.6-23.6v-13.5H-571V1017.9z"/>
    <path fill="#775DD0" d="M-533.5,978.6l7.1-7.1l-2.8-2.8l-7.8,7.8c-3.2-1.6-6.7-2.5-10.5-2.5s-7.3,1-10.5,2.5l-7.8-7.8l-2.8,2.8l7.1,7.1
        c-5.9,4.3-9.7,11.2-9.7,19v3.4h47.3v-3.4C-523.8,989.8-527.6,982.9-533.5,978.6z M-557.5,994.2c-1.9,0-3.4-1.5-3.4-3.4
        c0-1.9,1.5-3.4,3.4-3.4s3.4,1.5,3.4,3.4C-554.2,992.7-555.7,994.2-557.5,994.2z M-537.3,994.2c-1.9,0-3.4-1.5-3.4-3.4
        c0-1.9,1.5-3.4,3.4-3.4c1.9,0,3.4,1.5,3.4,3.4C-533.9,992.7-535.4,994.2-537.3,994.2z"/>
</g>
</svg>

The markers are added from a for loop to a group (H.map.Group) that was already added in the map. The lag is happening not while loading the markers, but when trying to move around the map or zoom in and out. It's very laggy especially when zoomed out and many markers are visible.
adding the group in the map:
this.map.addObject(this.markerGroup);

adding a marker:
addMarker(data) {
    const id = data.id;
    if (!mapObjects[id]) {
      let coords;
      coords = { lat: data.lat, lng: data.lon };
      const icon = new H.map.DomIcon(this.createMarkerIcon(data));
      this.mapObjects[id] = new H.map.DomMarker(coords, { icon: icon });
      this.mapObjects[id].setData(data);
      this.markerGroup.addObject(this.mapObjects[id]);
    } else if (this.markerChanged(data)) {
      this.updateMarker(data);
    }
  }

loop that adds the markers:
markers.forEach(markerData => {
      this.addMarker(markerData);
});

edit: svg added, snippets added

A: Caching could help you to avoid this zoom out lag. reading larger marker data again and again with complex svg making it laggy. you can try to store the markers in one variable and cache it if the data is not changing all the time, like below
var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

A: The problem was that I used H.map.DomMarker instead of H.map.Marker and the many html elements caused the map to lag.
H.map.Markers are rendered on the map and don't cause zooming and moving lag.


text:
Q: How to use the current Chrome Engine for Cordova Apps? I have a very big problem and unfortunately I cannot find a solution. Help from some professionals would be really great. Thanks!
The little problem
I have a Angular Web App / Android App using Cordova. My app needs at least the Chrome Engine 50 to support all functions and looks right. Unfortunately I noticed that there are many devices that use a much older version. Also the devices do not use a common source for the Chrome Engine. Some use the Chrome Browser itself or the Android System WebView. In these two cases I can tell my testers, install the two things and then it works. Currently I check at the start of the app which version is installed and if it is less than 50 I show an info that users have to update ther apps / components particularly important here the two things (Chrome Browser itself or the Android System WebView). I rather say my users that they should update all ther apps because some hardware manufacturers have their own apps that include the Chrome Engine. That alone I find very unpleasant.
The biger problem
But it is worse with devices that have their own Chrome Engine built into the firmware. So one that you can not update at all via the apps update only just the hardware manufacturer of the phone can update them with firmware updates. So many cheap devices that don't get any more updates simply fall out and bring me possibly bad ratings.
What can you do?
Maybe someone has an idea? Because this way I can put my app in the store from Android 4.4 on but even 6.0 devices have older Chrome Engine versions in their firmwares. Can't I provide a chrome engine version or say I use it there from Chrome or from the Android system WebView? I'm really on the edge and need a clever solution.
I would be very happy about some help or exchange. Thanks a lot.
Best regards
Robi


text:
Q: Can I purge linux-modules-4.* and linux-modules-extra-4.* packages? I have a plenty of old config-file status linux-modules-4.xxx and linux-modules-extra-4.xxx (see the pictures). The 5.x version of the Linux kernel is already out.
When I do wajig large there was a plenty of old packages, can I remove all of these and only keep the 5.x versions?
image1
image2


text:
Q: Is "belongs-on-serverfault" a real tag? I mean, really.  I like ice cream, but you don't see me making an i-like-ice-cream tag on SO.
If it really belongs on ServerFault, can't I be trusted to figure that out on my own?

A: We generally frown on the use of the "belongs-on-" tags.  Tags are supposed to be used to categorize questions, not direct what site a question belongs on.  People can flag for a moderator if they don't have the reputation to vote to close.  It also looks stupid once a question is migrated to retain the tag, just making more work on both ends (adding the tag and removing it later).

A: It is a generally frowned upon tactic, but I can see why some people who may not have the ability to vote may retag it in such a way to alert higher rep users who may be skimming the question lists.
I would also say that "bogus-tags" is not a very good tag itself. It has not been used any other times (at least not when this was written according to the sidebar). The purpose of tagging in general is to categorize questions into the correct buckets, and there are much larger and more comprehensive tags about tagging.

A: Besides the reasons TheTXI listed, it also let's new users know where they should have posted it.


text:
Q: why is this layout class not always working? This is my attempt to write my own layout class for a panel of buttons (which may have between 2 and 20 buttons). Basically they should all be of a uniform size, with a constant spacing (5px) and resize appropriately.
However it doesn't always work.
Sometimes it works absolutely fine, but others it gives space for an extra column, or becomes unable to add additional columns on resizing (removing columns is fine), or something wont work. And it takes ages and seems horribly expensive in terms of computations. Reducing width seems significantly more painful in this respect for some reason.
Anyway, here it is:
package layouts
{
    import mx.core.ILayoutElement;

import spark.components.supportClasses.GroupBase;
import spark.layouts.supportClasses.LayoutBase;

public class QButtonsLayout extends LayoutBase
{
    public function QButtonsLayout()
    {
        super();
    }

    override public function measure():void
    {
        super.measure();

        target.measuredHeight = 130;

    }

    override public function updateDisplayList(w:Number, h:Number):void
    {
        super.updateDisplayList(w,h);

        var tCount:int = target.numElements; // Number of elements
        var tW:Number = target.width; // Width of target (button area) - somewhere between 550 and 1000px

        var maxW:Number = 1; // Largest natural width of any given element
        var maxH:Number = 1; // Largest natural height of any given element

        var eSetW:Number = 1; // Set (to be) width of each element upon the target
        var eSetH:Number = 1; // Set (to be) height of each element upon the target

        var tCols:Number = 1; // Number of columns upon the target
        var tRows:Number = 1; // Number of rows upon the target

        for (var i:int = 0; i<tCount; i++) // Find maxW
        {
            var layoutElement:ILayoutElement = useVirtualLayout ? target.getVirtualElementAt(i):target.getElementAt(i);
            var thisW:Number = layoutElement.getPreferredBoundsWidth();
            var thisH:Number = layoutElement.getPreferredBoundsHeight();

            if(thisW > maxW)
            {
                maxW = thisW;
            };

            if(thisH > maxH)
            {
                maxH = thisH;
            };
        }

        tCols = Math.floor((tW-5)/(maxW+5)); //Find maximum number of columns one can fit onto the target

        if(tCols>tCount) //Fix to deal with cases with low tCounts
        {
            tCols = tCount;
        };

        tRows = Math.ceil(tCount/tCols); //Find corresponding number of rows

        eSetW = ((tW-5)/tCols)-5; //Set widths of elements based upon number of columns, 5s to add some space between elements
        eSetH = maxH; //Takes height as the largest height

        for (var j:int = 0; j<tCount; j++)
        {
            var layoutElement2:ILayoutElement = useVirtualLayout ? target.getVirtualElementAt(j):target.getElementAt(j);

            var eRow:int = Math.floor(j/tRows); //Row of given element, taking the 1st to be zero
            var eCol:int = j - eRow*tRows; // Column of given element, again taking the 1st column as zero

            var _x:Number = 5 + eRow*(eSetW+5);
            var _y:Number = 5 + eCol*(eSetH+5);

            layoutElement2.setLayoutBoundsPosition(_x,_y);
            layoutElement2.setLayoutBoundsSize(eSetW,eSetH);
        }
    }
}
}

Any thoughts would be much appreciated.
Criticism more than welcome.

A: Turns out that it's not. The layout class itself is fine, as far as calculating element positions and size is concerned.
It is actually a problem in the way in which the buttons used calculated their prefered widths. Whilst I'm not versed in the actual manner in which this happens, it was solved by removing %width values for any height and width values for graphic elements within the button skins. (Eg changing width="100%" to left="0" right="0").
I hope this might help someone, somewhere, sometime.


text:
Q: Change position of icons added to shipping methods Woocommcerce Based on this question I added some icons to the shipping methods of a store I'm building. I used png images by using this code:
add_filter( 'woocommerce_cart_shipping_method_full_label', 'filter_woocommerce_cart_shipping_method_full_label', 10, 2 );

function filter_woocommerce_cart_shipping_method_full_label( $label, $method ) {
// Use the condition here with $method to apply the image to a specific method.

if( $method->method_id == "flat_rate" ) {
   $label = $label.('');
} else if( $method->method_id == "local_pickup" ) {
   $label = $label.('');
}
return $label;
}

There is one thing I would like to change, and I can't figure out how to do it. I want the icons to show next to the shipping method name. No it's underneath. Any ideas of how to fix this?
Thanks in advance.
Vasco

A: You need to change display css property for your icons in your child theme's style.css file:
#shipping_method label > img {
    display: inline-block;
}

So you can test it in this code where styles are hard coded on the icons:
add_filter( 'woocommerce_cart_shipping_method_full_label', 'filter_woocommerce_cart_shipping_method_full_label', 10, 2 );

function filter_woocommerce_cart_shipping_method_full_label( $label, $method ) {
    $style = ' style="display:inline-block;"'; // Style applied to the thumbnails

    // Use the condition here with $method to apply the image to a specific method.
    if( $method->method_id == "flat_rate" ) {
       $label = '  ' . $label;
    } else if( $method->method_id == "local_pickup" ) {
       $label = '  ' . $label;
    }
    return $label;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.


text:
Q: conditional select with time adding calculation I have this table:
id | PlateNumber |  ImgDate |    ImgTime|
1  | abc123 |      2020-03-01 |  09:10:33|
2  | qwe128 |      2020-03-02|   09:13:39|
3  | abc123 |      2020-03-01|   09:11:21|

So, there are too many repeated plate numbers based on image capturing time.
I need a select statement that returns repeated records only when there is a time difference of more than 3 minutes. I hope that this makes sense.
Please help
Thank you guys!

A: You need to provide a bit more info, but you would want to compare the current row with the previous one (for each PlateNumber). You can do that using an analytical function like LAG.
WITH CTE as (
Select
  id
  ,PlateNumber
  ,ImgDate
  ,ImgTime
  ,LAG(ImgDate) OVER (PARTITION BY PlateNumber ORDER BY ImgDate,ImgTime) as PreviousDate
  ,LAG(ImgTime) OVER (PARTITION BY PlateNumber ORDER BY ImgDate,ImgTime) as PreviousImgTime
FROM YourTable
)
Select id
  ,PlateNumber
  ,ImgDate
  ,ImgTime
FROM CTE
  WHERE (PreviousDate is null and PreviousImgTime is null) -- to keep the first occurence
  OR (
      DATEDIFF(second,
         DATEADD(day, 0, DATEDIFF(day, 0, PreviousDate)) + DATEADD(day, 0 - DATEDIFF(day, 0, PreviousImgTime), PreviousImgTime) ,
         DATEADD(day, 0, DATEDIFF(day, 0, ImgDate)) + DATEADD(day, 0 - DATEDIFF(day, 0, ImgTime), ImgTime)
         ) > 180
      )

If your columns are DATE and TIME datatype
 OR (
          DATEDIFF(second,
            cast(PreviousDate as DATETIME) +cast(PreviousImgTime as DATETIME) ,
            cast(ImgDate as DATETIME) + cast(ImgTime as DATETIME),
            ) > 180
          )

A: In SQL Server, you can add datetime values, so you can do this basically just with lag():
select t.*
from (select t.*, v.dt,
             lag(dt) over (partition by platenumber order by dt) as prev_dt
      from t cross apply
           (values (convert(datetime, t.imgdate) + convert(datetime, t.imgtime))
           ) as v(dt)
     ) t
where prev_dt is null or prev_dt < dateadd(minute, -3, dt);


text: Q: Address Book with UITableView I would like to have a better idea of how to go about creating an address book with a UITableView. I currently have an app that displays a UITableView with a detail view with hardcoded data. What I want to to is be able to 1) add a new contact (TableVIewCell) and 2) then enter basic information that will be saved to the detail view. When the data is saved I want to display only one textfield to be displayed into the UITableVIewCell. I hope this makes sense! Thank you!!


text:
Q: Getting a Select Value after appending This is for javascript and jquery.
I have in my body...
    <select id="option1_select" name="courseCodeSelectName">
        <option></option>
        <option>Word1</option>
        <option>Word2</option>
    </select>
    <script>
        $("select").change(function () {
            functionLoadOpt2() }).trigger("change" );
    </script>

    <select id="option2_select" name="courseNumSelectName">
        <option></option>
    </select>
   <button onclick="changePage()">Load Textbook Page!</button>

As we see above, the web page has 2 select boxes and a button. Depending on what you select in the first select box loads what is in the second one, using the functionLoadOpt2 function locating higher up in my code.
if (result == "Word1") {
     $("#option2_select").append('<option>Letter1</option>');

...
There is more but it follows the same code different values.
Result is the following, above the if statement(just a row up),
var result = (document.getElementById('option1_select').value);

now on the button click, the function changePage() runs,
and all I want is ...
var result = (document.getElementById('option1_select').value);
var result2= (document.getElementById('option2_select').value);

Assume they selected and option for both. Result2 doesnt work. I'd imagine because I'm appending it but how would I work around this. So that when I click changePage() I get the selected value of option1_select and option2_select.
functionLoadOpt2:
function functionLoadOpt2(){

    var opt1Val = (document.getElementById('option1_select').value);

    $("#option2_select").find('option').remove().end().append('<option></option>');

    if (opt1Val == "Word1") {

        $("#option2_select").append('<option>Letter1</option>');
        $("#option2_select").append('<option>Letter2</option>');
        $("#option2_select").append('<option>Letter3</option>');
        $("#option2_select").append('<option>Letter4</option>');
        $("#option2_select").append('<option>Letter5</option>');
    }else if (opt1Val == "Word2") {

        $("#option2_select").append('<option>Letter3</option>');//they have similar ones in some cases
        $("#option2_select").append('<option>Letter6</option>');
        $("#option2_select").append('<option>Letter7</option>');
        $("#option2_select").append('<option>Letter8</option>');
        $("#option2_select").append('<option>Letter9</option>');
        $("#option2_select").append('<option>Letter10</option>');
        $("#option2_select").append('<option>Letter11</option>');
        $("#option2_select").append('<option>Letter12</option>');
        $("#option2_select").append('<option>Letter13</option>');
        $("#option2_select").append('<option>Letter14</option>');
        $("#option2_select").append('<option>Letter15</option>');
        $("#option2_select").append('<option>Letter16</option>');
        $("#option2_select").append('<option>Letter17</option>');

//this works

    }

}

A: use jQuery to get and set the value of <select> with .val()

A: Both your select elements have the same id, fix it the it should be fine
<select id="option1_select" name="courseCodeSelectName">
    <option></option>
    <option>Word1</option>
    <option>Word2</option>
</select>
<select id="option2_select" name="courseNumSelectName">
    <option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>

Demo: Fiddle
Note: You can improve the script a lot by using proper jQuery constructs, like this


text:
Q: How can I use a Pandas data structure to calculate autocorrelation? I have data in text files that I have successfully parsed into a MultiIndex pandas structure however I don't know if what I have will do what I want it to do.
What I have is a lot of time series data with many identifiers (indices).  I ultimately need to calculate auto correlation times and other time series statistics on each time series.
#!/usr/bin/python

from pandas import Series, DataFrame, MultiIndex
...
data = Series(value, index=[smear, block, obser])
print data

print data.ix[('0.07','1','0')]

This produces output like this for the data structure:
0.07  0  0     1.5802561
         1    0.82228274
         2    0.70917131
         3    0.90707599
         4     0.8517223
         5    0.26346815
      1  0     1.8163109
         1     0.9972372
         2     1.0872181
         3     1.2459765
         4     1.1500478
         5    0.35668446
      2  0     2.0734421
         1     1.2863641
         2     1.4033583
...
0.34  2  3     1.9047537
         4     1.8193612
         5    0.77739654
      3  0     2.2757423
         1     1.5499509
         2     1.6623247
         3     1.8330889
         4     1.7484187
         5    0.72914635
      4  0     2.3269071
         1     1.7137621
         2     1.7359068
         3     1.9162268
         4     1.9714984
         5     1.2095218
Length: 32100

and the time series information I am interested in exists at a specified value of smear, block, obser.  Here an example is given of smear = 0.07, block = 1, obser = 0.  The right most column is my time series data.
0.07  1  0    1.8163109
         0    1.8191682
         0     1.816836
         0    1.8172168
         0    1.8169705
...
         0    1.8184542
         0    1.8170772
         0    1.8159326
         0    1.8161826
Length: 107

How do I reshape the data such that I can write functions that will calculate auto correlation times?

A: First, use the "values" component of your data.ix(whatever) object to get the raw array of the time series. Then use numpy.correlate to calculate the autocorrelation, using the method described in the answers to this question.


text:
Q: appgc.setResizable(true); error So I've been making a game for a while now. Recently I ecnountered an error saying
 "Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    The method setResizable(boolean) is undefined for the type AppGameContainer

at felix.riskminer.game.MainGame.main(MainGame.java:1760)"

This started happening as soon as I added appgc.setResizable(true); to the code.
The problem is that if I remove it I get a bunch of other errors. Any fix?
With appgc.setResizable(true);

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    The method setResizable(boolean) is undefined for the type AppGameContainer

at felix.riskminer.game.MainGame.main(MainGame.java:1760)

without appgc.setResizable(true);

Exception in thread "main" java.lang.UnsatisfiedLinkError: no lwjgl64 in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at org.lwjgl.Sys$1.run(Sys.java:72)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.lwjgl.Sys.doLoadLibrary(Sys.java:66)
    at org.lwjgl.Sys.loadLibrary(Sys.java:87)
    at org.lwjgl.Sys.<clinit>(Sys.java:117)
    at org.lwjgl.opengl.Display.<clinit>(Display.java:135)
    at org.newdawn.slick.AppGameContainer$1.run(AppGameContainer.java:39)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.newdawn.slick.AppGameContainer.<clinit>(AppGameContainer.java:36)
    at felix.riskminer.game.MainGame.main(MainGame.java:1759)

LIBRARIES THAT ARE BEING USED: Slick2D and LWJGL
Thanks in advance.

A: For missing setResiable method: I can't find this method in the official documentation. It may depends on the version of slick you're using. To correct this you can go for this solution posted here

In your StateBasedGame, in your main method, you can call lwjgl's Display object,
Display.setResizable(true);
This will allow you to resize/maximize the Display window. Make sure
  you have a recent version of lwjgl!

Check lwjgl jar and native, restart your IDE and come back if you still have problem with classloading.


text:
Q: jQuery and the this object jQuery is too overpowering :(
String.prototype.trim = function () {
    return this.replace(/^(\s| |\u00A0)+|(\s| |\u00A0)+$/g, "");
}

when I try to add the above code, I get "this.replace is not a function".
I realise that jQuery references itself as this, so how are you meant to reference this?

A: The code you've posted defines a "trim" method on a String.  That allows you to do this:
"  some random string  ".trim();

Sounds like you've copied and pasted the BODY of that trim function into some other jQuery function, like this:
$('#myfield').change(function () {
  this = this.replace(/^(\s| |\u00A0)+|(\s| |\u00A0)+$/g, "");
});

Try this instead:
$('#myfield').change(function () {
  $(this).val($(this).val().trim());
});

A: Problem solved:
I forgot to put the semi colon on the end of the function and it was running in to the jQuery function
String.prototype.trim = function () {
    return this.replace(/^(\s| |\u00A0)+|(\s| |\u00A0)+$/g, "");
};

(function ($) {
......


text:
Q: For loop in pandas dataframe column For example I have 2 data frames with 3 columns and I want to do
a = df[x].isin(df2[x])
b = df[x].isin(df2[y])
c = df[y].isin(df2[x])
d = df[y].isin(df2[x])

x and y is a column name of my two dataframes. How can I do it in loop and save each result ? So it can be elegant.
The result I expected more or less :
a; True = ddd
   False = eee
b; True = rrr
   False = fff
c; and so
d; and so

thanks

A: You need two loops:
columns = (x, y)
for a in columns:
    for b in columns:
        df[a].isin(df2[b])


text:
Q: How should I return to a previous dialog from another one? I've got an inputDialog, which allows for some text inputs. On clicking save, the inputDialog checks if the entered text is already available (to prevent double entries). If this is the case, a new AlertDialog is created, simply stating "The value you entered already exists", with just an "Ok" button to dismiss this AlertDialog. This all works.
I would like to have the inputDialog pop back up again, after dismissing the AlertDialog, with the values that were entered by the user before still in the editText fields.
I'm not expecting any problems on getting those values back in the editText fields (Store them in a variable on clicking save, if the double entry error occurs, set those variables on the editText's. If I'm doing this in a stupid way, please let me know).
I am however having trouble with getting the first (inputDialog) dialog to come back. The code you see below is the code for my inputDialog fragment (The code is simplified, so if something seems to be missing, it probably is. Let me know, so I can add it back in.)
So, to repeat myself: How can I return to the previous dialog after dismissing the second one?
StuffManagerInputDialogFragment.java:
public class StuffManagerInputDialogFragment extends DialogFragment {

    EditText nameInputField;
    EditText tagInputField;
    DBHandler dbHandler;
    StuffManagerFragment f = new StuffManagerFragment();

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater inflater = getActivity().getLayoutInflater();

        final View v_iew = inflater.inflate(R.layout.fragment_inputdialog, null);

        nameInputField = (EditText) v_iew.findViewById(R.id.inputdialogname);
        tagInputField = (EditText) v_iew.findViewById(R.id.inputdialogtag);
        dbHandler = new DBHandler(getActivity(), null, null, 1);
        final MainActivity ma = (MainActivity) getActivity();

        final AlertDialog.Builder newLinkDialog = new AlertDialog.Builder(getActivity());
        newLinkDialog.setView(v_iew)
                .setTitle("New Link")
                .setPositiveButton("Save", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String nameInputFieldText = nameInputField.getText().toString();
                        String tagInputFieldText = tagInputField.getText().toString();
                        ArrayList<String> nameArray = dbHandler.nameArrayMethod();
                        ArrayList<String> tagArray = dbHandler.tagArrayMethod();
                        NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
                        Menu menu = navigationView.getMenu();

                        if (nameArray.contains(nameInputFieldText) || tagArray.contains(tagInputFieldText)) {
                            if (nameArray.contains(nameInputFieldText) && tagArray.contains(tagInputFieldText)) {
                                AlertDialog.Builder errorBoth = new AlertDialog.Builder(getActivity())
                                        .setTitle("Error")
                                        .setMessage("The name and tag you entered are already in use.")
                                        .setIcon(R.drawable.ic_error_black)
                                        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                //Return to previous dialog here
                                            }
                                        });
                                        errorBoth.show();
                            }
                        } else {
                            dbHandler.addLink(nameInputFieldText, tagInputFieldText);
                            nameArray = dbHandler.nameArrayMethod();

                            int nameArraySize = (nameArray.size() - 1);
                            MenuItem item = menu.add(R.id.group1, nameArraySize, 1, nameArray.get(nameArraySize));

                            Toast.makeText(getContext(), "'" + nameInputFieldText + " - " + tagInputFieldText + "' link saved.", Toast.LENGTH_SHORT).show();

                            ma.addSMVFFragments();
                            f.hideDeleteAllButton = false;
                            getActivity().invalidateOptionsMenu();
                        }
                    }
                })
                .setNegativeButton("Cancel", null);
        return newLinkDialog.create();
    }
}

A: A better solution is to have a dialog fragment for your input layout, and that dialog fragment would display an AlertDialog on OK if the text validation fails. The input dialog fragment would not dismiss in this case, it will remain in the background so when you dismiss the alert dialog to tell the user the input is invalid, you return to the input dialog as it was.
To prevent the dialog fragment from dismissing on OK you would override onStart and get a reference to the OK button and set the listener there, like this:
@Override
public void onStart() {
    super.onStart();
    AlertDialog alertDialog = (AlertDialog) getDialog();
    if (alertDialog != null) {
        mOKButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
        mOkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (field OK) {
                    // save data
                    dismiss();
                } else {
                    // show error dialog
                }
            }
        });
    }
}


text:
Q: Why pi() function does not work in Oracle using its JDBC driver? Query 1 works fine with the Oracle JDBC driver but Query 2 doesn't. I don't understand why. Please, could someone help me?
Query 1:
SELECT {fn pi()} FROM table;

Query 2:
SELECT pi() FROM table;

A: There is no native pi() function in Oracle. The JDBC driver will simply replace that with a hardcoded value.
If you run
SELECT {fn pi()} FROM dual;

The driver will send:
SELECT ( 3.141592653589793238462643383279502884197169399375 )
FROM
 dual

to the server - that's why you can use the {fn pi()} against an Oracle database even though there is no such function available.

A: You can use this equation:
select 2*asin(1) from dual;
Or can define a function that returns this number as below:
create or replace function PI return numeric is
  Result numeric;
begin
  select 2*asin(1)
  into Result  from dual;
  return(Result);
end PI;

A: There doesn't seem to be any native function called PI. The error suggests that you haven't created a user-defined function either.
The {fn foo()} syntax is provided by JDBC, thus won't work without it:

JDBC escape syntax for fn keyword
You can specify functions in JDBC escape syntax by using the fn
  keyword. Syntax
{fn functionCall}

where functionCall is the name of one of the scalar functions listed
  below.

... and following the previous link we can see that the underlying PI() function is provided by Java DB and/or Apache Derby.

A: for me id did not work with numeric so i changed to float
create or replace function PI return float is
  Result float;
begin
  select 2*asin(1)
  into Result  from dual;
  return(Result);
end PI;


text:
Q: C++ print number with decimals I have a GPS antenna attached to a Raspberry Pi and tried to get its coordinates through C++ with the gps.h library. In there, the latitude is defined as double. Now, when I tried to print it out using printf, with %d the output is 5 and with %f it's 0.000000. I'm just tying to get the exact number that's behind the latitude.
I live in Switzerland and the latitude here is at around 47 degrees. I think that the latitude is stored as 4.7... and there could be some rounding happening, hence the output 5.
Thanks to everybody
edit:
struct gps_data_t gps_d;
printf("%d\n", gps_d.fix.latitude);

A: I see that gps_d.fix.latitude is a double value, you have to use either %f or %lf to print it using printf. And it also says valid if mode is >=2 so check your code if this is the case. If %f is printing 0.0 then probably the variable value contains actually 0.0.
double latitude;    /* Latitude in degrees (valid if mode >= 2) */

However, if you are programming in C++ then you can also print as below:
std::cout << gps_d.fix.latitude << std::endl;

A: I agree with Jabberwocky. You can try to read the NMEA to check whether the GPS works.
cat /dev/<GPS Serial Port>


text:
Q: Oracle + Java, huge json unload to file Usually, I try to dig out some info on my problems from the Internet without asking questions, but this time - I'm kinda stuck...
The problem is, that I have few huge tables containing JSON objects in rows. The final output is a JSON string with all of the objects, so it can be sent to our headquarters as a operational report. One, single report contains approx. 15GB of data in very specific structure.
The report has this structure:
{header1:value,
header2:value,
[...]
sub_objects:[
 sub_object1:[{row1tab1},{row2tab1}...(6GB of data, 14 milions of rows)],
 sub_object2:[{row1tab2},{row2tab2}...(another 5GB of data, 6 milions of rows)],
 sub_object3:[...]
]}

Now, the problem is that my query builds whole, complete 15GB's string on the database side, and then, it's unloaded to a text file using a Java console app, that I've written some time ago. It's nothing fancy - simple query and fetching data as binary stream directly to file.
The above process works fine, but the time is killing me (and soon - my boss will want to kill me also). It takes approx. 5 hours to build the complete string. What's funny - if I'll store the string in database - the unloading process takes only 5 minutes. But still - storing the string in database takes 5 hours.
I'm trying to find some different angle here to fetch the data during query execution on the server's side, so I'd build the complete string directly in file, and not on the database side.
Any help would be much appreciated! If you'll need any extra info on this - don't hesitate to ask - I'll try to provide as much as I can.
Thank you in advance!
Tom


text:
Q: Filtering a list of tuple data I have a list like below.
list1 = [
    ('Ram','Laxman','Bharat','Sita'),
    ('Ram','Ravan','Bharat','Sita'),
    ('Ram','Luv','Dashrat','Sita'),
    ('Dasrath','Kekei','Bharat','Ram'),
    ('Laxman','Bharat','Ram','Hanuman'),
    ('Hanuman','Sita','Kekei','Ravan'),
    ('Ram','Sita','Hanuman','Ravan')
]

I want to filter the list data which has at least 3 tuple values matching , If 2 or more tuples have at least 3 value matching then only 1st tuple should be there in the list along with rest.
For example in above list we have below list tuple which has 3 value matching.
result = [
    ('Ram','Laxman','Bharat','Sita'),
    ('Ram','Luv','Dashrat','Sita'),
    ('Dasrath','Kekei','Bharat','Ram'),
    ('Hanuman','Sita','Kekei','Ravan')
]

A: from operator import add
from functools import reduce

def solve(xss):

    mems = [xss[0]]

    for xs in xss[1:]:
        if len(set(reduce(add,mems)).intersection(set(xs))) < 3:
            mems = mems + [xs]
    return mems

A: I think your question is interesting. I use some matrix operation to solve it. This way I think will much faster than common loop.
from collections import OrderedDict
import numpy as np
from sklearn.preprocessing import MultiLabelBinarizer

class DuplicateFinder(object):
    def __init__(self, raw_list):
        self.raw_list = raw_list
        self.multi_label_encoder = MultiLabelBinarizer()
        self.final_results = OrderedDict()
        self.title_select = []
        self.content_select = []
        self.not_select = []

    @property
    def match_result(self):
        label_matrix = self.multi_label_encoder.fit_transform(self.raw_list)
        return np.dot(label_matrix, label_matrix.T)

    @property
    def raw_results(self):
        return np.array(np.where(self.match_result >= 3)).T

    def solve(self):
        for result in self.raw_results:
            if result[0] == result[1]:
                continue
            if result[0] in self.content_select:
                continue
            if result[0] not in self.final_results:
                self.final_results[result[0]] = []
                self.final_results[result[0]].append(result[1])
                self.title_select.append(result[0])
                self.content_select.append(result[1])
            elif result[1] not in self.content_select + self.title_select:
                self.final_results[result[0]].append(result[1])
                self.content_select.append(result[1])
            else:
                continue
        self.not_select = list(set(range(self.match_result.shape[0])) - set(
            self.title_select + self.content_select
        ))

    def print_result(self):
        print(f"This is more than one matched: {self.final_results}")
        for key in self.final_results:
            print(self.raw_list[key])
        print(f"This is just one: {self.not_select}")
        for key in self.not_select:
            print(self.raw_list[key])

list1 = [
    ("Ram", "Laxman", "Bharat", "Sita"),
    ("Ram", "Ravan", "Bharat", "Sita"),
    ("Ram", "Luv", "Dashrat", "Sita"),
    ("Dasrath", "Kekei", "Bharat", "Ram"),
    ("Laxman", "Bharat", "Ram", "Hanuman"),
    ("Hanuman", "Sita", "Kekei", "Ravan"),
    ("Ram", "Sita", "Hanuman", "Ravan"),
]
solver = DuplicateFinder(list1)
solver.solve()
solver.print_result()

This is the result:
This is more than one matched: OrderedDict([(0, [1, 4]), (5, [6])])
('Ram', 'Laxman', 'Bharat', 'Sita')
('Hanuman', 'Sita', 'Kekei', 'Ravan')
This is just one: [2, 3]
('Ram', 'Luv', 'Dashrat', 'Sita')
('Dasrath', 'Kekei', 'Bharat', 'Ram')


text:
Q: Is it ok, then additional tags of Angular break html-layout in dev mode? I insert two components inside template of another one.
// my.component.html

    <app-products-menu [dropped]="false"></app-products-menu>
    <app-top-menu></app-top-menu>

And after ng serve -o I look at page source html code:

Of course bootstrap cols within row don't work. How can I test my html? Maybe I have posibillity to turn off this feature or smth else?

A: There are a couple of options. In both cases, you'll need to remove the

 from your component templates.
If you want to avoid the presence of the custom tag for each component, you can change your selector for each to an attribute, e.g.: selector: '[appProductsMenu]' and bind that to the columns:

Another option is to remove the columns from the components and move the class to your component tags:
<app-products-menu class="col"></app-products-menu>

This is often the case when you're working with a CSS framework that expects a certain hierarchy.


text:
Q: 'Strict Standards: Only variables should be passed by reference' error I am implementing phpmobilizer on a website.  I have created a subdomain "m" which contains a file with the following code (this is just one section):
function __construct($url){
    $this->url = $url;
    $this->server = preg_replace('/^m\./', '', $_SERVER['SERVER_NAME']);
    $this->ext = strtolower(end(explode('.', $this->url)));
    $this->patterns = array();
    $this->replacements = array();
    $this->cookieDomain = $this->__getCookieDomain();
}

The error I am getting is on line 15:
$this->ext = strtolower(end(explode('.', $this->url)));

Strict Standards: Only variables should be passed by reference in website.com/m/phpmobilizer.class.php on line 15

This is the code I am using in the head section to redirect mobile users to the "m" subdomain.  I have tested the mobile subdomain with Google's mobile friendly test and it is working correctly.

A: The error is being caused by the use of 'end()'. The array is passed to end() by reference.
Try splitting the code up e.g.
$urlParts = explode('.', $this->url);
$this->ext = strtolower(end($urlParts));

Reference:
http://php.net/manual/en/function.end.php


text:
Q: How to querying and aggregate multiple collection in Firebase I need to retrieve a monthly work orders collection by project and list of users (in the month I could have some project's OdL hours not included in the users list and the users could have some OdL of other projects).
The OdL model contains the strings for project (projectCode) and user (userId).
I send to the service the dates in Timestamp format, the code of the project and an array with users list.
this.loadGantt(from: Timestamp, to: Timestamp, projectCode: string, users: string[]){...}

I tried to execute single queries, one for project code and one for single user.
These are the queries of the service:
this.docs = this.afs.collection<OdlModel>('odl', ref => {
      return ref.where('projectCode', '==', project)
        .where('date', '>=', from)
        .where('date', '<=', to)
        .orderBy('date', 'asc');
    })
      .snapshotChanges().pipe(map(coll => {
        return coll.map(doc => ({ id: doc.payload.doc.id, ...doc.payload.doc.data()}));
      }));
    return this.docs;

this.docs = this.afs.collection<OdlModel>('odl', ref => {
      return ref.where('userId', '==', user)
        .where('date', '>=', from)
        .where('date', '<=', to)
        .orderBy('date', 'asc');
    })
      .snapshotChanges().pipe(map(coll => {
        return coll.map(doc => ({ id: doc.payload.doc.id, ...doc.payload.doc.data()}));
      }));
    return this.docs;

This is the solution that I found:
loadGantt() {
    const momentDate: Moment = moment(new Date());
    this.firstDay = momentDate.startOf('month').toDate();
    this.lastDay = momentDate.endOf('month').toDate();
    const from = firebase.firestore.Timestamp.fromDate(this.firstDay);
    const to = firebase.firestore.Timestamp.fromDate(this.lastDay);
    this.odl = [];
    const odlArray = [];
    const a$ = this.odlService.getProjectOdlCollection(from, to, 'IGNC0954-IMI-19');
    odlArray.push(a$);
    this.user.forEach(u => {
      const b$ =  this.odlService.getUserOdlCollection(from, to, u);
      odlArray.push(b$);
    });
    const result$ = combineLatest([odlArray]);

    result$.subscribe(res => {
      res.map(r => {
         r.subscribe(odl => {
           odl.forEach(o => {
             const index = this.odl.findIndex(x => x.id === o.id);
             if (index === -1) {
               this.odl.push(o);
             }
           });
         });
      });
    });
  }

How to I get all data in a single Observable object?

A: Below is a snippet which shows how to combine two or more Firestore collections from AngularFire into a single Observable object.
Link here
Data Structure
const usersRef = this.afs.collection('users');

const fooPosts = usersRef.doc('userFoo').collection('posts').valueChanges();
const barPosts = usersRef.doc('userBar').collection('posts').valueChanges();

Solution
import { combineLatest } from 'rxjs/observable/combineLatest';

const combinedList = combineLatest<any[]>(fooPosts, barPosts).pipe(
      map(arr => arr.reduce((acc, cur) => acc.concat(cur) ) ),
      )

Also this example may also help with your issue.
Let me know if this was helpful.


text:
Q: How to extract property names from custom class in C# I am making function for exporting table to .csv file.
I have List where T is custom class.
I need property names of T for columns in .csv file.
How can I extract them to other List ?

A: You can use reflection:
var propertyNames = typeof(T).GetProperties()
      .Select(p => p.Name));

A: Your question was a tad hard to understand.
However I wrote some example code for you, hopefully it answers your question.
As I believe you just needed help with the reflection part of the question.
using System.Reflection;

namespace Example
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            var types = Assembly.GetExecutingAssembly().GetTypes();
            foreach (var type in types)
            {
                var props = GetProperties(type);

                foreach (var property in props)
                {
                    Console.WriteLine($"Type: {type.FullName} -> Property: {property.Name}");
                }
            }
        }

        public static PropertyInfo[] GetProperties(Type T)
        {
            return T.GetProperties();
        }
    }

    public class TestClass
    {
        public int Health { get; set; } // Example property
    }
}

A: I maintain some libraries that make this very easy: Sylvan.Data.Csv and Sylvan.Data.
The Sylvan.Data library provides an API for turning an IEnumerable<T> into a DbDataReader (AsDataReader). The Sylvan.Data.Csv library provides an API for writing DbDataReader to a CSV file (CsvDataWriter). You can combine these to make an extension method:
using Sylvan.Data;
using Sylvan.Data.Csv;

static class CsvMethods
{
    public static long WriteAsCsv<T>(this IEnumerable<T> seq, string file)
        where T : class
    {
        using var writer = File.CreateText(file);
        return WriteAsCsv(seq, writer);
    }

    public static long WriteAsCsv<T>(this IEnumerable<T> seq, TextWriter output)
        where T : class
    {
        using var csvWriter = CsvDataWriter.Create(output);
        return csvWriter.Write(seq.AsDataReader());
    }
}

You can then write your List<T> to a CSV file with one line of code:
List<MyData> data = ...;
data.WriteAsCsv("mydata.csv");

The code implementing these libraries is extremely efficient, and will handle CSV edge-cases like fields containing delimiters, quotes, etc.


text:
Q: How to create Tkinter GUI that accepts Malayalam Unicode as input? How can I write Malayalam Unicode script from keyboard in Text widget created using Tkinter in python. I tried by setting font to the Text widget as
self.area = tk.Text(self, height=5, width=45, font=('MLU-Panini', 15))

While entering input from keyboard shows '????' for characters.


text:
Q: Trying to get jquery code to work in external file without conflicting with other jquery code When I put this simple code in it's own file i get some jquery conflicts with another code.
jQuery(function ($){

        $(".tabContents").hide();
        $(".tabContents:first").show();

        $("#tabContainer ul li a").click(function(e){
            e.preventDefault();
            var activeTab = $(this).attr("href");
            $("#tabContainer ul li a").removeClass("active");
            $(this).addClass("active");
            $(".tabContents").hide();
            $(activeTab).fadeIn();
        });

    });

But when I put it in the php file like so
<script type="text/javascript">
    jQuery(function ($){

        $(".tabContents").hide();
        $(".tabContents:first").show();

        $("#tabContainer ul li a").click(function(e){
            e.preventDefault();
            var activeTab = $(this).attr("href");
            $("#tabContainer ul li a").removeClass("active");
            $(this).addClass("active");
            $(".tabContents").hide();
            $(activeTab).fadeIn();
        });

    });
</script>

Every thing works fine. How can I alter the code to get it to work in an exteral file vs putting in the php file? Note the exteranl files are joined, minified and compress. I also tried without joined, minified and compress. The Jquery version is 1.6

A: What file are you saving your jQuery into? You want to do something like this:
index.html
<html>
    <head>
        <script type="text/javascript" src="jquery.min.js"></script>
        <script type="text/javascript" src="myscript.js"></script>
    </head>
    <body>
        <!-- Your Body Code-->
    </body>
</html>

myscript.js
jQuery(function ($){

    $(".tabContents").hide();
    $(".tabContents:first").show();

    $("#tabContainer ul li a").click(function(e){
        e.preventDefault();
        var activeTab = $(this).attr("href");
        $("#tabContainer ul li a").removeClass("active");
        $(this).addClass("active");
        $(".tabContents").hide();
        $(activeTab).fadeIn();
    });

});


text:
Q: Creating hrefs to subdomains with localhost during development I have several angular applications I would like to have links that go to each other.
For example in App1 I may have the following App2. This works when the application is live, but during development, this does not work as app2 is being hosted on localhost:50001.
Is there a way to setup some type of proxy that captures my subdomains and routes them to the proper localhost during development?

A: If you are using angular-cli, you can make use of the environment.ts file under /src/environments.
You can define environment specific values in these environment files
environment.<some-environment-name>.ts

Example:
environment.prod.ts (Production environment)
export const environment = {
    production: true,
    api: {
        baseUrl: "http://app2.apps.com"
    },
    // some other properties if required
};

And another object for for development
environment.ts (dev environment)
export const environment = {
    production: false,
    api: {
        baseUrl: "http://localhost:50001"
    },
    // some other properties if required
};

If you have any more environments, you can additional environment files,
environment.stage.ts (staging environment)
export const environment = {
    production: false,
    api: {
        baseUrl: "http://app2.stagingapp.com"
    },
    // some other properties if required
};

Then, declare them in angular-cli.json under apps property
apps: {
    ..
    ..
    "environmentSource": "environments/environment.ts",  // this should be imported in all the components/services etc
    "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts",
        "stage": "environments/environment.stage.ts"
    }
}

To use these values anywhere else (Components, Services etc)
import { environment } from ../environments/environment

and then use it
foo.service.ts
private readonly API_URL = `${environment.api.baseUrl}/foo`

public getFoo() {
    return this._http.get(API_URL);
}

NOTE: Never import a specific environment file in any of the components or services,
for example,
You should NEVER do this
import { environment } from ../environments/environment.prod; // NEVER do this

instead
When running with ng serve, use the --environment or --env option to specify the environment values and angular-cli will take care of the rest.
ng serve --env=prod  // uses values in environment.prod.ts
ng serve --env=stage // uses values in environment.stage.ts
ng serve             // uses values in environment.ts

When doing a ng build, use the --prod flag for production builds
ng build --prod

To build with other environments, you can use the --env option to specify the environment
ng build --env=stage

Hope this helps.


text:
Q: System signal interception in Julia In a Julia program which run under Linux, I need to launch a dedicated action  when a console window is resized. So how in Julia, can I intercept  the system signal SIGWINCH (window resizing) and attach to it a function which performs the required action ?
In Ada it is rather straightforward to declare it :
 protected Signalhandler is
      procedure Handlewindowresizing;
      pragma Attach_Handler (Handlewindowresizing, SIGWINCH);
 end Signalhandler;

TENTATIVE SOLUTION BASED ON IDEA OF SCHEMER : I try to use a C Library which conducts the SIGWINCH interruption monitoring.
myLibrary.h
void Winresize (void Sig_Handler());

myLibrary.c
#include "myLibrary.h"
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

void Winresize(void sig_handler (void)) {
     signal(SIGWINCH, sig_handler);
}

Compilation & Library preparation
gcc -c -Wall -fPIC myLibrary.c
gcc -shared -fPIC -o myLibrary.so myLibrary.o
Program in Julia which uses the C-Library :
function getc1()
ret = ccall(:jl_tty_set_mode, Int32, (Ptr{Cvoid},Int32), stdin.handle, true)
ret == 0 || error("unable to switch to raw mode")
c = read(stdin, UInt8)
ccall(:jl_tty_set_mode, Int32, (Ptr{Cvoid},Int32), stdin.handle, false)
c
end

function traitement() println(displaysize(stdout)); end
Mon_traitement_c = @cfunction(traitement, Cvoid, ())
ccall((:Winresize, "/home/Emile/programmation/Julia/myLibrary.so"), Cvoid, (Ptr{Cvoid},), Mon_traitement_c)

while true
println(getc1())
end

The Julia program run properly but when the terminal window is resized a Segmentation fault (core dumped) is issued and program is said exited with code: 139.
So the question is where does this segmentation fault come from ? From the compilation model ? Julia has not the right to control code execution in the memory part where C manages the signal monitoring ?
Removing println operation in Sig_handler suppress the segmentation fault :
curr_size = displaysize(stdout)
new_size = curr_size
function traitement()  global new_size ; new_size = displaysize(stdout); return end

Mon_traitement_c = @cfunction(traitement, Cvoid, ())

ccall((:Winresize, "/home/Emile/programmation/Julia/myLibrary.so"), Cvoid, (Ptr{Cvoid},), Mon_traitement_c)

while true
    global curr_size, new_size
    if new_size != curr_size
       curr_size = new_size
       println(curr_size)
    end
    sleep(0.1)
end

A: Since no one has answered this question so far, one possible workaround could be asynchronously monitoring the size of the terminal in some time intervals.
function monitor_term(func)
    @async begin
        curr_size = displaysize(stdout)
        while (true)
            sleep(0.1)
            new_size = displaysize(stdout)
            if new_size != curr_size
                curr_size = new_size
                func()
            end
        end
    end
end

And now sample usage:
julia> monitor_term(() -> print("BOO!"))
Task (runnable) @0x0000000013071710

As long as the terminal is alive, any change to its size will print BOO!.

A: Yes, it is indeed a fallback solution which is hardly what one expects from a new language full of promises ... but for lack of thrushes we can actually eat blackbirds (smile).
But if Julia hasn't planned to be able to take into account the system signals of the Unix/Linux world, it might be possible to do it using a C library like the one that signal.h accesses.
 #include <stdio.h>
 #include <stdlib.h>
 #include <signal.h>

 void sig_handler(int signum)
 {
    printf("Received signal %d\n", signum);
 }

int main()
{
   signal(SIGINT, sig_handler);
   sleep(10); // This is your chance to press CTRL-C
   return 0;
}

We would have to define a julia function doing what is expected when the system signal is received. Make it usable in C as Sig_handler and call from julia  the C statement signal(SIGWINCH, Sig_handler);
I am not enough familiar with julia to write the exact code. But this is the idea...


text:
Q: wso2 esb enrich target xml node I have an xml which is following structure
<XML><Payload><InXML></InXML><Endpoint><Response/></EndPoint>

i want to enrich this payload tag InXML, i have tried the following way but it seems it's failing and works only if we enrich the xml property/body as a whole,
so it gets appended to <XML> tag as a child but not to InXML
Suppose the above xml is current set in body
<enrich>
<source type="property" clone="true" property="inputXML"/>
<target type="custom" action="child" xpath="//InXML"/>
</enrich>

I have referred this as well but my case is different.

A: If you have defined the inputXML as bellow before the enrich mediator, then make sure to define the type attribute as "OM".
Eg:
<property name="inputXML" expression="//foo/bar" type="OM"/>

A: The selection of target action "replace" or "child" depends on the source type (when the defined property for the source isn't set with type="OM").
source is property:
<source type="property" clone="true" property="inputXML"/>
<target type="custom" action="replace" xpath="//InXML"/>
source is inline:
<source type="inline" clone="true">
  <test>1234</test>
</source>
<target type="custom" action="child" xpath="//InXML"/>


text:
Q: Angular correct login flow and structure I am trying to implement a frontend with angular, but I am not sure if my login and overall flow is correct.
I have a login component for the login page which sends the user information to an auth service for authentication, then I save the auth token in the localhost and send it with every get request for the user data, but also I need to check for expired jwt token so I logout the user and clear the localstorage from the information. But I am not sure where this logout should happen.
Also my home page displays 2 different views if the user is logged or not, so I have a boolean in the service that I check. This is my flow:
The login component: Here the error is bind to the html lets say if credentials are invalid
export class LoginComponent implements OnInit {
  error : string;

  constructor(private authService : AuthService) { }

  ngOnInit() {
    this.authService.login("Robocop1", "password").subscribe(
      data =>{
        localStorage.setItem('Authorization', data['token'])
        this.auth.isLoggedIn = true
      },
      err  => this.error = err['error']
    );
  }

}

Service component:
export class AuthService {

  isLoggedIn : boolean = false

  constructor(private httpClient : HttpClient) { }

  login(username, password) {
    return this.httpClient.post('http://localhost:8090/login', {
      username,
      password
    })
  }
}

This is my home component that checks first if the user is logged:
export class HomeComponent implements OnInit {

  isLoggedIn : boolean

  constructor(private auth : AuthService) { }

  ngOnInit() {
    this.isLoggedIn = this.auth.isLoggedIn

  }

}

And displays different part of the html:

           hey user

           not logged

So my question is is injetcing a dependencies in the home component ok just to check for single boolean and is there a better way to do it.
Also I can have another data component where I get user data from the database. In the post request I am sending the authentication token so I will have something like:
this.dataService.getItems().subscribe(
    data =>{
        this.userData = data
    },
    err  => {
        if(err['error' === 'Jwt token has expired'){
            this.authService.logout()
        }else{
            this.error = err['error']
        }
    }
);

So is again injecting dependency just to call a logout method ok? should this logout method be in the authService or elsewhere?

A:
So my question is is injetcing a dependencies in the home component ok
  just to check for single boolean and is there a better way to do it.

If your application will be about a couple of simple pages and will not expand, your approach might be enough but for it the best practise is using Angular Route Guards
A route guard is a CanActivate implementation in which you implement your authentication/authorization logic to guard your routes (pages)

So is again injecting dependency just to call a logout method ok?
  should this logout method be in the authService or elsewhere?

This should be done implementing an HttpInterceptor. So that you don't need to handle each http call for handling faulty responses or adding authorization tokens. Catching the error response inside your http interceptor and logging out is the way to go. That way you do not have to inject your corresponding service into each place this is required.
HttpInterceptor is also not a big deal. You can follow this step by step guide and implement your own


text:
Q: min-height doesn't work I have a weird problem. I need two backgrounds on the bottom of the website in left and right corner (always stick it to the bottom of the whole browser's window) so I used min-height in CSS, like this:
For body, html - height: 100%;
For inner wrap div - height: auto !important; height: 100%; min-height: 100%;
This should do the whole trick and always display a div with 100% but it doesn't work at all, I'm getting a bit desperate from it.
Here is the demo: http://clients.youweyoucoding.com/jm/peter-bilka/crescita/
Is there something wrong in the code?

A: I think your additional wrappers may be causing you issues.
I'd possibly go back to a basic 100% height layout and then add your content.
This works across all browsers including IE6.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<title>100% Height CSS Layout</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Quisque tempor. Nam in libero vel nisi accumsan euismod. Quisque quis neque. Donec condimentum, enim convallis vestibulum varius, quam mi accumsan diam, sollicitudin ultricies odio ante vitae purus. Etiam ultricies quam. Vestibulum turpis turpis, fermentum ut, accumsan quis, tempor at, ipsum. Nam felis elit, sollicitudin id, ultrices faucibus, fringilla vel, dui. Aliquam tincidunt iaculis eros. Sed in lorem. Nullam eu enim. Quisque tristique pretium diam. Fusce tempor sollicitudin ligula. Donec purus eros, mattis quis, mattis vestibulum, congue quis, felis. Nulla facilisi. Nam ultricies posuere justo. In feugiat.

A: This:
height: auto !important; height: 100%; min-height: 100%;

is not really necessary. You probably want height: auto; min-height: 100%;
EDIT: ignore what I wrote before the edit, I just overlooked the div :)
EDIT 2: Opera tells me that height of the div is 551px but height of the wrapper div is just 451px. This is caused by the wrapper div having a 100px bottom padding that increases the height.


text:
Q: Stokes's theorem outer unit normal for a hemisphere Stokes's theorem says
$$\oint \mathbf{F}.d\mathbf{r}=\iint_{D}^{-} \nabla \times \mathbf{F}\cdot \mathbf{n} \, dA$$
Evaluate using the RHS of Stokes' theorem the following problem.
for the hemisphere
$$S:x^{2}+y^{2}+z^{2}=9,$$
$$z\geq 0,$$ its bounding circle $$C:x^{2}+y^{2}=9,$$
$$z=0$$ and the field $$\mathbf{F}=y\mathbf{i}-x\mathbf{j}$$
I have no idea how to find the outer normal vector.
I have tried grad(F)/Magnitude of grad (F) but its incorrect

A: Stokes theorem is basically relating the flux through a surface with a closed path around the surface. Intuitively it says that a vector field, the total flux of the surface or flow through the closed path, must be equal to the dot product of the vector field along the path.
$\iint \nabla \times \mathbf {\vec F}\cdot \mathbf n dA = \iint \nabla \times \mathbf{\vec F}(\mathbf G(u,v))\cdot (\frac{\partial{\mathbf G}}{\partial u}\times \frac{\partial {\mathbf G}}{\partial v})dudv$
One such parameterization $\mathbf G$ is $\mathbf G(\phi, \theta)$ in spherical coordinates. $\mathbf F(\phi, \theta)=\langle 3\sin\phi \sin \theta, -3\sin\phi \cos\theta, 0 \rangle $ this comes from cartesian coordinates in terms of spherical.
$\iint \nabla \times \mathbf {\vec F}\cdot \mathbf n dA = \iint \nabla \times \langle 3\sin\phi \sin \theta, -3\sin\phi \cos\theta, 0 \rangle \cdot \langle 3\cos\phi \sin\theta, 3\sin\phi \cos\theta, -3\sin\phi \rangle \times\langle -3\sin \phi \sin\theta, 3\sin\phi \cos\theta, 0 \rangle d\phi d\theta$
It should be strait forward how to integrate this, but you do need to consider the limit's of integration to fit what was asked. You should arrive at the same conclusion when you compute the line integral along the path and further it should be a little easier.


text:
Q: How is $k[x,y]/(y^2) \to k[x,y,z]/(z^2, xz-y)$ an integral extension? Any polynomial in $k[x,y,z]/(z^2, xz-y)$ can be written as
$$c_0+c_1x+c_2y+c_3z+c_4x^2+c_5xy+c_6x^3+c_7x^2y+\cdots + dx^n+ex^{n-1}y.$$
From this, we can see that $k[x,y]/(y^2) \to k[x,y,z]/(z^2, xz-y)$ is injective.
However, I don't see how it is integral.
Which polynomial in $\frac{k[x,y]}{(y^2)}[t]$ is satisfied by $c_0+c_1x+c_2y+c_3z+c_4x^2+c_5xy+c_6x^3+c_7x^2y+\cdots + dx^n+ex^{n-1}y$?

A: Since $$(c_0+c_1x+c_2y+c_3z+c_4x^2+c_5xy+c_6x^3+c_7x^2y+\cdots + dx^n+ex^{n-1}y)-(c_0+c_1x+c_2y+c_4x^2+c_5xy+c_6x^3+c_7x^2y+\cdots + dx^n+ex^{n-1}y)=c_3z$$ and $(c_3 z)^2 \equiv 0$ in $k[x,y,z]/(z^2, xz-y)$, then the monic polynomial
$$(t-c_0+c_1x+c_2y+c_4x^2+c_5xy+c_6x^3+c_7x^2y+\cdots + dx^n+ex^{n-1}y)^2$$
in $\frac{k[x,y]}{(y^2)}[t]$ has root $c_0+c_1x+c_2y+c_3z+c_4x^2+c_5xy+c_6x^3+c_7x^2y+\cdots + dx^n+ex^{n-1}y$.


text:
Q: Create RMSLE metric in caret in r Could someone please help me with the following: I need to change my xgboost training model with caret package to an undefault metric RMSLE. By default caret and xgboost train and measure in RMSE.
Here are the lines of code:
create custom summary function in caret format
custom_summary = function(data, lev = NULL, model = NULL){
out = rmsle(data[, "obs"], data[, "pred"])
names(out) = c("rmsle")
out
}

create control object
control = trainControl(method = "cv",
                   number = 2,
                   summaryFunction = custom_summary)

create grid of tuning parameters
grid = expand.grid(nrounds = 100,
               max_depth = 6,
               eta = 0.075,
               gamma = 0,
               colsample_bytree = 0.4,
               min_child_weight = 2.25,
               subsample = 1)

cl = makeCluster(3, type="SOCK") #make clusters

registerDoSNOW(cl)  #register clusters

set.seed(1)

train my model
caret4 =  train(price_doc~. - sub_area - id,
                    data=train.train,
                    method="xgbTree",
                    trControl=control,
                    tuneGrid=grid,
                    metric="rmsle",
                    maximize = FALSE)

and I keep getting an error: { :task 1 failed - "can not find function "rmsle""

A: I also encountered the same issue in my project.
This is even after loading the Metrics package in memory using the below command.
library(Metrics)
If you see, rmsle function is being called from another function called custom_summary. It is not called directly.
So I loaded the Metrics package from within the function custom_summary and it solved the issue for me.
so here, the custom_summary function should look like:

custom_summary = function(data, lev = NULL, model = NULL) {
library(Metrics)
  out = rmsle(data[, "obs"], data[, "pred"])
  names(out) = c("rmsle")
  out
  }


text:
Q: Windows 7 sounds tab missing This "Sounds" tab is gone from my system:

I have sound on my laptop, anything I playback has sound, I can even switch theme profiles and sounds change (as evidenced by the "welcome" sound that I hear everytime I switch to a different desktop profile), but the sounds tab is gone.
I've already ran sfc /scannow and no errors were found.
What causes this?
Thanks .

A:
Found the answer here:
Run... regedit

HKCU\Software\Policies\Microsoft\Windows\Personalization\

Name: NoChangingSoundScheme
Type: REG_DWORD
Data: 0x00000000 (0)

0 = Sounds Tab
1 = No Sounds Tab

Still would like to know how this policy got changed.


text:
Q: Unable to evaluate the integral $\int \csc\left(x-\frac{\pi}{3}\right)\csc\left(x-\frac{\pi}{6}\right) dx $ The Question
$$\int \csc\left(x-\frac{\pi}{3}\right)\csc\left(x-\frac{\pi}{6}\right) dx $$
What I Tried-
 I tried dividing both numerator and denominator by $\sin \pi/6$ but couldn't get too far, what I got after dividing and doing some simplification-
$$2\int \frac{1}{\frac{\sqrt3}{2} - \sin 2x}dx \ = \int \csc\left(\frac{\pi}{6}+x\right)\sec\left(\frac{\pi}{6}-x\right)dx$$
Now I am stuck after this step and don't think there is scope for simplification. Kindly tell where I am going wrong, it may be a very stupid mistake.

A: Hint
$$\csc(x-\pi/3)\csc(x-\pi/6)$$
$$=\dfrac1{\sin(\pi/3-\pi/6)}\cdot\dfrac{\sin(x-\pi/6-(x-\pi/3))}{\sin(x-\pi/3)\sin(x-\pi/6)}$$

A: $$\csc \left(x-\frac{\pi }{3}\right)\csc \left(x-\frac{\pi }{6}\right)= \csc \left(\frac{\pi }{6}-x\right) \sec \left(x+\frac{\pi }{6}\right)=\frac{4}{\sqrt{3}-2 \sin (2x) }$$ Now, let $x=\tan^{-1}(t)$ and tou face
$$I=4\int \frac{dt}{\sqrt{3} t^2-4 t+\sqrt{3}}$$ The denominator has two simple real roots. Then partial fraction decomposition to face two simple integrals.

A: Substitute $t= \tan(x-\frac\pi4)$
$$\int \csc\left(x-\frac{\pi}{3}\right)\csc\left(x-\frac{\pi}{6}\right) dx =4\int \frac{2-\sqrt3}{t^2-(2-\sqrt3)^2}dt\\
= 4\ln | \frac{2-\sqrt3-t}{2-\sqrt3+ t} |
= 4\ln | \frac{2-\sqrt3-\tan(x-\frac\pi4)}{2-\sqrt3+ \tan(x-\frac\pi4)} |+C
$$


text:
Q: Is it safe to define a utility function for local use in my .cpp file? The code listed below is intended to calculate some rotation data which will later get used in my rendering code.
renderer.cpp:
rendered_image renderer::common_tasks(render_info const& info) {
    //info.radius is a float, info.min_image_size is an int calculated by taking the minimum
    //of info.image_width and info.image_height
    cl_float raw_delta = 2.f * info.radius / info.min_image_size;
    //cl_float4 is functionally a wrapper around float[4].
    //info.rotation is a float value representing the rotation in degrees
    cl_float4 final_deltas{
        cos(to_radians(info.rotation)) * raw_delta,
        sin(to_radians(info.rotation)) * raw_delta,
        -sin(to_radians(info.rotation)) * raw_delta,
        cos(to_radians(info.rotation)) * raw_delta
    };
    //Other, irrelevant code
    /*...*/
}

But of course, I wanted to clean up the code a bit, so I rewrote it like this:
renderer.cpp:
cl_float4 get_deltas(render_info const& info) {
    //info.radius is a float, info.min_image_size is an int calculated by taking the minimum
    //of info.image_width and info.image_height
    cl_float raw_delta = 2.f * info.radius / info.min_image_size;
    //cl_float4 is functionally a wrapper around float[4].
    //info.rotation is a float value representing the rotation in degrees
    cl_float4 final_deltas{
        cos(to_radians(info.rotation)) * raw_delta,
        sin(to_radians(info.rotation)) * raw_delta,
        -sin(to_radians(info.rotation)) * raw_delta,
        cos(to_radians(info.rotation)) * raw_delta
    };
    return final_deltas;
}

rendered_image renderer::common_tasks(render_info const& info) {
    cl_float4 final_deltas = get_deltas(info);
    //Other, irrelevant code
    /*...*/
}

Now, however, I have a globally declared function get_deltas that only exists in this .cpp file. As-is, this code compiles and runs normally, but are there any significant risks to me writing code like this? Should I be nesting the function in a namespace or declare it private in the renderer class? I know for a fact that I will never need to use get_deltas anywhere else in my code: does that change whether this is a good or bad use of this code style?

A: In addition to Steve Barnes answer:

*

*Making the function a private method is the clean OO way; I would prefer this.

*Using an anonymous namespace is the "new" C++ way; I'm using it time and again, e. g. for local internals (constants etc.) that may not leak to the outside, and are never ever thought to be used by derived classes. It's still not clean OO, though.
namespace {
    const int myMagicNumber = 0xdeadbeef;
}

*Using static is the old C way; in my projects, depending on the context, I usually move these facilities into an anonymous namespace or make them a member when I find one.

A: As a matter of principle private or local methods should always either be private members of the class or static local functions. Declaring a function as static it becomes file scope and the linker will throw an error if it is attempted to be used outside of the scope of the file that it is declared in.
You can also use the anonymous namespace to achieve the same thing which is more verbose but some places prefer.
One of the major reasons is that, while you may never intend to use get_deltas elsewhere someone else might at sometime in the life of the program, possibly as a typo, and then there is a reasonable chance that the program will compile and link without errors, (you should get a warning), but will have an obscure and hard to locate bug.

A: In general my answer would be the same as Steve Barnes' answer, with one addition:
If there is a future need to perform unit-testing on the sub-function that you have now extracted (e.g. with GTest), you will need to make that callable from the outside. This means the function prototype need to be declared in a *.h file. Furthermore, it cannot be a private function inside a class, and it cannot be inside an anonymous namespace.
The question as to whether you should be unit-testing the publicly callable function or the now-extracted utility function is best left to you, since you have the best knowledge of your project. There are general guidelines which are covered in most unit-testing textbooks.


text:
Q: jQuery validation + rails isn't firing I'm using
Rails: 5.1.4
Ruby: 2.4.1
I'm currently trying to get jQuery validation working with my rails app but I think the reason why it's not working is that when I inspect my code I'm getting an Uncaught TypeError: Cannot read property 'addMethod' of undefined error.
Now I have these gems installed:
gem 'jquery-validation-rails'
gem 'jquery-rails'
Here is my application.js file:
//= require jquery
//= require jquery_ujs
//= require jquery.validate.additional-methods
//= require jquery.validate
//= require popper
//= require bootstrap-sprockets
//= require trix
//= require rails-ujs
//= require local-time
//= require turbolinks
//= require_tree .

Here is the validation jQuery I have so far:
<script type="text/javascript">
 $(document).ready(function () {
 $("new-listing-form").validate(
 {
   rules: {
     listing_title: {
       required: true
     }
   }
 }
 );
 });
 </script>

I'm trying to test the validation on this form field:
<%= form.text_field :title, id: :listing_title, class: 'form-
 control', placeholder: 'What is the job title?' %>

What do you think is the matter with all of this?
Thank you ahead of time!

A: 1 - If you are using turbolinks then must use
$(document).on("turbolinks:load", function(){
  //the code
});

see turbolinks events
https://github.com/turbolinks/turbolinks
2- Like "new-listing-form" is not a tag
 $("new-listing-form")

never will find nothing