text:
Q: How to show shapefile on map in python? I am currently working with python and using basemap to draw Vietnam's map like this :
Vietnam's Map
My shapefile : enter image description here
I want to show all island groups or small islands by using shapefile I've had already but I have no idea to read shapefile. I've tried some code on the Internet but it did not work. I hope you guys can help me. I really appreciate. Thanks a lot.
This is my code :
import cartopy.crs as ccrs
from cartopy.feature import ShapelyFeature
from cartopy.io.shapereader import Reader
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np
plt.figure(figsize=(12,7))
m = Basemap(projection='mill',
       llcrnrlat = 7,
       urcrnrlat = 25,
       llcrnrlon = 90,
       urcrnrlon = 120,
       resolution = 'l')
m.drawcoastlines()
m.drawcountries()
m.drawstates()
m.fillcontinents(color='None',lake_color='#FFFFFF')
m.drawmapboundary(color='k', linewidth=1.0, fill_color=None, zorder=None, ax=None)
parallels = np.arange(0.,81,10.)
# labels = [left,right,top,bottom]
m.drawparallels(parallels,labels=[False,True,True,False])
meridians = np.arange(10.,351.,10.)
m.drawmeridians(meridians,labels=[True,False,False,True])

fig, ax = plt.subplots(subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([90, 120, 25, 7])
# Set map extent
In_st_shp = 'E:\koppen-master\haidao\haidao.shp'
# provide path of shapefile
state_feature = ShapelyFeature(Reader(In_st_shp).geometries(),
                               crs=ccrs.PlateCarree(), edgecolor='k')
ax.add_feature(state_feature, facecolor="none")

plt.show()

haidao.shp

A: Here is the working code using cartopy.
Please check the map extent and set the path fo shapefile in the code.
import shapefile
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.feature import ShapelyFeature
from cartopy.io.shapereader import Reader
import matplotlib.pyplot as plt
fig, ax = plt.subplots(subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([102, 111, 7, 23])
ax.coastlines(color='black', linewidth=1, resolution='50m')
ax.add_feature(cfeature.BORDERS.with_scale('50m'),
               linestyle='-', alpha=.5)
# Set map extent
In_st_shp = 'Path_to_shape.shp'
# provide path of shapefile
state_feature = ShapelyFeature(Reader(In_st_shp).geometries(),
                               crs=ccrs.PlateCarree(), edgecolor='r')
ax.add_feature(state_feature, facecolor="r")


text:
Q: regex in JavaScript to identify browser type is not returning expected value - test(navigator.userAgent) I am trying to find a way to identify the browser through JavaScript to disable a component based on the browser for a feature requirement in Volvo US project that involves AR (Augmented Reality).
Platform: Web Application
Approach Attempted:
    var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
    var isChromeBrowser = navigator.userAgent.includes("Chrome");
    var isFirefox = navigator.userAgent.includes('Firefox');

Problem Statement:
In the above approach, Safari is detecting Firefox browser as Safari browser & Safari browser as Safari.
Expected Output:
Need a solution where the method clearly returns Safari* browser alone as safari. (not for the Firefox browser or any other browsers)
Looking forward to any inputs towards a solution.
Many thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: rails/webpacker module build fail issue from ./node_modules/mini-css-extract-plugin/dist/loader.js I have upgraded @rails/webpacker from v4 to v5 (5.72.1, to be precise). While upgrading, I got following issue

ERROR in ./node_modules/croppie/croppie.css Module build failed (from
./node_modules/@rails/webpacker/node_modules/mini-css-extract-plugin/dist/loader.js):
TypeError: Cannot read property 'tap' of undefined

This is how I have setup my webpack config
const { environment } = require('@rails/webpacker');
const vue = require('./loaders/vue');
const webpack = require('webpack');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const TerserPlugin = require('terser-webpack-plugin');
const path = require('path');

const customConfig = {
  resolve: {
    fallback: {
      dgram: false,
      fs: false,
      net: false,
      tls: false,
      child_process: false,
    },
  },
  entry: {
    vendor: ['babel-polyfill', 'vue', 'moment', 'axios'],
  },
};

environment.splitChunks((config) => {
  console.log('config', environment);
  return {
    ...config,
    ...{
      optimization: {
        splitChunks: { chunks: 'all', name: '~' },
        runtimeChunk: true,
      },
    },
  };
});

environment.config.delete('node.dgram');
environment.config.delete('node.fs');
environment.config.delete('node.net');
environment.config.delete('node.tls');
environment.config.delete('node.child_process');

environment.config.merge(customConfig);

environment.plugins.append('VueLoaderPlugin', new VueLoaderPlugin());
environment.loaders.append('vue', {
  test: /\.vue$/,
  loader: 'vue-loader',
});

// Comment this if you need case-sensitive-paths-plugin in local development.
if (process.env.RAILS_ENV === 'development') {
  environment.plugins.delete('CaseSensitivePaths');

  // Only add en.js locale for local development.
  environment.plugins.append('moment', new webpack.ContextReplacementPlugin(/moment[/\\]locale/, /(en).js/));
}

environment.plugins.prepend('Environment', new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(process.env))));
environment.plugins.prepend(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    jquery: 'jquery',
  })
);

const config = environment.toWebpackConfig();

config.resolve.alias = {
  jquery: 'jquery/src/jquery',
};

let sassLoader = environment.loaders.get('sass').use.find(item => item.loader === 'sass-loader')
sassLoader = {
  ...sassLoader,
  options: {
    ...sassLoader.options,
    sassOptions: {
      ...sassLoader.options.sassOptions,
      includePaths: ["./node_modules"],
    }
  }
}

let miniCssExtractPlugin = environment.plugins.get('MiniCssExtract')
console.log('miniCssExtractPlugin', miniCssExtractPlugin)

environment.loaders.append('vue', vue);

environment.config.merge({
  optimization: {
    minimize: false,
    minimizer: [
      new TerserPlugin({
        test: /\.js(\?.*)?$/i,
      }),
    ],
  },
  resolve: {
    alias: {
      app: path.resolve(__dirname, '../../app/'),
    },
  },
});

module.exports = environment

This is the logs

If I comment import 'croppie/croppie.css' in the js file where it is used, the error goes away where croppie is a third party library.
Not sure if this issue is only while importing third party css file.


text:
Q: How can I enter multiple keywords in a row in Photos 5 (Catalina) When adding keywords to my photos in Apple's Photos app, I pull up the Info window, click in the Keywords field, and type them in. In previous versions, comma would commit the keyword but leave the cursor in the field so I could type another. So:

park,sunset,dog,

would add three keywords. Since upgrading to Catalina, comma still commits the keyword but also (usually) removes focus from the keyword field. So anything I type afterward not only doesn't go in the keyword field, but is interpreted as keyboard shortcuts and does unpredictable things.
Clearly comma is no longer the right way to do this. So how can I add multiple keywords in a row to an image or group of images?


text:
Q: How to merge grayscale and rgb image with opencv? These dont solve my questions :
refs 1, refs 2, refs 3
Input 1 (Grayscale)
Input 2 (RGB)
Output
Question :
Is it possible to achieve both output with provided inputs? If yes, how to do it in python?
ps. dont mind the ball please. Its intended


text:
Q: Is there a word for a limited term of employment for a specific project? I am looking for a word or term for the concept of being employed only for a specific project.
In my native language, we have a word that just means "project employment", it is commonly used to describe the kind of employment where one has a set period of time in the contract, and where one is only expected to work on this very specific project. The contract may even not have a set end date, but instead, stipulate "until the project is done". But it is always a limited time employment.
It is commonly used as a way in on the job market, as if the circumstances allow it, one could be hired for a permanent place after the period ends.
What would the correct English term for this kind of employment for use in my resume/curriculum vitae be?

A: I have now learned that the correct term is contract engagement, at least according to someone I know who works in the automotive industry in Europe.


text:
Q: .Net Core 2.0 Internal Server Error with Redis Cache I'm trying  to add Redis Cache support to my .Net Core 2.0 application and having issues after publishing to Azure App Services.
I've specified the connection string to my Azure Redis Cache in the appsetting.json, added the required bits to Startup.cs and tested storing and retrieving data locally successfully.
Once the application is published, it fails to start and only reports that there was a problem starting the application.
The line in the Startup.cs which seems to be causing the issue is:
services.AddDistributedRedisCache(o => { o.Configuration = redisConnection; });

The string "redisConnection" is populated just above using:
string redisConnection = Configuration.GetConnectionString("Redis");

I'm not sure why this would fail only when published.
How can I debug the cause of the failure?
EDIT:
I've managed to get as far as this error, referring to the version of Microsoft.Extensions.Caching.Redis being used.

FileLoadException: Could not load file or assembly
  'Microsoft.Extensions.Caching.Redis, Version=2.0.1.0, Culture=neutral,
  PublicKeyToken=adb9793829ddae60'. The located assembly's manifest
  definition does not match the assembly reference. (Exception from
  HRESULT: 0x80131040)
  Bootstrap_CoreApp.Startup.ConfigureServices(IServiceCollection
  services)
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
  Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection
  services)
  Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
  Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

I'm not sure why this is a problem because the referenced NuGet package in the project is set to use version 2.0.1

A: In my case I found that I added two nuget packages to the project:

*

*Microsoft.Extensions.Caching.Redis version 2.0.1

*Microsoft.Extensions.Caching.Redis.Core version 1.0.3

it worked locally, but didn't work in Azure.
then I removed Microsoft.Extensions.Caching.Redis.Core from the project, deployed project to Azure and site was started without any issues.


text:
Q: How to derive this $\dfrac{dT}{d\tau}$? I am studying the paper "Gravitational field of a particle falling in a Scharzschild geometry analyzed in tensor harmonics" by Zerilli. The author calculates the gravitational radiation emitted by a particle falling along a geodesic into a Schwarzschild black hole.
The stress energy tensor of the particle is:
$$T^{\mu\nu}=m_0 \dfrac{dT}{d\tau} \dfrac{dz^\mu}{dt} \dfrac{dz^\nu}{dt} \dfrac{1}{r^2}\delta(r-R(t)) \delta^{(2)}(\Omega-\Omega(t))$$
where the trajectory of the particle is $z^\mu=\left( T(\tau),R(\tau), \theta(\tau), \phi(\tau) \right)$.
In the appendices the author calculates the expression of the stress energy tensor of a particle falling radially into the black hole with the method of tensor harminics. For expample the 00 component is:
$$A_{lm}^{(0)} = m_0 \dfrac{dT}{d\tau} \left(1-\dfrac{2m}{r}\right)^2 \dfrac{1}{r^2} \delta(r-R(t)) Y_{lm}^*$$
In order to calculate the gravitational radiation emitted one must Fourier transform this expression: the author gives the procedure: 1) multiply by $\exp(i\omega t)dt$, the write $dR=dt/(dR/dt)$ so that the delta is simplified thanks to its properties. At the end of the calculations the author reports:
$$A_{lm}^{(0)}=\dfrac{m_0}{2\pi} \sqrt{\left(l+\dfrac{1}{2}\right) \dfrac{r}{2m}} \dfrac{1}{r^2} \exp(i\omega T(r))$$
The last two expressions give me troubles:

*

*Starting from the Fourier transform: where does the $\dfrac{dT}{d\tau}$ goes? Since it is the time component of the trajectory of the particle I thought that it could be derived by the Lagrangian as Wald does, i.e. from
$$-1=-\left( 1-\dfrac{2m}{r} \right) \dfrac{dT}{d\tau} + \left( 1- \dfrac{2m}{r} \right) \dfrac{dR}{d\tau}$$
from this I can derive the $\dfrac{dT}{d\tau}$ term, but it depends on $\dfrac{dR}{d\tau}$, whose dependence I do not know. Wald derives $\dfrac{dR}{d\tau}$ from the above Lagrangian by using the fact that (through Killing vecotrs) one has $E=\left(1-\dfrac{2m}{r} \right)\dfrac{dT}{d\tau}$, but then I need the energy $E$. From thecontour conditions of Zerilli problem the particle stars at infinity with 0 velocity, so at infinity $E=m_0c^2$, but this doesn't seem to be the way Zerilli calculated the Fourier transform, so I am lost;

*The second problem I have is with the the second equation I have reported: where does the $\left( 1-\dfrac{2m}{r} \right)^2$ term comes from?

A: Well the paper is exactly about how to obtain such a decomposition. Just reading carefully shows that
$$ T^{00}= \sum_{L M} A^{(0)}_{LM}(r,t) \text{a}_{LM}^{(0)}$$
from eq (A1). So besides the Fourier transform and resolving the delta, one must multiply with ${\rm a}$ and sum over $M$ to get the result you want. Note $M$ is not $m$, so $m$ seems to be the Schwarzschild mass, while $M$ is the index of the spherical harmonic "magnetic number" and $m_0$ the particles mass, avoid being clumsy with the notation to understand better.
Question 1:
The author explicitly says that is the case of a particle falling in starting with "zero velocity", so you do know how $R$ depends on $t$ indirectly. You can solve the geodesic equation for the particle to find its wordline explicitly.
Question 2:
For the second question you only need to follow the metric used and the factors
$$\frac{dz^0}{dt}= \frac{dT(\tau)}{dt}= \frac{d\tau}{d t}\frac{dT}{d\tau}$$
check the metric and you should get the factors $$\left(1-\frac{2m}{r}\right)$$.
You will also get one of those factors from ${\rm a}^{(0)}$, a look at Table I should help.
PD: Also the author is a bit clumsy with using $T$ for the inverse function of $R(t)$ and also for the time component of the path.

A: The equations of motion for a geodesic starting at rest at infinity are very simple, and as usual the key is to start with the constants of motion:
$$ -1 = \frac{d z^\mu}{d\tau}\frac{d z^\nu}{d\tau} g_{\mu\nu} = -\left(1-\frac{2m}{r}\right)\left(\frac{d T}{d\tau}\right)^2 + \left(1-\frac{2m}{r}\right)^{-1}\left(\frac{d R}{d\tau}\right)^2$$
and
$$ 1=\mathcal{E} = -g_{t\mu}\frac{d z^\mu}{d\tau} = \left(1-\frac{2m}{r}\right)\frac{d T}{d\tau}$$
(The specific energy $\mathcal{E}$ is one because the particle starts at rest at infinity.)
These can be solved for $\frac{d T}{d\tau}$ and $\frac{d R}{d\tau}$
\begin{align}
\frac{d T}{d\tau} &= \left(1-\frac{2m}{r}\right)^{-1}\\
\frac{d R}{d\tau} &= -\sqrt{\frac{2m}{r}}
\end{align}
These can be combined to calculate.
$$\frac{d R}{dT} = \frac{\frac{d R}{d\tau}}{\frac{d R}{d\tau}} =  -\sqrt{\frac{2m}{r}}\left(1-\frac{2m}{r}\right) $$
You now have all the ingredients you need to calculate $A_{LM}$. (Also note that you can make your life easy by placing the incoming particle on the pole. This implies that  $A_{LM}=0$ for all $M$ except 0.)


text:
Q: Defining a method with equals signs in Ruby I'm trying to create a User class that would store only hashed password
class User
  # Password should be stored only as hash in @password_hash,
  # crypted by that function:
  def self.crypt(password)
    # Returns password hash
  end

  # Crypt password and store it in @password_hash
  def password=(str)
    @password_hash = crypt(str)
  end

  # Crypt given password and compare it with stored @password_hash
  def password==(str)
    @password_hash == crypt(str)
  end
end

me = User.new
me.password = 'qwerty'

if me.password == 'qwerty'
  puts 'Ok'
else
  puts 'Error'
end

But I get a syntax error, unexpected tEQ, expecting '\n' or ';' on 14 line

A: You can't define a method called password==. Assignments are special; comparisons are not. If you really want to use User.password == "something" syntax, this is the way to do it:
class User
  attr_reader :password
  def password=(str)
    @password = Password.new(str)
  end

  class Password < String
    def encrypt(str)
      "foo" + str # TODO make stronger
    end

    def initialize(str)
      super(encrypt(str))
    end

    def ==(other)
      super(encrypt(other))
    end
  end
end

A: Try:
def == str
   @password_hash == crypt(str)
end

Also take a look at the Comparable module.


text:
Q: sqlite 3 error in logic or missing database in I think its a logic error as I can access my local database fine. My error code looks like this:

SQL logic error or missing database

 SQLiteConnection myConnection = new SQLiteConnection();
        myConnection.ConnectionString = @"Data Source= C:\Users\Lewis Elliott\Desktop\banklist.sqlite3";

        using (myConnection)
        {
            string SQL = "INSERT INTO recipes (Index, name, serves, description, information, method_1, method_2, key, cost, calories, carbs, fat, protein, sodium, sugar, type, is_populated) VALUES";
            SQL += "(@Index, @name, @serves, @description, @information, @method_1, @method_2, @key, @cost, @calories, @carbs, @fat, @protein, @sodium, @sugar, @type, @is_populated)";

            SQLiteCommand cmd = new SQLiteCommand(SQL);
            cmd.Connection = myConnection;

            cmd.Parameters.AddWithValue("@Index", Guid.NewGuid());
            cmd.Parameters.AddWithValue("@name", nameBox.Text);
            cmd.Parameters.AddWithValue("@serves", servesBox.Text);
            cmd.Parameters.AddWithValue("@description", descriptionBox.Text);
            cmd.Parameters.AddWithValue("@information", informationBox.Text);
            cmd.Parameters.AddWithValue("@method_1", method1Box.Text);
            cmd.Parameters.AddWithValue("@method_2", method2Box.Text);
            cmd.Parameters.AddWithValue("@key", keyBox.Text);
            cmd.Parameters.AddWithValue("@cost", costBox.Text);
            cmd.Parameters.AddWithValue("@calories", caloriesBox.Text);
            cmd.Parameters.AddWithValue("@carbs", carbsBox.Text);
            cmd.Parameters.AddWithValue("@fat", fatbox.Text);
            cmd.Parameters.AddWithValue("@protein", proteinBox.Text);
            cmd.Parameters.AddWithValue("@sodium", sodiumBox.Text);
            cmd.Parameters.AddWithValue("@sugar", sugarBox.Text);
            cmd.Parameters.AddWithValue("@type", typeBox.Text);
            cmd.Parameters.AddWithValue("@is_populated", isPopulatedBox.Text);

            myConnection.Open();
            cmd.ExecuteNonQuery();
            myConnection.Close();

Can anyone see any errors in this logic?


text:
Q: How Google Cloud determines which packet should route to Premium network tier/Standard tier? Google mentions that

Premium Tier delivers traffic from external systems to Google Cloud resources by using Google's low latency, highly reliable global network. This network consists of an extensive private fiber network with over 100 points of presence (PoPs) around the globe.

But how do they control the network packet that the packet should go into premium network route rather than the standard network route.
For instance, users make a request from their home internet to mywesbsite.com hosted on the Google Cloud running on Premium network tier.
mywebsite.com doesn't tell anything about the network tier. I'm just wondering what piece of information that Google uses to determine/control the route of the network packet.


text:
Q: MySQL: Coalesce doesn't work on table with unique index Similar to a previous question I have here, I have a table storing the theme, the prefix, and the suffix of user-generated maps, with the idea that no map could ever have the same name due to an identifier index.
Here's my table (other fields removed to keep it short):
CREATE TABLE IF NOT EXISTS `map_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `author_id` int(11) NOT NULL,
  `map_theme` int(11) NOT NULL,
  `map_prefix_id` int(11) NOT NULL DEFAULT '1',
  `map_suffix_id` int(11) NOT NULL DEFAULT '1',
  `map_identifier_index` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`) /*!80000 INVISIBLE */,
  UNIQUE KEY `uidx_atc` (`map_theme`,`map_prefix_id`,`map_suffix_id`,`map_identifier_index`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci

And here's a sample insert statement, based off the insert statement in the link above:
INSERT INTO map_info (author_id, author_time, map_theme, map_prefix_id, map_suffix_id, map_identifier_index) SELECT 3, 0, 1, 7, 3, COALESCE(MAX(map_identifier_index) + 1, 1) from map_info where map_theme = 1;

In theory, if a user were to insert another map with the theme of 1, prefix of 7, and suffix of 3, the map identifier to be inserted would auto-increment to 2, as a map with the same theme, prefix and suffix combo already exist. If any of those were different, the map identifier would default to 1.
In practice, however, the map identifier increments even if the prefix-suffix combo is unique, and the only thing that seems to change it up is the theme.

I'm not sure what I'm doing wrong, seeing as it's just one column more in the unique key from last time.
Could it be the insert statement?

A: You said:

INSERT INTO map_info (author_id, author_time, map_theme, map_prefix_id, map_suffix_id, map_identifier_index) SELECT 3, 0, 1, 7, 3, COALESCE(MAX(map_identifier_index) + 1, 1) from map_info where map_theme = 1;

And also:

the only thing that seems to change it up is the theme.

Your query will cause an incremented index to be generated based on the map_theme column only. To base your decision off more columns, they need adding to the where clause

with the theme of 1, prefix of 7, and suffix of 3, the map identifier to be inserted would auto-increment to 2, as a map with the same theme, prefix and suffix combo already exist

So your query would need to look for other rows that have all these columns with all these values:
INSERT INTO map_info (author_id, author_time, map_theme, map_prefix_id, map_suffix_id, map_identifier_index)
SELECT 3, 0, 1, 7, 3, COALESCE(MAX(map_identifier_index) + 1, 1) from map_info

where
  map_theme = 1 and
  map_prefix_id = 7 and
  map_suffix_id = 3

This way the index only rolls if another record with all these attributes exists


text:
Q: How do i get data from multiple apis simultanously and display them on my webpage? I am building a news/blog website which gets the data from an external api and displays it to the webpage.So far I have managed to render data from one api but I also have a sport section in my  webpage which requires me to get data from another such api but i dont know how i can do that without node throwing me an error.
Below is my NODE.JS code-
//jshint esversion: 6

const express = require('express');
const https = require('https');
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
const port = 3000;

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

app.get('/', (req, res) => {
const sporturl ="https://timesofindia.indiatimes.com/feeds/newsfeed/33187923.cms?
feedtype=sjson";
const newsurl = "https://timesofindia.indiatimes.com/feeds/newsdefaultfeeds.cms?
feedtype=sjson#";
https.get(newsurl, function(response){
    var data;
response.on("data", function(chunk) {
    if (!data) {
        data = chunk;
    } else {
        data += chunk;
    }
});

response.on("end", function() {
    const fulldata = JSON.parse(data);
            let mainHeader = fulldata.NewsItem[0].HeadLine;
            let mainheaderurl = fulldata.NewsItem[0].WebURL;
            let mainCaption = fulldata.NewsItem[0].Caption;
            let mainUrl = fulldata.NewsItem[0].Image.Photo;
            let featured = fulldata.NewsItem[1].HeadLine;
            let featuredlink = fulldata.NewsItem[1].WebURL;
            let featuredimg = fulldata.NewsItem[1].Image.Photo;

    res.render("index",{
                mainHeader: mainHeader,
                headerUrl: mainheaderurl,
                mainCaption: mainCaption,
                imgUrl: mainUrl,
                featured:featured,
                featuredlink:featuredlink,
                featuredimg:featuredimg,
            });
     });

     });

     });

     app.listen(port, () => {
     console.log(`server started on port 3000`);
     });
    // api key: ff827a803d4540f5814864d207fd23b5
    // const mainHeadingUrl = "https://newsapi.org/v2/everything?q=tesla&from=2021-
    05-26&sortBy=publishedAt&apiKey=ff827a803d4540f5814864d207fd23b5";

A: I would use the Fetch API (for nodeJS you could utilise node-fetch), async/await, and Promise.all to gather the data.
Push some API calls into an array. They will return as promises (a promise that data will (or will not) return). Promise.all waits until all those promises have resolved, and outputs the data as an array that you can then iterate over.

function mockApi(n) {
  return new Promise((res, rej) => {
    setTimeout(() => res(n), 2000);
  });
}

// Here you would bundle up your fetch calls
// eg:  fetch(url)
// I'm using mockApi as a convenience
const fetchCalls = [mockApi(1), mockApi(2), mockApi(3)];

async function getData() {
  const data = await Promise.all(fetchCalls);
  console.log(data);
}

getData();

A: This is answered here.
nodejs - How to promisify http.request? reject got called two times
You can then use the method described there and use Promise.all and achieve the desired result


text:
Q: Is there a way to merge signatures from a decorator and wrapped function? I'm looking to wrap a callable with a decorator taking an additional parameter, with the signature of the wrapped function as the union of the two.
For example
def decorator(func):
    # something like @functools.wrap
    def wrapper(other_param: int = None, **kwargs):
        pass

    return wrapper

@decorator
def myfunc(*, foo: int, bar: int):
    pass

What I would like is a way to call inspect.signature on decorated myfunc and get all three named params. I am aware of the sigtools library but cannot use it as a dependency.
Edit: To clarify, I want the signature of wrapper to be (foo, bar, other_param).


text:
Q: Intersecting dictionaries based on values I have 2 dictionaries (dict1,dict2) consisting of three keys (gene_expression, Metadata, pValues) each containing large datasets. I would like to compare and contrast those two dictionaries to create a separate dictionary with common elements where pValue was <=0.005.
If I try:
intersection=dict(dict1.items() & dict2.items())

I get
unhashable type: 'DataFrame'

Ideally I would like to actually subset the items from both dictionaries where value is <=0.005
Thanks,

A: Demonstrate that the error 'unhashable type: 'DataFrame'' appears when attempting to use a dataframe as a key. This is because dataframes are mutable and keys cannot be mutable.
dict1 = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7',
         8: '8', 9: '9'}
dict2 = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 50: '50', 60: '60', 70: '70',
         80: '80', 90: '90'}

intersection = dict(dict1.items() & dict2.items())
print(f'{intersection=}')
intersection = dict1.items() & dict2.items()
print(f'{intersection=}')

import numpy as np
import pandas as pd

data = np.random.randint(5, 30, size=10)
df = pd.DataFrame(data, columns=['random_numbers'])

print(df)
dict3 = {df: 100}


text:
Q: Как сделать словарь из списков У меня есть список с ключами и список со значениями
ключи:
k = [3, 1, 4, 2, 7, 5, 6]
 z = [
     [3, [[2, 4], [0, 6], [2, 2]]],
     [2, [[1, 4], [8, 7]]],
     [3, [[0, 3], [7, 6], [8, 3]]],
     [3, [[4, 2], [1, 1], [7, 7]]],
     [2, [[6, 4], [7, 0]]],
     [1, [[6, 6]]]]
     [1, [[4, 9]]
]

Мне нужно создать цикл, который бы делал словарь для элементов, чтобы было так:
{k[0]:z[0], k[1]:z[1]...}и тд до конца
Пыталась через цикл for, но мне он делает несколько словарей, а мне нужен один большой. Помогите пожалуйста!
Также нужно, чтоб каждое ключ-значение было на новой строчке, через width = 1 не работает.

A: In [4]:  k = [3, 1, 4, 2, 7, 5, 6]
   ...:  z = [
   ...:      [3, [[2, 4], [0, 6], [2, 2]]],
   ...:      [2, [[1, 4], [8, 7]]],
   ...:      [3, [[0, 3], [7, 6], [8, 3]]],
   ...:      [3, [[4, 2], [1, 1], [7, 7]]],
   ...:      [2, [[6, 4], [7, 0]]],
   ...:      [1, [[6, 6]]],
   ...:      [1, [[4, 9]]]
   ...: ]

In [5]: dict(zip(k,z))

A: Думаю такой код будет правильным:
k = [3, 1, 4, 2, 7, 5, 6]
z = [
     [3, [[2, 4], [0, 6], [2, 2]]],
     [2, [[1, 4], [8, 7]]],
     [3, [[0, 3], [7, 6], [8, 3]]],
     [3, [[4, 2], [1, 1], [7, 7]]],
     [2, [[6, 4], [7, 0]]],
     [1, [[6, 6]]],
     [1, [[4, 9]]]
]

result = {}

for index in range(len(k) - 1):
    result[k[index]] = z[index]

PS: Я поправил список z, потому-что он был не правильно построен. Выходила IndentationError
PSS: У меня цикл for работает, если я правильно понял ваш вопрос.


text:
Q: Isomorphism of Ideal tensored with affine open and restriction of ideals
Let $f:X \rightarrow Y = \operatorname{Spec}A$ be a morphism and $Y = \bigcup U_\alpha$ where $U_\alpha = \operatorname{Spec}A_\alpha$.
  Given the ideal $I = \{a\in A: f^*(a) = 0\}$, show that $I \otimes _A A_\alpha \cong I_\alpha$ where $I_\alpha := I|_{U_\alpha}$ = {$a \in A_\alpha : f^*(a) = 0$}

I was proving a different problem and got stuck on this. This seems fine if the covering is a covering of principal opens, but I don't see why it should hold for an arbitrary affine open cover.

A: Here is a partial answer, provided that $f$ is quasi-compact (which your comment indicates is the case in the situation you are interested in). Your ideal $I$ is the module of global sections of the kernel of $\mathcal O_Y\to f_\ast \mathcal O_X$. Let's denote this sheaf by $\mathcal I$. As $f$ is quasi-compact, this is a quasi-coherent sheaf. Then restricting the morphism $f$ to $f^{-1}U_\alpha$ corresponds to restricting $\mathcal O_Y\to f_\ast \mathcal O_X$ to $U_\alpha$, and the kernel of the restriction is the restriction of the kernel. But on affines pullback of quasi-coherent modules is given by tensoring, that is we have $\mathcal I\vert_{U_\alpha}\cong (I\otimes_A A_\alpha)^\sim$, which proves the claim.


text:
Q: how get element by class name from while loop? following code is working with ID but not working with class name, i am using this code in loop hence i can not use ID. Please suggest ... :-

function myFunction() {
  var new1 = document.getElementByClassName("bookBedNo").value;
  document.getElementById("my").value = new1;
}
<input class='bookBedNo' type='text' name='bedNo' value="BD002" readonly >

<input type="text" id="my" value="abc">

<button onclick="myFunction()">Try it</button>

A: getElementByClassName is not a function, you meant getElementsByClassName (Elements plural).
Since getElementsByClassName returns an Array-like structure, take the 0th index out to get your element.

function myFunction() {
  var new1 = document.getElementsByClassName("bookBedNo")[0].value;
  document.getElementById("my").value = new1;
}
<input class='bookBedNo' type='text' name='bedNo' value="BD002" readonly >

<input type="text" id="my" value="abc">

<button onclick="myFunction()">Try it</button>

You could also use querySelector to get just one element based of that class:

function myFunction() {
  var new1 = document.querySelector(".bookBedNo").value;
  document.querySelector("#my").value = new1;
}
<input class='bookBedNo' type='text' name='bedNo' value="BD002" readonly >

<input type="text" id="my" value="abc">

<button onclick="myFunction()">Try it</button>


text:
Q: Segmentation fault during running for mkl's interface I am running mkl_lab_solution.c which is an example for using MKL, I can compile it correctly, while I run it, I got Segmentation fault.My runtime is below:

*

*OS is centos 6.3

*gcc's version is 4.1.2

*mkl is mkl_10.3.12.361

*makefile is below
gcc -g -L/opt/intel/composer_xe_2011_sp1.12.361/mkl/lib/intel64 -lmkl_intel_ilp64 -lmkl_intel_lp64 -lmkl_intel_sp2dp  -lmkl_intel_thread -lmkl_core -lpthread  -L/opt/intel/composer_xe_2011_sp1.12.361/compiler/lib/intel64 -liomp5 -L/usr/lib64 -lstdc++ -I/opt/intel/composer_xe_2011_sp1.12.361/mkl/include -o test mkl-lab-solution.c

A: Since this works fine on my system, let me point you to possible errors.
First, you need to run . /path/to/intel/compilervars.sh intel64 such all environment variables are set, like MKLROOT.
Second, check on intel mkl link line advisor for the options on your system. So reading your compile command I guess: linux, gnu compiler, dynamic linked, 64 bit target architecture, 64 bit long pointer, multithreaded, intel omp library.
These settings give me:
linker options:
-L$(MKLROOT)/lib/intel64 -lmkl_intel_ilp64 -lmkl_intel_thread -lmkl_core -liomp5 -lpthread -lm
compile options:
-DMKL_ILP64 -m64 -I$(MKLROOT)/include
For whatever reason the brackets around MKLROOT don't work on bash, so just remove them.
Next remember to put all compile options in front of linker options. The final command line should read like this:
gcc mkl-lab-solution.c -DMKL_ILP64 -m64 -I$MKLROOT/include  -L$MKLROOT/lib/intel64 -lmkl_intel_ilp64 -lmkl_intel_thread -lmkl_core -liomp5 -lpthread -lm
Since you get runtime errors, I suspect that you are linking the Intel MKL libraries with objects compiled for different interface layers.


text:
Q: MachineKey in web.config going out of sync between two IIS applications We've got an ASP.NET 4.5 WebAPI service that is hosted on two seperate AWS instances that are behind a load balancer. Both of these machines have a standard system.web configuration section containing the machineKey element with both the decryption and validation keys and algorithms set. The web.configs on both machines are identical:
<system.web>
    ...
    <machineKey decryption="AES" decryptionKey="..." validation="SHA1" validationKey="..." />
    ...
</system.web>

These keys are used by the OAuth middleware to decrypt/validate bearer tokens in requests.
Everything has been working absolutely fine for the last two years, but in the last month, requests going to the second web box have been failing because the OAuth bearer token appears to be invalid.
If we only run one 'leg' of the web balancer at once, everything is fine, no matter which leg handles all requests. But if both are running, requests to the second box fail. This is odd as there have been no code changes, and no environmental changes we are aware of, either to the web boxes or the load balancer.
It all suggests that both machines are using different machine keys, even though they are both hard-coded in the web.config.
Is there some way that the machine key is overridden somehow? Are there any other explanations for what might be going wrong?

A: Check the system clock on both AWS instances match. I seem to recall this happening to me a few years ago.


text:
Q: How can I pass a prop to a child component, in a variable length array of children? How can I fire a callback in a child component that will then pass data to a sibling component, in a specific position of the array of component children?
I have 3 components, App, Col, and Task. The hierarchy is that the App contains any number of Column component, which each in turn contain any number of Task components. The high level goal is to move a Task from one Column, to a sibling, at the firing of a callback.
However the parent component, App, doesn't seem to have any knowledge of which Column component lives at which Index. Codepen for easy viewing
class App extends React.Component {
constructor() {
    super();
    this.state = {
    cols: [
        'a',
        'b',
        'c',
        'd',
    ]
    }
}

moveCard = (dir) => {
    console.log(dir);
    console.log(this.state);
}

render() {
    return (

        {this.state.cols.map((col, i) => <Column key={i} moveCard={this.moveCard} name={col} />)}

    );
}
}

const Task = ({text, moveCard}) => {
return (

 moveCard(e, -1)}>{'<'}

{text}

 moveCard(e, 1)}>{'>'}

);
};

class Column extends React.Component {
constructor(props) {
    super();
    this.state = {
    tasks: ['a', 'b'],
    }
}

render() {
    return (

        {this.props.name}
        {this.state.tasks.map((tasktText, id) => <Task key={id} text={tasktText} moveCard={e => {
        const updatedState = this.state.tasks;
        updatedState.splice(updatedState.indexOf(tasktText), 1);
        this.setState({
            tasks: updatedState,
        });
        this.props.moveCard(tasktText);
        }} />)}

    );
}
}

The task is removed from the column correctly, however the parent most component function moveCard has all the pertinent information, but no reference to each children, as they are simply mapped in the render call. How should I restructure my code so that for example, when the right arrow is clicked on the top task in column 1, it disappears from column one, and reappears at the bottom of column 2?

A: My approach would be to keep all the column and task information in the state of the <App /> component.
The moveCard() prop in <Column /> should hand over the relevant task info; Title, old column and new column.
The handler in <App /> then updates its state (= move task to new column) – the columns get updated.

A: Move all of the state to one place to manage. An example would be to move all data and indexes to the App component. An example is here:
https://stackblitz.com/edit/react-uz7xyq
This is using Context API to prevent prop drilling. Redux would be a good mechanism for managing this as it grows
this.state = {
  cols: [
    { name: 'A', tasks: ['A', 'B']},
    { name: 'B', tasks: ['C', 'D']},
    { name: 'C', tasks: ['E', 'F']}
  ]
};

this.state.move = (isRight, colName, taskName) => {
  const index = this.state.cols.findIndex(x => x.name === colName);
  if ((!isRight && index > 0) || (isRight && index < this.state.cols.length - 1)) {
    this.state.cols[index].tasks = this.state.cols[index].tasks.filter(x => x !== taskName);
    const index2 = isRight ? 1 : -1;
    this.state.cols[index + index2].tasks = [...this.state.cols[index + index2].tasks, taskName];
    this.setState({ cols: this.state.cols });
  }
};

(Ideally you should also not mutate state as I have done)


text:
Q: query does not delete data from the db this is my query
$db2=mysql_connect("localhost","root","");
    mysql_select_db("my_requests",$db2);

    $query=mysql_query("SELECT * FROM details INNER JOIN product ON details.user_id = product.user_id"); // find the city
    $row=mysql_fetch_array($query);// save record

        $id=$row['user_id'];
        echo "$id";

        $query1=mysql_query("DELETE * FROM details WHERE details.user_id=$id");
        $query2=mysql_query("DELETE * FROM product WHERE product.user_id=$id");

Here i have two tables products and detail ,user id is the primary key in details and made foreign key in product.
lets suppose i have two entries in the database with user_id =12 and another with user_id=11
 1. when i take the innerjoin of two tables and try to display the user_id's it shows only one user_id 12
 2. when i am trying to delete data using the user_id,it does not delete the data from the table.
sorry for the bad english

A: The proper syntax of a DELETE query does not include *
DELETE FROM product WHERE product.user_id=$id
//^^^^^^^^^

If you do some basic error checking and debugging, the API will report a syntax error.
// This query has a syntax error and will return FALSE...
$query1 = mysql_query("DELETE * FROM details WHERE details.user_id=$id");
if (!$query1) {
  // On failure, see what your error was.
  echo mysql_error();
}

The above will report an error similar to:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM

A: In your SELECT query, you have to specify tha table to get the * like details.* or products.*, becasue you're joinning two tables. In your case, it's the same result.
You also need to place $row=mysql_fetch_array($query); in a loop, to fetch each rows, then, you have a bad DELETE syntax  :
while($row=mysql_fetch_array($query)) {
    $id=$row['user_id'];
    echo "$id";

    $query1=mysql_query("DELETE FROM details WHERE details.user_id=$id");
    $query2=mysql_query("DELETE FROM product WHERE product.user_id=$id");

}


text:
Q: Append textbox at certain string length I have an Access form which inserts an input field after the previous textbox reaches 8 digits.
This is how it looks before the user types something with 8 digits
When the textbox reaches the string limiter, it creates another input with the same properties and so on
How may I create the same item with JavaScript?
When the textbox get's it's full length limit, I need to append another input and make JavaScript press "tab" to skip to the next element
This is what I've been trying so far.
HTML
<input type="text" id="opNum_1"  onInput="checkLength(8,this)" onfocus="add_numOp(code);return false;" >

JAVASCRIPT
var counter = 1;
 function checkLength(len,ele){
  var fieldLength = ele.value.length;

  if(fieldLength <= len)
  {

  }
  else
  {
    $(this).keydown();
  }
}

function add_numOp(codigo){

$('#new_Ops_'+codigo+'').append(

        '
'+
        '
'+
            '<input type="text" id="opNum_'+codigo+'_'+counter+'" onblur="add_numOp('+myCode+')" style=" margin-left: 28px; "><button type="button"  id="addOp" class="btn btn-rounded btn-default btn-icon" onclick="javascript:remove_op(opRol_'+codigo+'_'+counter+')" ></button>'+
        '
'
    );
 counter++;

}

A: By targeting our elements and keeping track of their state programmatically,  we can reuse the handler on any number of input elements.

const form = document.querySelector('#our-form');
addListener(); // For our initial input event

function addListener() {
  getLastChild().addEventListener('keypress', handler);
}

const appendNewField = () => {
  const newField = form.appendChild(document.createElement('input'));
  newField.setAttribute('maxlength', '8');
  return newField;
}

function getLastChild() {
  return form.children[form.children.length - 1];
}

function handler(e) {
  // Ignore tab, backspace, etc https://regex101.com/r/gOSyKu/1
  if (e.target.value.length >= 7 && e.key.match(/^[0-9a-zA-Z]$/)) {
    // If we are also the last child, append a new sibling
    if (e.target === getLastChild()) {
      const newInput = appendNewField();
      addListener();
    }
    getLastChild().focus();
  }
}
<form id="our-form">
  <input type="text" maxlength="8">
</form>

A: from what i can understand, i simply coded the solution using a global count variable for better accessing of inputs and call focus() for the tab functionality.
var count=2;
function checkLength(e){
  if(e.value.length>=8){
    $('#'+e.closest("div").id).append("<input type='text' id='opNum_"+count+"' onInput='checkLength(this)' maxlength='8'>");
    $('#opNum_'+count).focus();
    count++;
  }
}

demo: http://jsbin.com/todadivivu/edit?html,js,output


text:
Q: Add channel to category by name     var server = message.guild;
    for (var i = 0; i < server.channels.array().length; i++) {
        server.channels.array()[i].delete();
    }

    server.createChannel("Text Channels", "category");
    server.createChannel('general', "text");

I am trying to make the text channel 'general` go into the category 'Text Channels'
All the solutions I have found rely on you knowing the categories id. I was wondering if there is a way I could get the category id, or else move general into "Text Channels" simply by its name.
NOTE:: Currently I am thinking of something along these lines to get the category id:
var categoryID = server.categories.find("name","Text Channels");

Then to use
server.channels.find("name","general").setParent(categoryID);

A: You can use GuildChannel.setParent(). Please keep in mind that categories are considered as channels by Discord: CategoryChannel extends GuildChannel, so you can check the type with GuildChannel.type
To assign an existing channel:
let category = server.channels.find(c => c.name == "Text Channels" && c.type == "category"),
  channel = server.channels.find(c => c.name == "general" && c.type == "text");

if (category && channel) channel.setParent(category.id);
else console.error(`One of the channels is missing:\nCategory: ${!!category}\nChannel: ${!!channel}`);

To create a new channel:
server.createChannel("general", "text")
  .then(channel => {
    let category = server.channels.find(c => c.name == "Text Channels" && c.type == "category");

    if (!category) throw new Error("Category channel does not exist");
    channel.setParent(category.id);
  }).catch(console.error);

Edit: discord.js@v12
The only thing that changes is that you have to use the GuildChannelManager for everything.
let category = server.channels.cache.find(c => c.name == "Text Channels" && c.type == "category"),
  channel = server.channels.cache.find(c => c.name == "general" && c.type == "text");

if (category && channel) channel.setParent(category.id);
else console.error(`One of the channels is missing:\nCategory: ${!!category}\nChannel: ${!!channel}`);

server.channels.create("general")
  .then(channel => {
    let category = server.channels.cache.find(c => c.name == "Text Channels" && c.type == "category");

    if (!category) throw new Error("Category channel does not exist");
    channel.setParent(category.id);
  }).catch(console.error);

A: I know it's too late, but here's the way to get the channel_id :

*

*right click on the channel to open the menu

*click on Copy id (in the bottom of the menu)


text:
Q: How to create a loop to extract rows based on condition from character string Looking to extract rows from a large data frame based on whether the row contains any of the datetime stamps listed in a character string and add them to a new data frame.
Example data frame and character string of datetime stamps.
df <- data.frame(
    Date = c("2017/05/10 15:00", "2017/05/10 22:00", "2017/05/25 10:00", "2017/05/25 20:00"),
    value = c(15, 10, 25, 7)
)
df$Date <- as.POSIXlt(df$Date, tz ="GMT", origin = '1970-01-01')

dtlist <- c("2017/05/10 22:00", "2017/05/25 20:00") # desired datetimes

Looking for output like this:
Date                 Value
2017/05/10 22:00      10
2017/05/25 20:00      7

First thought was to use which() to identify the rows but don't know how to incorporate the condition of reading the variables from dtlist.
e.g. which(df$value == dtlist(i)) where i is nth object in the list


text:
Q: How to stop IntentService Android I have build an IntentService in Android.
So if I received a pushNotification message, I muse stopped this service.
public class DosimeterDataSensingService extends IntentService {
    private static final String TAG = "DosimeterDataSensingService";
    public static boolean isStarted = false;
    private Context mContext;
    private int mStatus;
    private BluetoothDevice mDevice;
    private BluetoothGatt mConnGatt;
    private boolean notificationsEnabled;
    private long dosimeterScanningTime;
    private boolean isThreadStarted = false;
    private List<DosimeterDataRequest.DataBean> dosimeterDataList;
    private List<DosimeterDataRequest.DataBean> dosimeterDataListMqtt;
    private DosimeterMqttParcel dosimeterMqttParcel = new DosimeterMqttParcel();
    private DosimeterDataRequest dosimeterDataRequest;
    private String macAddress;
    private boolean isRecordingEnabled = false;
    private String dose = "";
    private int battery = -1;
    private Boolean syncRadiactionWS = false;
    private Boolean syncRadiactionMQTT = false;
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public DosimeterDataSensingService(String name) {
        super(name);
    }

    public DosimeterDataSensingService() {
        super(null);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.d("dosimetro", "ON HANDLE INTENT");
        if(intent!=null){
            String action = intent.getStringExtra(PreferenceHandler.ACTION_STOP);

            Log.d("dosimetro", action!=null ? action : "no action");
            if(action!=null && action.equals(PreferenceHandler.ACTION_STOP)){
                Log.d("dosimetro", "fermo il servizio");
                String syncScanTime = PreferenceHandler.readString(getApplicationContext(), PreferenceHandler.DOSIMETER_SCANNING_TIME, null);
                Log.d("dosimetro", syncScanTime!=null ? syncScanTime : "nullo");
                String syncRotTime = PreferenceHandler.readString(getApplicationContext(), PreferenceHandler.DOSIMETER_ROTATION_TIME, null);
                Log.d("dosimetro", syncRotTime!=null ? syncRotTime : "nullo");
                super.stopSelf();
                Log.d("dosimetro", "ho stoppato");
                onDestroy();
                return;
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Paper.init(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = createNotificationChannel();
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
                .setSmallIcon(R.drawable.logoxhdpi)
                .setCategory(Notification.CATEGORY_SERVICE)
                .setContentTitle("Cardio App")
                .setContentText("Getting data from Dosimeter")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        Notification notification = mBuilder.build();
        startForeground((int) (System.currentTimeMillis() + 1), notification);
        isStarted = true;

        if (PreferenceHandler.readString(this, PreferenceHandler.TYPE_USER, null).equals("2")) {
            checkDosage();
        }
        List<GetAssignedDevicesListResponse.Parameters> preferenzeParametri= Paper.book().read(PreferenceHandler.PARAMETRI_VITALI, new ArrayList<>());
        if(preferenzeParametri!=null && preferenzeParametri.size()>0){
            for (GetAssignedDevicesListResponse.Parameters p: preferenzeParametri) {
                if(p.getIdParameter() == PreferenceHandler.ID_RADIACTION){
                    //VERIFICO COME L'RR DEVE ESSERE SINCRONIZZATO
                    syncRadiactionWS = p.getSyncWs()!=null ? p.getSyncWs() : false;
                    syncRadiactionMQTT =  p.getSyncMqtt()!=null ? p.getSyncMqtt() : false;
                    Log.e("DOSIMETER", "syncRadiactionWS true");
                }
            }
        }else{
            Log.e("DOSIMETER", "paperi init false");
        }

        checkBattery();
        Log.i("SCANNINGTIME", "SYNC WS STARTED");
        syncRadiactionLevel();
        syncMqtt();
    }

    @Override
    public void onDestroy() {
        Log.d("DOSIMETRO", "ondestroy");
        isStarted = false;
        disconnectDosimeter();
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        return START_STICKY;
    }

    @SuppressLint("LongLogTag")
    public void disconnectDosimeter() {

        if (mConnGatt != null) {
            isThreadStarted = false;
            if ((mStatus != BluetoothProfile.STATE_DISCONNECTING)
                    && (mStatus != BluetoothProfile.STATE_DISCONNECTED)) {
                mConnGatt.disconnect();
                mConnGatt.close();
                mConnGatt = null;
                mStatus = BluetoothProfile.STATE_DISCONNECTED;
            }
        }
        try {
            Method m = mDevice.getClass().getMethod("removeBond", (Class[]) null);
            m.invoke(mDevice, (Object[]) null);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

        Log.v("Dosimeter", "isRecordingEnabled" + isRecordingEnabled);
        Log.v("Dosimeter", "Disconnecteddd");
    }

    /**
     * Enable recording of values
     */
    private void startRecordingData() {
        String dosimeterRotation = PreferenceHandler.readString(getApplicationContext(), PreferenceHandler.DOSIMETER_ROTATION_TIME, null);
        Log.i("ROTATIONTIME", dosimeterRotation);
        long dosimeterRotationTime = 0L;
        if (dosimeterRotation != null) {
            dosimeterRotationTime = Long.parseLong(dosimeterRotation);
            new Handler().postDelayed(() -> {
                isRecordingEnabled = true;
                isThreadStarted = false;
            }, dosimeterRotationTime);
        }
    }

}

To stop the service I m using this code:
Intent i = new Intent(this, DosimeterDataSensingService.class);
i.putExtra(PreferenceHandler.ACTION_STOP,PreferenceHandler.ACTION_STOP);
stopService(new Intent(this, DosimeterDataSensingService.class));

From my log I can see that the system call
super.stopSelf();
onDestroy();

method but the IntentService works always.

A: You need not call stopSelf() or stopService() for IntentService.
As per the description mentioned in Docs:
Because most of the started services don't need to handle multiple requests simultaneously (which can actually be a dangerous multi-threading scenario), it's best that you implement your service using the IntentService class.
The IntentService class does the following:
It creates a default worker thread that executes all of the intents that are delivered to onStartCommand(), separate from your application's main thread.

Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading.

Stops the service after all of the start requests are handled, **so you never have to call stopSelf().**

Provides a default implementation of onBind() that returns null.

Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent() implementation.

If the service is still running may be some intents are running.
Hope this helps.


text:
Q: Help needed for the given question Given that m,n are natural numbers, when can $3^m + 3^n +1$ be a perfect square?
This question was asked in today's exam. I am stuck. Can anyone help?

A: Without loss of generality assume $m>n$ and let the perfect square be $(a+1)^2$. Then $$a(a+2)=3^n(3^{m-n}+1)$$ You can now look at the possibilities for the factor of $3^n$.


text:
Q: Run code if screen has certain width I'm just trying to write a message in the console when the size of the window is less than 700 px.
The things I have tried is:
if(window.innerWidth < 700){
console.log("hello");
}

And
if(screen.width < 700){
console.log("hello");
}

I don't get any error meassages but the code doesn't run. If I ad "px" after the 700 I get the error meassage "Uncaught SyntaxError: Unexpected identifier".

A: You need to put this inside the window's resize event listener. And also you need to use window.innerWidth and it always returns an integer value.

if (window.attachEvent) {
  window.attachEvent('onresize', function() {
    if (window.innerWidth < 760)
      console.log("Less than 760");
    else
      console.log("More than 760");
  });
} else if (window.addEventListener) {
  window.addEventListener('resize', function() {
    if (window.innerWidth < 760)
      console.log("Less than 760");
    else
      console.log("More than 760");
  }, true);
} else {
  //The browser does not support Javascript event binding
}

A: You need to listen for 'resize' event on 'window':
window.addEventListener('resize', resize);

function resize() {

    if (window.innerWidth < 700) {

        console.log('window.innerWidth < 700');
        // window.removeEventListener('resize', resize); // once
    }
}

more information about .addEventListener: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

A: onResize();
window.addEventListener('resize', onResize);

function onResize(){
    var width = document.documentElement.clientWidth;
}


text:
Q: How to avoid repetion with my code I've written a code that extracts all the words from two files, and only returns the words that are in both of the file.
However, i have done some repetition and that is not considered a good style, so i wondering if it would be possible to avoid this with my code?
import re

def print_common_words(filename_1, filename_2):

    try:

        input_file = open(filename_1, 'r')
        source_string = input_file.read().lower()
        input_file.close()
        all_words1 = set(re.findall('[a-zA-Z]+', source_string))

        input_file = open(filename_2, 'r')                         #Repetition
        source_string = input_file.read().lower()                  #Repetition
        input_file.close()                                         #Repetition
        all_words2 = set(re.findall('[a-zA-Z]+', source_string))   #Repetition

        intersection_list = all_words1.intersection(all_words2)
        union_list = []
        for word in intersection_list:
            union_list += [word]
            union_list.sort()
        for i in union_list:
            print(i)

    except FileNotFoundError:
        print("A file could not be found.")

A: Use a method to factor out the duplicated code.
def get_file(file):
    input_file = open(file, 'r')
    source_string = input_file.read().lower()
    input_file.close()
    return set(re.findall('[a-zA-Z]+', source_string))

Call it like:
all_words1 = get_file(filename_1)
all_words2 = get_file(filename_2)

Eg:
all_words1 = get_file(filename_1)
all_words2 = get_file(filename_2)
intersection_list = all_words1.intersection(all_words2)
union_list = []
for word in intersection_list:
    union_list += [word]
    union_list.sort()
for i in union_list:
    print(i)


text:
Q: Get numeric value from boolean I prefer casting boolean value to integer, but I found using conditional operator ?: like in example:
boolVal ? 1 : 0;

I think it looks ridiculous. What is most efficient way to get numeric value from boolean value in .NET?

A: You could use Convert.ToInt32
int zeroOrOne = Convert.ToInt32(boolVal);

Use the most readable approach, performance will be the same.
This is the source code of Convert.ToInt32:
public static int ToInt32(bool value) {
    return value? Boolean.True: Boolean.False;
}

A: I ran a quick test and comparing the conditional operator and Convert.ToInt32:
bool bVal = true;
Stopwatch sw = new Stopwatch();

sw.Start();
for(int i =0; i < amountOfTries; i++ )
{
    int b = bVal ? 1 : 0;
}
sw.Stop();
Console.WriteLine( $"Conditional operator: {sw.ElapsedTicks}t" );

sw.Restart();
for( int i = 0; i < amountOfTries; i++ )
{
    int b = Convert.ToInt32(bVal);
}
sw.Stop();
Console.WriteLine( $"Convert: {sw.ElapsedTicks}t" );

Result with 1000000 (1 million) tries:
Conditional operator: 7518 ticks
Convert: 8744 ticks
So the conditional operator is slightly faster in this case (its such a small difference the result can be different too). I think the Convert looks clearer personally though.
Note:  As you can see in Tim Schmelter's answer, under the hood Convert.ToInt32(bool) does practically the same as the conditional operator.


text:
Q: Is there a way to save a google spreadsheet as a blob in a database and then, during apps script, open that blob as a spreadsheet I have a very complex Google spreadsheet that I am using as a template to create another spreadsheet. The sheets have formatting, named ranges, data validation, formulas, data, permissions, etc. The code will select certain sheets within the template spreadsheet and copy them to the new spreadsheet.
Example of code that does this:
var s = "complexity";
var srcsheet = ss_src.getSheetByName(s);
var newsheet = srcsheet.copyTo(ss).setName(s).hideSheet();
rebuildNamedRange(ss,newsheet);
var rule = ss_src.getSheetByName(s).getRange("C2").getDataValidation();
newsheet.getRange("C2:C99").clearDataValidations();
newsheet.getRange("C2:C99").setDataValidation(rule);
copySheetProtections(srcsheet,newsheet);

The issue is that the "copyTo" functions require that the user has edit privileges to the spreadsheet.  Obviously that is not ideal.
Is there a way to save a google spreadsheet as a blob in a database and then, during apps script, open that blob as a spreadsheet?
I've tried the following to no avail.
Test#1
function getBlob() {
  var doc = SpreadsheetApp.openById(SRC);
  var docContentBlob = doc.getBlob();
  copyBlobSheet(docContentBlob);
}
function copyBlobSheet(blob) {
  var dst = SpreadsheetApp.openById(DST);
  blob.setContentType('application/vnd.google-apps.spreadsheet'); // tried with and without this
  var newDocfromBlob = DriveApp.createFile(blob).setName("doc from blob");
  var src = SpreadsheetApp.open(newDocfromBlob); // this fails
  src.getSheetByName("one").copyTo(dst).setName("copy of one success");
}

Test#2
function getBlob() {
  var doc = SpreadsheetApp.openById(SRC);
  var docContentBlob = doc.getBlob();
  copyBlobSheet(docContentBlob);
}
function copyBlobSheet(blob) {
  var dst = SpreadsheetApp.openById(DST);
  blob.setContentType('application/vnd.google-apps.spreadsheet'); // tried with and without this
  var file = {
    title: 'advanced_test',
    mimeType: 'application/vnd.google-apps.spreadsheet'
  };
  newFile = Drive.Files.insert(file, blob); // this fails with "invalid mime type"
}

Any thoughts on this capability or a work-around would be greatly appreciated!

A: A work around answer:
View access should be enough for them to copy the template. Once they have their own copy of the master template they run your script from inside it to make another sheet with the correct subset of properties.

A: Not sure if you still have this issue.
If I was you, I would use the GDrive API to copy/download the spreadsheet. If you copy then you can give the spreadsheet shared link to the user or download a copy for the user.


text:
Q: How to distribute code to be executed by an external command? Bash script? EDIT: Based on discussions below, I think my question really could apply to any language. Python naturally has a packaging system and installation procedure via pip. But let's say this was C code or a perl script. Users would still download the program files, and have a way to execute the code in the command line via capsall input.txt.
I have a python script that takes an input file and gives an output file.
For a concrete example, this script file1.py takes in an input text file and outputs a text file with all letters capitalized:
import sys
inFile = sys.argv[1]
outFile = sys.argv[2]

with open(inFile,'r') as input_file:
    lines = input_file.readlines()

# process the input file somehow
# here we simply capitalize the text,
# but naturally something more complex is possible

capitalized_lines = []
for line in lines:
    capitalized_lines.append(line.upper())

with open(outFile,'w') as output_file:
    for line in capitalized_lines:
        output_file.write(line)

The way users execute this code now with
python file1.py input.txt output.txt

Let's say I wanted to distribute this code such that users would download a tarball and be able to execute the above in the command line with (for example)
capsall input.txt

which would run python file1.py and output the file output.txt. Does one write a bash script? If so, how do you distribute the code such that users will have this in their PATH?

A: Add a "hash bang" at the top of the script file to tell bash to invoke the Python interpreter. Also make your script executable:
#!/usr/bin/env python
import sys

inFile = sys.argv[1]
outFile = sys.argv[2]
...

Make the script file executable:
$ cp file1.py capsall
$ chmod +x capsall

Now you can run the script with:
$ ./capsall input.txt output.txt

Or if capsall is on your path:
$ capsall input.txt output.txt

A: I would recommend using python packaging (e.g., [pip]) for this.  You could use the OS specific packaging method as well, something like apt, yum, msiexec, whatever, but I wouldn't unless you have to.  Your users already have python installed since they are used to explicitly passing your script to the interpreter already.  If you are interested in using python packaging, then read on.
First, I would put your script into a package along with whatever other processing is necessary.  Let's call it mylibrary.  Your project should look something like:
myproject
 |-- README.rst
 `-- myproject
  |-- __init__.py
  `-- capsall.py

Keep __init__.py simple and make sure that you can import it without dependencies.  I use something like:
version_info = (0, 0, 0)
version = '.'.join(str(v) for v in version_info)

Next, add a file named setup.py at the root.  This is what will define your package, it's metadata, and the scripts to install into your user's $PATH.  The following will work nicely:
#!/usr/bin/env python
import setuptools
import myproject

setuptools.setup(
    name='myproject',
    version=myproject.version,
    description='Package of useful utilities.',
    long_description=open('README.rst').read(),
    url='https://github.com/me/myproject',
    author='Me',
    author_email='me@example.com',
    packages=['myproject'],
    entry_points={
        'console_scripts': ['capsall=myproject.capsall:main'],
    },
    license='BSD',
)

If you plan on uploading to pypi.python.org, then you will need at least that much metadata. I would recommend adding classifiers as well.  The Python Packaging Authority docs on writing a setup.py are invaluable.
The part that you are most interested in is the entry_points keyword parameter.  It defines various ways that your package can be invoked.  You are looking for console_scripts since it creates shell scripts that are installed into the local path.  See the setuptools documentation for more details.
The console_scripts definition that I gave above creates a script named capsall that invokes the my project.capsall.main function.  I would repackage your code into a project.  Bundle your script into the main function of the capsall.py module.  Then generate a source repository and upload it to pypi.python.org (./setup.py sdist register upload).  Once you have it uploaded, your users can install it using pip install myproject.
Chances are that you have code that you don't want to give to the outside world.  If that is the case, then you can generate a source distribution and make the tarball available on an internal server -- ./setup.py sdist will generate a tarball in the dist directory.  Then pip install whatever/myproject-0.0.0.tar.gz will install your script.


text:
Q: download direct file I want to download a file directly from a url (for example: http://iranfairco.com/icon/Iranfairco.png)
and save this file on our server.
How do I do this?

A: You can use WebClient.DownloadFile(url,local) e.g.
WebClient webClient = new WebClient();
webClient.DownloadFile("http://iranfairco.com/icon/Iranfairco.png",@"c:\mypng.png");


text:
Q: Replacing all rows in a data frame starting with specific character with values stored in vector I have a data frame (df) which looks like this:
df

    df$column1
>hg19_chr1:55343-67868
ATATGAGCGT
>hg19_chr6:343114-831443
GGGGCCGCGTGCTG
>hg19_chr15:76644-90990
TTTCATCAT

Then I have a vector (vec) with 3 character
"SRSF4", "MAX", "BIM"
I would like to replace all the rows of the data frame which starts with the character ">" with the name stored in the vector:
Output:
df

    df$column1
SRSF4
ATATGAGCGT
MAX
GGGGCCGCGTGCTG
BIM
TTTCATCAT

I wrote something like this but it does not seem to work:
data <- data.frame(lapply(df, function(x) {gsub(">.$ ", vec, x)}))

Any help highly appreciated, thanks!

A: We can create a logical vector and then do the replacement
i1 <- grep("^[>]", df$column1)
df$column1[i1] <- paste0(">", vec)

NOTE: Here, we are assuming that the length of the 'vec' and the number of rows that have > as starting character to be the same


text:
Q: Python in visual studio code Every time I use input function vsc stops to respond and just doesn't work
It just loads for a long time and then the notification pops out telling me that it took to long to compile and I have to restart program
I tried searching about this problem on Google but I found nothing
On youtube video I saw that the person using vsc could use input normally


text:
Q: Forward-only one-pass stateful IEnumerable to IEnumerable> with no interim storage? I want to take streamed IEnumerable values such as: (Tuples shown for illustration purposes. The actual application will be streaming DataRecords from a DataReader)
var tuples = new(int, int)[]
{
    (0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2),
};

I want to maintain state and watch for each change in the left field. Each group of items with the left field in common should be returned as a series of IEnumerables (the data will be pre-sorted so I don't have to worry about collating on the local end).
(0,0) (0,1) (0,2) (0,3)
(1,0) (1,1)
(2,0) (2,1) (2,2)

It may not be possible, but the hope is to do this without creating any per-group interim Lists that would bank records in RAM because each group will be fairly large. In other words, somehow get each group to somehow magically siphon from the original IEnumerable such that it is completely forward-only, one-pass.
An inner-TakeWhile seemed like it might be the way to go, but it always restarts the iteration on tg from ground zero.
            private int currentGroup;

            public IEnumerator<IEnumerable<Tuple<int, int>>> GetEnumerator()
            {
                var tg = TupleGenerator();
                foreach (Tuple<int, int> item in tg)
                {
                    currentGroup = item.Item1;
                    yield return tg.TakeWhile((x) => x.Item1 == currentGroup);
                }
            }

            static IEnumerable<Tuple<int, int>> TupleGenerator()
            {
                for (int i = 0; i < 10; i++)
                {
                    for (int j = 0; j < 10; j++)
                    {
                        yield return new Tuple<int, int>(i,j);
                    }
                }
            }

A: So while it is possible to avoid storing an entire groups worth of data in memory, and to only ever stream each item as you request it with only a constant amount of memory, there are downsides.  It's important to realize why buffering is the typical solution to problems like this.  First, the code to avoid buffering is just more complex.  Second, it's essential that the consumer always iterate every inner IEnumerable to completion before ever requesting the next group, and that no inner IEnumerable ever be start being iterated more than one time.  If you violate any of those rules (if you don't check for them explicitly) things will just silently be wrong.  (You'll end up with data that should be in the same group in multiple groups, have the wrong number of groups, etc.)  Given how easy those mistakes are to make, and the consequences of messing up, it's really worth explicitly checking for them and throwing an exception, so the consumer at least knows it's wrong and needs to be fixed.
As for the actual code, you really need to do a lot manually, to have direct control over the enumerator and when exactly you get items, but at it's core the code mostly just boils down to keeping track of the previous item and continuing to  yield items into the same group as long as the current item "matches" with it.
public static IEnumerable<IEnumerable<T>> GroupWhile<T>(
    this IEnumerable<T> source,
    Func<T, T, bool> predicate)
{
    using (var iterator = source.GetEnumerator())
    {
        bool previousGroupFinished = true;
        bool sourceExhaused = !iterator.MoveNext();
        while (!sourceExhaused)
        {
            if (!previousGroupFinished)
                throw new InvalidOperationException("It is not valid to request the next group until the previous group has run to completion");
            previousGroupFinished = false;
            bool startedIteratingCurrentGroup = false;

            yield return NextGroup();

            IEnumerable<T> NextGroup()
            {
                if (startedIteratingCurrentGroup)
                    throw new InvalidOperationException("This sequence doesn't support being iterated multiple times.");
                startedIteratingCurrentGroup = true;

                T previous;
                do
                {
                    yield return iterator.Current;
                    previous = iterator.Current;
                    sourceExhaused = !iterator.MoveNext();
                }
                while (!sourceExhaused && predicate(previous, iterator.Current));
                previousGroupFinished = true;
            }
        }
    }
}

To use it in your case, it's pretty simple, your items are grouped while the first item in the pair is equal, but you can use any arbitrary condition that you want for grouping.
var data = new[] { (0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2) };
var grouped = data.GroupWhile((previous, current) => previous.Item1 == current.Item1);
foreach (var group in grouped)
{
    Console.WriteLine(String.Join(", ", group));
}

Rather than grouping on a predicate, it's also often convenient to group on some key object.  In your case for your example, the key is just the first item in the tuple.  But if computing the key is expensive or otherwise can't be computed multiple times, you can alter the grouping mechanism to have a key selector instead of a predicate, and to store the previous key rather than the previous item.  It results in code that's fairly similar, but subtly different:
public static IEnumerable<IEnumerable<TSource>> GroupAdjacent<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    IEqualityComparer<TKey> keyComparer = null)
{
    keyComparer = keyComparer ?? EqualityComparer<TKey>.Default;

    using (var iterator = source.GetEnumerator())
    {
        bool previousGroupFinished = true;
        bool sourceExhaused = !iterator.MoveNext();
        TKey nextKey = keySelector(iterator.Current);
        while (!sourceExhaused)
        {
            if (!previousGroupFinished)
                throw new InvalidOperationException("It is not valid to request the next group until the previous group has run to completion");
            previousGroupFinished = false;
            bool startedIteratingCurrentGroup = false;

            yield return NextGroup();

            IEnumerable<TSource> NextGroup()
            {
                if (startedIteratingCurrentGroup)
                    throw new InvalidOperationException("This sequence doesn't support being iterated multiple times.");
                startedIteratingCurrentGroup = true;

                TKey previousKey;
                do
                {
                    yield return iterator.Current;
                    sourceExhaused = !iterator.MoveNext();
                    previousKey = nextKey;
                    if (!sourceExhaused)
                        nextKey = keySelector(iterator.Current);
                }
                while (!sourceExhaused && keyComparer.Equals(previousKey, nextKey));
                previousGroupFinished = true;
            }
        }
    }
}

Allowing you to write:
var data = new[] { (0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2) };
var grouped = data.GroupAdjacent(pair => pair.Item1);
foreach (var group in grouped)
{
    Console.WriteLine(String.Join(", ", group));
}

A: Using MoreLinq's GroupAdjacent method:

Groups the adjacent elements of a sequence according to a specified key selector function.

var groupings = GetValues().GroupAdjacent(tuple => tuple.Item1);

foreach (var grouping in groupings)
{
    Console.WriteLine($"Value: {grouping.Key}. Elements: {string.Join(", ", grouping)}");
}

IEnumerable<(int, int)> GetValues()
{
    yield return (0, 0);
    yield return (0, 1);
    yield return (0, 2);
    yield return (0, 3);
    yield return (1, 0);
    yield return (1, 1);
    yield return (2, 0);
    yield return (2, 1);
    yield return (2, 2);
};

This outputs the following:

Value: 0. Elements: (0, 0), (0, 1), (0, 2), (0, 3)
Value: 1. Elements: (1, 0), (1, 1)
Value: 2. Elements: (2, 0), (2, 1), (2, 2)

Each instance on the groupings enumerable is an IGrouping<int, (int, int)> which when enumerated results in what you need.
(P.S: the iterator is only hit once with this implementation, so it is completely forward-only)


text:
Q: Angular 2 routing/navigation I have angular 2 ts app, where routs defined as:
@RouteConfig([
        { path: '/accounts', name: 'Accounts', component: AccountComponent, useAsDefault: true},
        { path: '/transactions', name: 'Transactions', component: TransactionComponent}
])

When i enter into browser: http://localhost/ the url updates with http://localhost/accounts and works as expected, however if I enter http://localhost/accounts it become http://localhost/accounts/accounts and fail.
What is wrong?
The backend -ASP.NET 5 which is refer to index.html for all unknown paths
   app.Use(async (context, next) =>
        {
            await next();

            if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
            {
                context.Request.Path = "/index.html";
                await next();
            }
        });

the startup section:
   public void Configure(IApplicationBuilder app)
    {
        app.UseIISPlatformHandler();

        app.Use(async (context, next) =>
        {
            await next();

            if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
            {
                context.Request.Path = "/index.html";
                await next();
            }
        });

        app.UseDefaultFiles();
        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute("spa-fallback", "{*anything}", new {controller = "Home", action = "Index"});
        });

    }

A: Updated
I just noticed the useAsDefault option in your angular router config (I haven't used angular 2 previously). I'm guessing that is automagically add the /accounts to your URL. Try this config
public void Configure(IApplicationBuilder app)
{
    app.UseIISPlatformHandler();

    app.Use(async (context, next) =>
    {
        await next();

        if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
        {
            ctx.Response.Redirect("/");
            return;
        }
    });

    app.UseDefaultFiles();
    app.UseStaticFiles();

}

What's happening is when you enter the route directly in the browser it is getting caught by the asp.net routing engine. What you'll need to do is let the runtime catch this route and not handle it.
app.UseMvc(routes => {
    // maybe you have some other routes.... or not
    routes.Map("spa-fallback", "{*anything}", new {controller = "Home", action="Index"})
});

What should happen now is that your initial page will be rendered by the server, and any additional JS will run on the route.

A: OK, the solution described there.
http://blog.nbellocam.me/2016/03/21/routing-angular-2-asp-net-core/


text:
Q: SSL connection , error I am trying to connect through SSL from my phone device to my server.
When i am debugging the application on the device while i try to connect to my server i get this in the logs :
> Opening URL:
> https://193.158.3.165:8443/low-level-sample/subscribe?username=fk&password=ckd&appid=35[0.0]
> 82-M4687r9k9k836r980kO2395i32i66y10a34&address=320ef999&osversion=5.0.0.669&model=9520&type=public&f[0.0]
> ield1=844;deviceside=false;ConnectionType=mds-public
>     SSL:->CH

and an error on the device that i cant reach my server. The server is accessible by the browser of the device though.
Any ideas what this mean :

SSL:->CH

Looking at it again i suppose this is something like the first step of the handshake between the client and the server?


text:
Q: How to remove "look up, translate, search web" options and keep "Find selection" for selected text iOS 16 Working with UITextView
//...
txtView.isFindInteractionEnabled = true
//...

My code:
override func buildMenu(with builder: UIMenuBuilder) {
    if #available(iOS 16.0, *) {
        builder.remove(menu: .lookup)
    }
    super.buildMenu(with: builder)
}

This will remove: Find selection, look up, translate, search web.
I want to keep only the option: "Find selection" and remove the others "look up, translate, search web"

A:     override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {

        if action.description == "_findSelected:" {
            return true
        }else{
            return false
        }
    }

A: Instead of removing the whole menu you can remove specific child elements from it.
override func buildMenu(with builder: UIMenuBuilder) {
    if #available(iOS 16.0, *) {
        builder.replaceChildren(ofMenu: .lookup) { elements in
            return elements.filter { item in
                switch (item as? UICommand)?.action.description {
                case "_define:", "_translate:":
                    return false
                default:
                    return true
                }
            }
        }
    }
    super.buildMenu(with: builder)
}

_define: action contains both the elements Look up and Search web.


text:
Q: Windows Phone 8 Binding I have a Windows Phone 8 Pivot application which contains the auto generated MainViewModel Binding mechanism.
I have changed the MainViewModel class to suit my needs and changed the MainPage.xaml markup so that it binds to the correct properties.
All good.
Now - I have a class which calls a Web Service and a call-back method which fires when data is received:
private void GetSigns_Completed(object sender, OpenReadCompletedEventArgs e)
{
    using (var sr = new StreamReader(e.Result))
    {
        var data = sr.ReadToEnd();
        var result = JsonConvert.DeserializeObject<SignViewModel>(data);
    }
}

As you can see, I am not returning or populating anything with the result object as I do not know how to do so. The MainViewModel's properties have private setters:
public ObservableCollection<SignViewModel> Signs { get; private set; }
public ObservableCollection<TweetsViewModel> Tweets { get; private set; }

Each of these objects have a NotifyPropertyChange event.
So how do I populate the Signs and Tweets objects and make the whole binding work automatically when retrieving data from a Web Service? How do I make the UI/Mainpage.xaml communicate with the Web Service Class and the MainViewModel class?

A: To solve the issue, I simply changed the setters to public for Signs and Tweets. Once this was in place, the NotifyPropertyChange worked it's magic and automatically bound to the View. Magic! I wonder why Microsoft Developers made the setters private .....


text:
Q: Help: Can someone please explain the "Something else" set-up during installation like I'm 3 years old? I'm a huge fan of Ubuntu, and I have been using it as my main OS for about 2 years now. I never had any issues with it until now when I have to dual boot (work requirement) with Windows.
I followed a guide how to install Ubuntu, and Windows and took the decision so simply start from scratch as it seems easier (since all guides said I should start with installing Windows).
So, I got myself another SSD (I want to have Windows on one and Ubuntu on the other one. I then started to install on sdb, so far so good, Windows starts fine. It created an EFI drive, and a system, etc. Whatever Windows needs.
However, now I wanted to install Ubunutu 18.10 on my PC on my other SSD. I created a USB installer and followed the normal steps until I came to pick drives, there I picked "Something Else" (I think that is what is it called) and re-portioned my other SSD (sdc) so half of it was the OS, and the other half my home folder. For the boot drive I have tried picking (sda, sdb and sdc), however, whenever I pick another drive than the Windows EFI drive as first boot option, I get straight into grub-rescue and can't do anything. :( If I move back over to making the Windows EFI drive, I get straight into windows and all works fine. I tried re-installing Ubunutu over and over again with different options but nothing worked.
Could someone explain the installation process to me like I'm 3 years old and can't even start the PC without my parents clicking the on-button? Because I just can't get it too work, and I miss having Linux as my main OS, I only want to boot in to Windows when I work from home, not always.
I'm not sure I understand all the options with /, /home, /boot, and the swap, EFI etc. when I create new drives.
sda = A regular HDD, 2 tb that I have partioned so 500 gig is for windows, and the rest I would like to partion as a second "home" drive for Ubuntu, that mounts automatically when I start Ubuntu, however, I have never figured out which option I need to pick for this one?
sdb = Windows drive and all the folders it automatically creates when installing the OS.
sdc = My other SSD where I want to have my /(OS), /home and SWAP.
However, like I said, I just can't get it working and I would really love any help at all to learn more about this and what it all means. I have tried reading several tutorials, but I just don't get it. :(
Update 1
It seems Ubuntu does NOT install in UEFI mode but in Legacy, and windows is installed in UEFI mode, how do I change this for Ubuntu when installing? The USB is also a UEFI (I turned of Legacy mode completely in my motherboard settings), but for some Ubuntu and Grub just won't work... – Zero just now   edit
Thanks in advance!

A: / is your root partition: main directory for your Ubuntu
/home is a user folder, it will be created anyway
/boot is a partitions where grub will be placed, should be primary
swap is for memory, same size as RAM, useful for hibernation.

A: You were on the right track.  A system can only have one EFI partition, and this is where the boot files go for all operating systems on the machine.
So do just what you had done, but let Ubuntu share the EFI partition with Windows.


text:
Q: How to run a macro on specific range in different sheets? I have a macro which read some data in a range and asks if I want to change it and then change any other cell which is the same in that way. it works just in one sheet how can I change it so that it searches all other sheets the same range?
I write it this way but I dont know why other data in other sheets would not change
Sub standardize()
For Each ws In ActiveWorkbook.Worksheets
For Each Title In Range("O1:O2000").Cells
Dim des As String
des = Title.Value
If Left(des, 1) <> "*" And Title.Value <> 0 Then
Dim MyDataObj As New DataObject
MyDataObj.SetText des
MyDataObj.PutInClipboard
newtitle = Application.InputBox(prompt:=des, Title:=" Input The description as you      like!", Type:=2)
If newtitle <> False Then
 For Each cate In ActiveWorkbook.Worksheets.Range("O1:O2000").Cells
 If titl.Value = des Then
 titl.Value = "*" & newtitle
 End If
 Next titl
 Next cate
 End If
 End If
 Next Title
 Next ws
 End Sub

A: EDIT 1: added better code
I removed your ws_loop and placed it in the middle of a new loop that loops through all of the worksheets. I also added a select at the top to switch between sheets  and a msgbox near the end.
Sub standardize()
Dim WS_Count As Integer
Dim I As Integer

' Set WS_Count equal to the number of worksheets in the active
' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count

' Begin the loop.
For I = 1 To WS_Count
 ActiveWorkbook.Worksheets(I).select

''''Below is your code without the ws loop

For Each Title In Range("O1:O2000").Cells
Dim des As String
des = Title.Value
If Left(des, 1) <> "*" And Title.Value <> 0 Then
Dim MyDataObj As New DataObject
MyDataObj.SetText des
MyDataObj.PutInClipboard
newtitle = Application.InputBox(prompt:=des, Title:=" Input The description as you      like!", Type:=2)
If newtitle <> False Then
For Each cate In ActiveWorkbook.Worksheets.Range("O1:O2000").Cells
If titl.Value = des Then
titl.Value = "*" & newtitle
End If
Next titl
Next cate
End If
End If
Next Title

MsgBox ActiveWorkbook.Worksheets(I).Name

Next I
End Sub


text:
Q: Why i can't run this simple example with selenium? The script is:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.python.org")

and this come out:
/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/GeniusV/Documents/pythonProject/untitled/hj.py
Traceback (most recent call last):
  File "/Users/GeniusV/Documents/pythonProject/untitled/hj.py", line 5, in <module>
    driver = webdriver.Firefox()
  File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 103, in __init__
    self.binary, timeout)
  File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/firefox/extension_connection.py", line 51, in __init__
    self.binary.launch_browser(self.profile, timeout=timeout)
  File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 67, in launch_browser
    self._start_from_profile_path(self.profile.path)
  File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 90, in _start_from_profile_path
    env=self._firefox_env)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception

OSError: [Errno 2] No such file or directory

i really don't understand why,is it my python or selenium's problem?

A: Sounds like a compatibility issue.
Make sure you are using the latest selenium:
pip install --upgrade selenium

And have the latest Firefox installed.


text:
Q: Extract all values in a string that occur after another substring in R Lets say I have a string:
fgjh=621729_&ioij_fgjh7=twenty-_-One-_-Forty

I want to extract the following substrings from this string:
1. "621729"
2. "twenty"
3. "One"
4. "Forty"

Basically I want to extract anything after the "fgjh=" substring and "fgjh7=" sub strings.
I've found that this formula works in excel:
=TRIM(RIGHT(SUBSTITUTE(A1,"fgjh=",REPT(" ",LEN(A1))),LEN(A1)))

But the excel file is too large and I need to perform the same operation in R
How would I deal with leading characters and trailing characters. Let's say the string was "lmnop_82137_hhgia=77789_pasdk_ikuk_fgjh=621729_&ioij_fgjh7=twenty--One--Forty_dsaoij_882390=lkuk" and I need to extract the data after "fgjh=" i.e 621729 and everything after "fgjh7=" to get only "twenty", "one" and "forty"

A: Using sub with regular expression is more flexible than splitting by position:
> sub(".*=(.*)_&.*", "\\1", "fgjh=621729_&ioij_fgjh7=twenty--One--Forty", )
[1] "621729"
> sub(".*=(.*)--.*--.*", "\\1", "fgjh=621729_&ioij_fgjh7=twenty--One--Forty", )
[1] "twenty"
> sub(".*--(.*)--.*", "\\1", "fgjh=621729_&ioij_fgjh7=twenty--One--Forty", )
[1] "One"
> sub(".*--(.*)$", "\\1", "fgjh=621729_&ioij_fgjh7=twenty--One--Forty", )
[1] "Forty"

In one line :
strsplit(sub(".*=(.*)_&.*=(.*)--(.*)--(.*)", "\\1\\|\\2\\|\\3\\|\\4",
  "fgjh=621729_&ioij_fgjh7=twenty--One--Forty" ), split="\\|")[[1]]

[1] "621729" "twenty" "One"    "Forty"

A: You could use the package stringr and the function str_match for example to parse out the interesting bits with regular expressions
> library(stringr)
> s <- "fgjh=621729_&ioij_fgjh7=twenty--One--Forty"

> str_match(s, "^fgjh=([0-9]+)_&ioij_fgjh7=(.+)--(.+)--(.+)$")
     [,1]                                         [,2]     [,3]     [,4]  [,5]
[1,] "fgjh=621729_&ioij_fgjh7=twenty--One--Forty" "621729" "twenty" "One" "Forty"

A: library(stringr)
unlist(strsplit(str_extract_all(string,'(?<=\\=)([^_]+)')[[1]],'--'))
[1] "621729" "twenty" "One"    "Forty"


text:
Q: Android Shape Rectangle with 2 colors I need to make a custom rectangle that should use hex colors from #bff54a up to #88c010.

Actually I have this xml but I can only use one of those colors. How can I make the gradient possible? I already searched and I didn't found anything like this.
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<stroke
    android:width="1dp"
    android:color="@color/gray_light" />

<solid android:color="#88c010" />

<corners
    android:bottomLeftRadius="8dp"
    android:bottomRightRadius="8dp"
    android:topLeftRadius="8dp"
    android:topRightRadius="8dp" />

</shape>

Thanks to all!

A: Use Gradient as the color of the Drawable :
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle" >

  <stroke
    android:width="1dp"
    android:color="@color/gray_light" />

  <gradient
    android:type="linear"
    android:centerX="0"
    android:centerY="1"
    android:startColor="#bff54a"
    android:endColor="#88c010" />

  <corners
    android:bottomLeftRadius="8dp"
    android:bottomRightRadius="8dp"
    android:topLeftRadius="8dp"
    android:topRightRadius="8dp" />

</shape>

See Drawable Resources

A: You can create file shape and implement this code
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>

        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangule"> <!-- oval -->
            <gradient
                android:startColor="#388E3C"
                android:endColor="#448AFF"
                android:centerColor="@color/colorPrimary"
                />
        </shape>
    </item>
</selector>

Result


text:
Q: Code for to Click on Customer textblock in telerik test studio How can I manually write code to click on a customer text block in Telerik Test Studio?  If I click on the customer, it displays to add new record text block. When I am recording and playback Telerik Test Studio, it's failing the click event.

A: By default, test studio doesn't trigger the appropriate javascript events to make dynamic web pages update correctly; but, there are a number of workarounds you can try. Which one you need depends on exactly which javascript event needs to be triggered and what needs to be happen, but I'd suggest trying the following:

*

*Edit the click step, enabling the 'SimulateRealClick' property:

*Add an extra step to deliberately invoke the OnBlur event:

*Add an extra step to deliberately invoke the OnChange event:

In any case, it's worth talking to your developers to find out exactly what kind of event they're using to add the new record text block; that way you'll understand what kind of workaround is most suitable.


text:
Q: SwiftUI: How to pass core data objects to views? What I want to do: pass a reference to a NSManagedObject of a FetchRequest (here from: TestView) to another Child-View (here: LogRectangle).
What I tried:
These are basically the important lines:
List(testObjects, id: \.self) { habit in
    LogRectangle(testObject: testObject)
}

And this is the whole code:
struct TestView : View {
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(
        entity: TestObject.entity(),
        sortDescriptors: [NSSortDescriptor(keyPath: \TestObject.name, ascending: true)]
    ) var testObjects: FetchedResults<TestObject>

    var body: some View {
        NavigationView {
            HStack {
                Button(action: {
                    let testObject = TestObject(context: self.managedObjectContext)
                    habit.name = "TestObject String"
                    do {
                        try self.managedObjectContext.save()
                    } catch {
                        // handle the Core Data error
                    }
                }) {
                    Text("Insert example TestObject")
                }
                List(testObjects, id: \.self) { habit in
                    LogRectangle(testObject: testObject)
                }
            }
                .navigationBarTitle("Test")
        }
    }
}

struct LogRectangle : View {
    var habit : TestObject

    var body: some View {
        Text(habit.name)
            .font(.title)
            .foregroundColor(.white)
    }
}

Here I get this error on the line with the text in the class LogRectangle.
Cannot convert value of type 'String?' to expected argument type 'LocalizedStringKey'

A: You are encountering this error perhaps because the attribute, name, is defined as an optional string in the data model.
The Text struct does not take an optional value. It has to be an explicit value that is:

*

*A value conforming to the StringProtocol

*A literal string that can be used for loading a localized string

Therefore, you will need to make some changes to the model that you are passing to the LogRectangle. These change can either be made at the data model level (and then updating the associated NSManagedObject class, or you can have a computed property on the model to provide a non-optional value of the attribute.

A: You may have better luck using the testObject indices for the list rather than iterating on the actual objects. Try this:
List(testObjects.indices, id: \.self) { index in
     LogRectangle(testObject: testObjects[index])
}