text:
Q: Incorrect result when solving Dirichlet problem for the Laplace equation in an annulus Following an example from the documentation (DSolve/Scope/Elliptic Partial Differential Equations),
I try in version 13 on Windows 10
ClearAll["Global`*"];
leqn = Laplacian[u[r, θ], {r, θ}, "Polar"] == 0;
bc1 = u[1, θ] ==Sin[θ]^4;bc2 = u[3, θ] == 1;
DSolve[{leqn, {bc1, bc2}}, u[r, θ], {r, θ}]

{{u[r, θ] -> Piecewise[{{3/8 + (5*Log[r])/(8*Log[3]), 1 <= r <= 3}}, Indeterminate]}}

It's clear the above  result is not correct. For comparison,
Maple 2022 produces
$$u \! \left(r , \theta \right) =
\frac{\left(328 r^{6}-26568 r^{2}\right) \ln \! \left(3\right) \cos \! \left(2 \theta \right)+\left(-r^{8}+6561\right) \ln \! \left(3\right) \cos \! \left(4 \theta \right)+19680 \left(\ln \! \left(3\right)+\frac{5 \ln \left(r \right)}{3}\right) r^{4}}{52480 \ln \! \left(3\right) r^{4}}.
 $$
Is there a symbolic, not numerical, workaround for this result of DSolve?

A:
Is there a symbolic, not numerical, workaround for this result of
DSolve

Here is a workaround.
Since $\sin^4(\theta) = \frac{3}{8}+\frac{\cos \left(4 \theta \right)}{8}-\frac{\cos \left(2 \theta \right)}{2}$ and since the pde is linear, we will solve the pde using each term above as the BC and then add the solutions.
This gives the same answer as Maple. Just make sure to use $u(3,\theta)=1$ once and set it to zero for the second and third solution so not to over add.
ClearAll["Global`*"];
leqn = Laplacian[u[r, θ], {r, θ}, "Polar"] == 0;

bc2 = u[3, θ] == 1;
bc1 = u[1, θ] == 3/8;
sol1 = DSolveValue[{leqn, {bc1, bc2}}, u[r, θ], {r, θ}];

bc2 = u[3, θ] == 0;
bc1 = u[1, θ] == Cos[4*θ]/8;
sol2 = DSolveValue[{leqn, {bc1, bc2}}, u[r, θ], {r, θ}];

bc2 = u[3, θ] == 0;
bc1 = u[1, θ] == -Cos[2*θ]/2;
sol3 = DSolveValue[{leqn, {bc1, bc2}}, u[r, θ], {r, θ}];

sol = sol1 + sol2 + sol3 // Simplify

 sol /. {r -> 1.5, θ -> Pi/2}
 (* 0.841205 *)

Compare to Maple
restart;
pde:=VectorCalculus:-Laplacian(u(r,theta),'polar'[r,theta]);
bc  := u(1,theta)=sin(theta)^4,u(3,theta)=1;
sol :=pdsolve([pde=0,bc],u(r,theta));

evalf(eval(rhs(sol),[r=1.5,theta=Pi/2]))

 #0.8412050606

For some reason, Mathematica had hard time with $\sin^4(\theta)$ as it stands.
 mmaPlot=ParametricPlot3D[{r Sin[θ], r Cos[θ], sol}, {θ, -Pi, Pi}, {r, 1, 3}]

mapleSol = ((328*r^6 - 26568*r^2)*Log[3]*
      Cos[2*θ] + (-r^8 + 6561)*Log[3]*Cos[4*θ] +
     19680*(Log[3] + (5*Log[r])/3)*r^4)/(52480*Log[3]*r^4);
maplePlot =  ParametricPlot3D[{r Sin[θ], r Cos[θ], mapleSol}, {θ, -Pi, Pi}, {r, 1, 3}]

Reply to comments

Unfortunately, this is a trick made by hand. Think of bc1 = u[1, θ]
==Sin[θ]^41;

Mathematica can also solve this by breaking the terms and adding the solutions one by one.  I do not understand what you mean by trick made by hand. You asked for a workaround and I gave one. This can always be automated. Here is the same thing done for $\sin^8(\theta)$ for example. I do not feel now like doing it for $\sin^{41}(\theta)$ without writing automated function which will do it automatically.
Since
$$
\sin^8(\theta) = -\frac{7}{16} \cos (2 \theta )+\frac{7}{32} \cos (4 \theta )-\frac{1}{16} \cos (6 \theta )+\frac{1}{128} \cos (8 \theta )+\frac{35}{128}
$$
Then
ClearAll["Global`*"];
leqn = Laplacian[u[r, θ], {r, θ}, "Polar"] == 0;

bc1 = u[1, θ] == 35/128;
bc2 = u[3, θ] == 1;
sol1 = DSolveValue[{leqn, {bc1, bc2}}, u[r, θ], {r, θ}];

bc2 = u[3, θ] == 0;
bc1 = u[1, θ] == Cos[8*θ]/128;
sol2 = DSolveValue[{leqn, {bc1, bc2}}, u[r, θ], {r, θ}];

bc2 = u[3, θ] == 0;
bc1 = u[1, θ] == -Cos[6*θ]/16;
sol3 = DSolveValue[{leqn, {bc1, bc2}}, u[r, θ], {r, θ}];

bc2 = u[3, θ] == 0;
bc1 = u[1, θ] == (7*Cos[4*θ])/32;
sol4 = DSolveValue[{leqn, {bc1, bc2}}, u[r, θ], {r, θ}];

bc2 = u[3, θ] == 0;
bc1 = u[1, θ] == -(7*Cos[2*θ])/16;
sol5 = DSolveValue[{leqn, {bc1, bc2}}, u[r, θ], {r, θ}];

sol = sol1 + sol2 + sol3 + sol4 + sol5 // Simplify

Which gives same answer as Maple.  DSolve have hard time with trig function raised to  powers on them for some reason.
Compare to the wrong solution when done without breaking it up first
ClearAll["Global`*"];
leqn = Laplacian[u[r, θ], {r, θ}, "Polar"] == 0;
bc1 = u[1, θ] == Sin[θ]^8;
bc2 = u[3, θ] == 1;
sol = DSolveValue[{leqn, {bc1, bc2}}, u[r, θ], {r, θ}]

Unfortunately, your statement "This can always be automated" is
ungrounded

Here is a simple way to automate the expansion. May be this will ground it now.
ClearAll["Global`*"];
leqn = Laplacian[u[r, θ], {r, θ}, "Polar"] == 0;
expand = Expand@TrigReduce[Sin[θ]^4];
expand = If[Head[expand] === Plus, expand = List @@ expand, {expand}];
assump = Assumptions -> 1 <= r <= 3;
sol = Total@First@Last@Reap@Do[
       Sow@If[n == 1,DSolveValue[{leqn, {u[3, θ] == 1, u[1, θ] == expand[[n]]}}, u[r, θ], {r, θ}, assump],
         DSolveValue[{leqn, {u[3, θ] == 0, u[1, θ] == expand[[n]]}},
          u[r, θ], {r, θ}, assump]
         ]
       , {n, 1, Length@expand}
       ];
sol = Simplify[sol]
ParametricPlot3D[{r Sin[θ], r Cos[θ], sol}, {θ, -Pi, Pi}, {r, 1, 3}]

Think of bc1 = u[1, θ] ==Sin[θ]^41;

Here it is for Sin[θ]^41
ClearAll["Global`*"];
leqn = Laplacian[u[r, θ], {r, θ}, "Polar"] == 0;
expand = Expand@TrigReduce[Sin[θ]^(41)];
expand = If[Head[expand] === Plus, expand = List @@ expand, {expand}];
assump = Assumptions -> 1 <= r <= 3;
sol = Total@First@Last@Reap@Do[
       Sow@If[n == 1,
         DSolveValue[{leqn, {u[3, θ] == 1,
            u[1, θ] == expand[[n]]}},
          u[r, θ], {r, θ}, assump],
         DSolveValue[{leqn, {u[3, θ] == 0,
            u[1, θ] == expand[[n]]}},
          u[r, θ], {r, θ}, assump]
         ]
       , {n, 1, Length@expand}
       ];
sol = Simplify[sol]
ParametricPlot3D[{r Sin[θ], r Cos[θ],
  sol}, {θ, -Pi, Pi}, {r, 1, 3}]


text:
Q: Check if a string contains another string from different Dataframe - Python I have two Dataframes with different columns and size.
The first one has some columns and one of them is a string field (column 1). The second dataframe has 2 columns, one is a string field (column 4) with 2 words separated by comma and another is a integer field (column 5).
I need to verify that column 1 in Dataframe 1 has the words in column 4 Dataframe 2 and fill in Dataframe 1 with the corresponding information in dataframe 2.
Example:
df1
    column 1                                column 2          column 3
0   bla bla sample1 bla bla sample2         a                 f
1   bla bla sample1 bla bla sample5         b                 g
2   bla bla sample3 bla bla sample4         c                 h
3   bla bla sample8 bla bla sample7         d                 i
4   bla bla sample1 bla bla sample2         e                 j

 df2
    column 4                       column 5
0   ('sample1', 'sample2'),        50
1   ('sample3', 'sample4'),        35
2   ('sample1', 'sample5')         18

I need the output:
Output:
df1
    column 1                               column 2  column 3  column 4                     column 5
0   bla bla sample1 bla bla sample2        a         f         ('sample1', 'sample2')     50
1   bla bla sample1 bla bla sample5        b         g         ('sample1', 'sample5')     18
2   bla bla sample3 bla bla sample4        c         h         ('sample3', 'sample4')     35
3   bla bla sample8 bla bla sample7        d         i         NaN
4   bla bla sample1 bla bla sample2        e         j         ('sample1', 'sample2')     50

Any ideas?
Thanks!

A: I don't guarantee this will be particularly fast, but it gets the job done. We'll use set logic to check for matches. We have to jump through some hoops so that we can store a list of tuples of the matches. I don't think this is a particularly good idea.
import numpy as np
import pandas as pd

df1['setc'] = df1['column 1'].str.split().apply(set)
# Initialize so addition works
df1['column 4'] = [[] for i in range(len(df1))]
df1['column 5'] = 0

for idx, row in df2.iterrows():
    m = (df1.setc.values & set(row['column 4'])) == set(row['column 4'])
    df1.loc[m, 'column 4'] += pd.Series([[row['column 4']] for x in range(len(m))])[m]
    df1.loc[m, 'column 5'] += row['column 5']

df1 = df1.drop(columns='setc')
# NaN where nothing matched
df1.loc[df1['column 4'].str.len().eq(0), ['column 4', 'column 5']] = np.NaN

Output:
                          column 1 column 2 column 3                                  column 4  column 5
0  bla bla sample1 sample5 sample2        a        f  [(sample1, sample2), (sample1, sample5)]      68.0
1  bla bla sample1 bla bla sample5        b        g                      [(sample1, sample5)]      18.0
2  bla bla sample3 bla bla sample4        c        h                      [(sample3, sample4)]      35.0
3  bla bla sample8 bla bla sample7        d        i                                       NaN       NaN
4  bla bla sample1 bla bla sample2        e        j                      [(sample1, sample2)]      50.0

redpajama_set_name: RedPajamaStackExchange


text:
Q: HighChart - Stacked Bar chart - To show dash line over the bar chart to the specific portion in the bar I tried to highlight specific portion in the bar chart like above screenshot. Whenever we tried to highlight, it always from the origin of the y axis. It would be great if you have to possible solution to achieve this use cases. Attached screenshot the way solution expecting.
Code Snippet:
Highcharts.chart('container', {
  chart: {
    type: 'bar'
  },
  xAxis: {
    categories: ['Jan'],
    visible: false
  },
  yAxis: {
    min: 0,
    visible: false
  },

  plotOptions: {
    series: {
      stacking: 'normal'
    },
    dataLabels: {
      enabled: false,
    }
  },

  series: [{
    name: 'John',
    data: [{
      y: 15
    }]
  }, {
    name: 'Jane',
    data: [{
      y: 22
    }]
  }, {
    name: 'Joe',
    borderWidth: 3,
    borderColor: 'red',
    zIndex: 1000,
    data: [
   { x:0,y:44}]
  }]
});

A: You just need to color the border of another series. So instead of:
series: [..., {
 name: 'Joe',
 borderWidth: 3,
 borderColor: 'red',
 zIndex: 1000,
 data: [
  { x:0,y:44}]
}]

you can write:
series: [..., {
 name: 'Jane',
 borderWidth: 2,
 borderColor: 'red',
 zIndex: 1,
 data: [{
  y: 22
}]
}, ...]

Demo: https://jsfiddle.net/BlackLabel/648ef3v7/


text:
Q: How to cast video to Sony TV I was using the CastCompanionLibrary to build an application. In my network, I had a Chromecast device and a Sony Bravia TV. When I clicked on  my app'sMediaRouteButton, I only saw the ChromeCast:

But when I used the YouTube application, I saw:

How can I discover my TV and cast my video to it like YouTube did?


text:
Q: Swing Popup Frame Hello i have a program that should create a popup when the button is pressed and popup should contain text fields and buttons.I searched but i only found JOptionPane but it does not contain more than one text field so i need something else.
I tought that if i make a internal frame and make it invisible and when pressed make it visible
private void ButtonActionPerformed(java.awt.event.ActionEvent evt) {
InternalFrame.show();
InternalFrame.toFront();
}
but it doesn't work so i need a code to make this possible(it doesn't matter if its frame or not)

A: You can add multiple Textfields and Buttons.
Refere below SO Questions and answers
Multiple input in JOptionPane.showInputDialog
JOptionPane with multiple inputs on different lines
JOptionPane with multiple buttons on each line?
JOptionPane showInputDialog with custom buttons


text:
Q: 'openURL' was deprecated in iOS 10.0: Please use openURL:options:completionHandler: instead in Swift 3 I have working open webLink url code in Swift3 but when I use it gives me this warning;

'openURL' was deprecated in iOS 10.0: Please use openURL:options:completionHandler: instead

How can I resolve it, my code under below.
let myUrl = "http://www.google.com"
 if !myUrl.isEmpty {
                                UIApplication.shared.openURL(URL(string: "\(myUrl)")!)
                            }

Thank you.

A: Try to use this:
UIApplication.shared.open(URL(string: "\(myUrl)")!)

A: Use like
 //inside scope use this
 let myUrl = "http://www.google.com"
    if let url = URL(string: "\(myUrl)"), !url.absoluteString.isEmpty {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }

    // or outside scope use this
    guard let url = URL(string: "\(myUrl)"), !url.absoluteString.isEmpty else {
       return
    }
     UIApplication.shared.open(url, options: [:], completionHandler: nil)

For more reference see this sample link.


text:
Q: ansible playbook: check linux process count I am trying to write a playbook which shows failed when number of process running in linux host is not equal to 2. Following playbook works, but is there any better way of doing it? like is there any specific Ansible module to check process linux host?
  ---
  - hosts: web
    become: yes
    become_method: su
    become_user: webuser
    tasks:
    - name: process check
      shell: ps -ef|grep -i etas|grep -v grep|wc -l
      register: command_result
      failed_when: "'2' not in command_result.stdout"

A: What is your Ansible version? There is no Ansible module to count the number of processes in Linux. You can make it readable by:
  tasks:
  - name: process check
    shell: pgrep etas | wc -l
    register: command_result
    failed_when: command_result.stdout|int != 2


text:
Q: Typing input in by hand works. Using input file causes infinite loop? I'm currently working on a programming assignment for school. It's a simple text-based RPG. When I test the program locally (by hand), it works correctly. However, when I submit it to the grading server, it creates some sort of infinite loop.
I emailed my professor, who responded by explaining how the server tested the program. It uses the following format: java IPA1 (XML file name) < (Input file) > (output file). IPA1 is the name of the main java file. It seems that the < (Input file) is causing the endless loop for some reason... but I cannot pinpoint why.
My program gets its input with the following code:
boolean gameOver = false;
while (!gameOver) {
  Command cmd = inputParser.getCommand();
  gameOver = processCommand(cmd);
}

The getCommand(cmd) is as follows:
public Command getCommand() {
  String input = "";

  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  try {
    input = reader.readLine();
  } catch(java.io.IOException exc) {
    System.out.println ("Error");
  }

  return new Command(input);
}

My question is: Why would this work when I type each command in sequentially by hand... but fail when an input file is used?

A: This is because you are creating a buffered reader that reads more than you requested it to read. When you tell it to read five characters, it reads a lot more and saves them for the next request to boost performance. You should reuse one BufferedReader instead of creating many of them because when you create many of them, the first one already grabs stuff you want to read with the second one.

A: Try printing out what you read - there might be new line symbol at the end of the string or something is different about the file, so it doesn't exit from the loop. You can also debug the program to see exactly what's happening.
If you want exact answer to why in this case it doesn't work you need to post the
processCommand() function and the content of the file.


text:
Q: JSONDecodeError when scraping target website using Scrapy Up until 3 days ago I was able to scrape the target site. However, it started showing the error I will post below. When I looked at the source code of the site, I could not see any changes. It also returns as scrapy (200) response. I am using proxy and user-agent. I changed them but still the same result. I keep getting json decode error.
Error:

File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char
0)

My code:
import scrapy
import json
import datetime
import bs4
import re
import time
from requests.models import PreparedRequest
import logging
from hepsibura_spider.items import HepsiburaSpiderItem
from scrapy.crawler import CrawlerProcess

class HepsiburaSpider(scrapy.Spider):
    name = 'hepsibura'
    # allowed_domains = ['www.hepsibura.com']
    handle_httpstatus_list = [301]
    def start_requests(self):
        urls = [
            'https://www.hepsiburada.com/monitor-bilgisayarlar-c-116465?filtreler=satici:Hepsiburada;?_random_number={rn}#tabIndex=0',

        ]
        for url in urls:
            params = []
            # added a meta to provide the used url here
            main_url, parameters = url.split('&') if '&' in url else url, None
            parameters = parameters.split(':') if parameters else []
            for parameter in parameters:
                key, value = parameter.split('=')
                params.append((key.strip(), value.strip()))

            # params.append(('main_url', main_url))

            if 'sayfa' not in dict(params):
                params.append(('sayfa', '1'))

            yield scrapy.Request(
                url=url.format(rn=time.time()),
                callback=self.parse_json,
                meta={
                    'main_url': main_url,
                    'params': dict(params),
                },
                headers={
                    'Cache-Control': 'store, no-cache, must-revalidate, post-check=0, pre-check=0',
                    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.5134.152 Safari/537.36',
                }
            )

    def parse_json(self, response):

        if response.status == 301:
            logging.log(logging.INFO, 'Finished scraping')
            return
        current_url = response.request.url.split('&')[0].strip()
        parameters = response.meta.get('params')

        soup = bs4.BeautifulSoup(response.text,'lxml')
        scripts = soup.select('script')
        data_script = ''
        for script in scripts:
            # print(script.text)
            if 'window.MORIA.PRODUCTLIST = {' in str(script):
                print('Found the data')
                data_script = str(script)
                break

        data_script = data_script.replace('<script type="text/javascript">','').replace('window.MORIA = window.MORIA || {};','').replace('window.MORIA.PRODUCTLIST = {','').replace('\'STATE\': ', '').replace('</script>','')[:-4]
        json_data = json.loads(data_script)
        products = json_data['data']['products']
        for product in products:
            item = HepsiburaSpiderItem()

            item['rowid'] = hash(str(datetime.datetime.now()) + str(product['productId']))
            item['date'] = str(datetime.datetime.now())
            item['listing_id'] = product['variantList'][0]["listing"]["listingId"]
            item['product_id'] = product['variantList'][0]["sku"].lower()
            item['product_name'] = product['variantList'][0]['name']
            item['price'] = float(product['variantList'][0]['listing']['priceInfo']['price'])
            item['url'] = 'https://www.hepsiburada.com' + product['variantList'][0]["url"]
            item['merchantName'] = product['variantList'][0]["listing"]["merchantName"].lower()

            yield item

        parameters['sayfa'] = int(parameters['sayfa']) + 1
        req = PreparedRequest()
        req.prepare_url(current_url, parameters)

        yield scrapy.Request(
            url=req.url,
            callback=self.parse_json,
            meta={
                'params': parameters,
            },
            headers={
                'Cache-Control': 'store, no-cache, must-revalidate, post-check=0, pre-check=0',
                'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.5134.152 Safari/537.36',
            }
        )

if __name__ == '__main__':
    process = CrawlerProcess()
    process.crawl(HepsiburaSpider)
    process.start()

I found somethings. Site changed their json format. Every requests generate unique id:
window.MORIA.PRODUCTLIST = Object.assign(window.MORIA.PRODUCTLIST || {}, {
'60cada8e-57dd-466e-f7af-62efca4fa8a8': {

How can I bypass this?
Thank you.

A: There's really no need to use BeautifulSoup with scrapy.
The problem is that data_script is empty.
Get rid of the loop, just use xpath to select the script tag that has that text, and use re_first() function to get the JSON string.
Also you might want to check that data is not empty for later uses.
# soup = bs4.BeautifulSoup(response.text, 'lxml')
# scripts = soup.select('script')
# data_script = ''
# for script in scripts:
#     # print(script.text)
#     if 'window.MORIA.PRODUCTLIST = {' in str(script):
#         print('Found the data')
#         data_script = str(script)
#         break
data = response.xpath('//script[contains(text(), "window.MORIA.PRODUCTLIST")]/text()').re_first(r'\'STATE\': ({.+})')

#data_script = response.xpath('//script[contains(text(), "window.MORIA.PRODUCTLIST")]/text()').re()
#data_script = data_script.replace('<script type="text/javascript">', '').replace('window.MORIA = window.MORIA || {};', '').replace('window.MORIA.PRODUCTLIST = {', '').replace('\'STATE\': ', '').replace('</script>', '')[:-4]
json_data = json.loads(data)
products = json_data['data']['products']

Output:
{'rowid': -1443611402678861624, 'date': '2022-09-18 16:25:58.168075', 'listing_id': 'fd2eb812-f483-4233-bfea-610490e16014', 'product_id': 'hbcv000013tlaw', 'product_name': 'MSI PRO\xa016T 10M-043TR Intel Celeron 5205U 4GB\xa0128GB SSD Windows 10 Pro 15.6" All In One Bilgisayar', 'price': 12491.21, 'url': 'https://www.hepsiburada.com/msi-pro-16t-10m-043tr-intel-celeron-5205u-4gb-128gb-ssd-windows-10-pro-15-6-all-in-one-bilgisayar-p-HBCV000013TLAW?magaza=Hepsiburada', 'merchantName': 'hepsiburada'}
DEBUG: Scraped from <200 https://www.hepsiburada.com/monitor-bilgisayarlar-c-116465?filtreler=satici:Hepsiburada;?_random_number=1663507557.5583432>
{'rowid': 557951834722614927, 'date': '2022-09-18 16:25:58.168075', 'listing_id': '76835cb4-74d3-498b-821a-58311752c934', 'product_id': 'hbcv0000065deb', 'product_name': 'Apple iMac M1 Çip 8GB 512GB SSD macOS Retina 24" FHD All In One Bilgisayar MGPJ3TU/A Yeşil', 'price': 34998.99, 'url': 'https://www.hepsiburada.com/apple-imac-m1-cip-8gb-512gb-ssd-macos-retina-24-fhd-all-in-one-bilgisayar-mgpj3tu-a-yesil-p-HBCV0000065DEB?magaza=Hepsiburada', 'merchantName': 'hepsiburada'}
DEBUG: Scraped from <200 https://www.hepsiburada.com/monitor-bilgisayarlar-c-116465?filtreler=satici:Hepsiburada;?_random_number=1663507557.5583432>
{'rowid': 2200588215358298971, 'date': '2022-09-18 16:25:58.168075', 'listing_id': '17fd6809-afa9-4e21-a772-509864d9bf28', 'product_id': 'hbcv000014z6fy', 'product_name': 'MSI MODERN AM241 11M-298TR Intel Pentium 7505 4GB 128GB SSD Windows 10 Pro 23.8" All In One Bilgisayar', 'price': 15335.09, 'url': 'https://www.hepsiburada.com/msi-modern-am241-11m-298tr-intel-pentium-7505-4gb-128gb-ssd-windows-10-pro-23-8-all-in-one-bilgisayar-p-HBCV000014Z6FY?magaza=Hepsiburada', 'merchantName': 'hepsiburada'}
DEBUG: Scraped from <200 https://www.hepsiburada.com/monitor-bilgisayarlar-c-116465?filtreler=satici:Hepsiburada;?_random_number=1663507557.5583432>
{'rowid': 2433557015268455354, 'date': '2022-09-18 16:25:58.170501', 'listing_id': '0f0e1577-f1c2-4df5-ae9c-6c754317e998', 'product_id': 'hbcv00001eo94e', 'product_name': 'MSI MODERN AM271P 11M-021XTR Intel Core i7 1165G7 16GB 512GB SSD Freedos 27" FHD All In One Bilgisayar', 'price': 26754.38, 'url': 'https://www.hepsiburada.com/msi-modern-am271p-11m-021xtr-intel-core-i7-1165g7-16gb-512gb-ssd-freedos-27-fhd-all-in-one-bilgisayar-p-HBCV00001EO94E?magaza=Hepsiburada', 'merchantName': 'hepsiburada'}
Scraped from <200 https://www.hepsiburada.com/monitor-bilgisayarlar-c-116465?filtreler=satici:Hepsiburada;?_random_number=1663507557.5583432>
...
...


text:
Q: Mvc apicontroller , how can i set unlimited length for maxJsonLength when i receive the request I am  new to mvc and ran into an issue wile creating a controller api where it will be able to accept files in the httpRequest. It works fine for small files, but when the size of the file exceeds 4MB, it fails with "Internal server error", the request does not even hit my controller api.
I did see some posts where it has mentioned to use JavascripSerializer in a controller.
(Can I set an unlimited length for maxJsonLength in web.config? 9)
But i am not sure how to use this when accepting a request with larger files.
Any help on this is appreciated.

A:
But i am not sure how to use this when accepting a request with larger files.

In your web.config you could increase the maximum size of the request:
<system.web>
    <!-- Set the maximum request size to 1GB (the value is in KB here) -->
    <httpRuntime maxRequestLength="1048576" />
    ...
</system.web>

and if you are running in IIS 7 integrated pipeline mode you also need to set the <requestLimits> to the same value:
<system.webServer>
    <security>
        <requestFiltering>
           <!-- Set the maximum request size to 1GB (the value is in Bytes here) -->
            <requestLimits maxAllowedContentLength="1073741824" />
        </requestFiltering>
    </security>
</system.webServer>


text:
Q: Python 3: How to extract url image? The urls I want to extract have same pattern:
"begin" : "url_I_want_extract"

They look like:
"begin" : "https://k2.website.com/images/0x0/0x0/0/16576946054146395951.jpeg"
"begin" : "https://k2.website.com/images/0x0/0x0/0/9460365509030976330.jpeg"
"begin" : "https://k2.website.com/images/0x0/0x0/0/9361112829030898475.jpeg"
"begin" : "https://k3.website.com/images/0x0/0x0/0/14705723619301900580.jpeg"
"begin" : "https://k3.website.com/images/8x36/922x950/0/1368601155311066426.jpeg"

And I used this code to extract but getting unexpected things.
r = re.findall('https://k(.?).website.com/images/0x0/0x0/0/(.*?).jpeg', response.text)

The output I got:
 [('2', '16576946054146395951'), ('2', '9460365509030976330'), ('2', '9361112829030898475'), ('3', '14705723619301900580')]

The output I want:
https://k2.website.com/images/0x0/0x0/0/16576946054146395951.jpeg
https://k2.website.com/images/0x0/0x0/0/9460365509030976330.jpeg
https://k2.website.com/images/0x0/0x0/0/9361112829030898475.jpeg
https://k3.website.com/images/0x0/0x0/0/14705723619301900580.jpeg
https://k3.website.com/images/8x36/922x950/0/1368601155311066426.jpeg

How to use regex to scrape Urls after ""begin"" word ? Thank you :)

A: The parenthesis surround the capturing groups that are returned by findall.  Right now your capturing groups are k(.>) and (.*?).jpeg.  Remove those parenthesis and instead capture the entire url.
Also, to match both the url's with "/0x0/0x0/0/" and "/8x36/922x950/0/", replace "/0x0/0x0/0/" in the regex with "/.*/.*/.*/":
r = re.findall('(https://k.?.website.com/images/.*/.*/.*/.*?.jpeg)', response.text)

A: This one may do the trick on a more general server path construction:
https?.*(jpeg|jpg|png|tiff|gif)

Start capturing the http ( with optional 's' for ssl servers ) and finish capture assuring a image file format. ( Please note that I included 5 types just as an example...)

Hope that helps !!

A: I think what you're asking for is to extract only the URLs after begin :. For this you'd want:
r = re.findall('"begin" : "(https://k.*?.jpeg)"', response.text)


text:
Q: Wrapper classes and generic clarifications in Java In the below code, the line System.out.println(sumInteger(bigs) == sumInteger(bigs)); displays as false. But when again we compare the another Integer wrapper classes System.out.println(bc == ab);, it returns true. Why is the comparison of wrapper classes false in the first case and true in the second case?
import java.util.Arrays;
import java.util.List;

public class Arrays {

    public void array1() {

        List<Integer> bigs = Arrays.asList(100,200,300);
        System.out.println(sumInteger(bigs) == sum(bigs)); // 1. Output: true
        System.out.println(sumInteger(bigs) == sumInteger(bigs)); //2. Output: false

        Integer ab = 10;
        System.out.println(ab == 10); //3. Output: true
        Integer bc = 10;
        System.out.println(bc == ab); //4. Output: true
    }

    public static int sum (List<Integer> ints) {
        int s = 0;
        for (int n : ints) { s += n; }
        return s;
    }

    public static Integer sumInteger(List<Integer> ints) {
        Integer s = 0;
        for (Integer n : ints) { s += n; }
        return s;
    }

    public static void main(String[] args) {
        Array tm = new Array();
        tm.array1();
    }
}

A:    System.out.println(sumInteger(bigs) == sum(bigs)); // 1. ***Output: true
   System.out.println(sumInteger(bigs) == sumInteger(bigs)); //2. ***Output: false

sumInteger() returns an Integer and sum() returns an int, so you are testing the the equality of an Integer with an int, which causes the Integer to be auto-unboxed, so you end up comparing an int with an int. Both ints now have the same value, hence 'true'.
sumInteger() returns an Integer, calling sumInteger() again returns an Integer. These two Integers are separately created objects, yet both hold the same internal value. When you use '=='' compare them it compares the references and seeing as how each object was created independently the references are not equal, hence 'false'. Had you wanted to test the value for equality you would have needed to use the .equals() method.


text:
Q: Different way to write LDRB So I'm writing up some ARM code, and we were told to disassemble a program, and then recode it using what we know. The problem is I keep coming across as LDRB command, of which I know nothing about. Going through the ARM documentation, it seems to offset the value by one byte? How could I recode this in simple ARM, even though it'll take more lines?

A: LDRB loads a single byte from memory into a register.  I don't think there's any way to simplify that operation further.
Here's a link to the ARM docs for the LDR instruction.


text:
Q: Coin tossing probability What's the expected number of times you need to toss a fair coin until you see both
a heads and a tails at least once?
Why is the answer 3 and not 2? Because I would need to flip the coin at least twice to get one each.

A: On the first flip, you'll definitely get one of them. Then, as you wrote, the expected number of flips to get the other one is $2$, for a total of $3$. For a generalisation, see the coupon collector's problem.

A: Whatever you get on your first flip, your situation is: stop when you get the opposite.
On any given flip, the "average" number of heads (or tails) you will see is 0.5 (as the coin is fair), so you need two more flips to get 1 of the opposite you got on the first flip (on average)
So it's your initial flip (1) + 2 more flips = 3 flips
If you want the math:
After the first flip, let's say expected number of flips till you see the opposite is E .
So on your next flip with p = 0.5 you get the opposite and with p = 0.5 you are back to where you started.
So:
E = 0.5*1 + 0.5(1 + E)
0.5E = 1, E = 2
So the total expected flips = 1 + E = 3


text:
Q: Serialize Treeview to JSON and Deserialize back to Treeview I need to serialize a Treeview node to JSON format and deserialize back to a Treeview.
I have got a custom SubNode class as shown below
Class SubNode: TreeNode
{
    dynamic obj;
}

So when a tree node is created, it will also have a complex object in every node as shown below.
SubNode sub = new SubNode();
sub.obj.property = "Value1"
sub.obj.Complex.Prooerty = "Value2"

so on....
Could you please let me know how do we achieve this? Thanks a million in advance!

A: Look at existing libraries out there, the famous one is using JSON.NET. You can look at the examples on how to do it.
Serializing an object
public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public IList<string> Roles { get; set; }
}

Account account = new Account
 {
     Email = "james@example.com",
     Active = true,
     CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
     Roles = new List<string>
     {
         "User",
         "Admin"
    }
};

string json = JsonConvert.SerializeObject(account, Formatting.Indented);
// {
//   "Email": "james@example.com",
//   "Active": true,
//   "CreatedDate": "2013-01-20T00:00:00Z",
//   "Roles": [
//     "User",
//     "Admin"
//   ]
// }

Console.WriteLine(json);

Deserializing an object
string json = @"{
   'Email': 'james@example.com',
   'Active': true,
   'CreatedDate': '2013-01-20T00:00:00Z',
   'Roles': [
     'User',
     'Admin'
   ]
 }";

Account account = JsonConvert.DeserializeObject<Account>(json);

Console.WriteLine(account.Email);


text:
Q: How to figure out why a specific dll version is expected I have a large solution, containing several projects, all with different dependencies and Nuget packages.
For one specific project, when running, I eventually get an exception "Could not load file or assembly 'System.Threading.Tasks.Extensions, Version=4.2.0.0, [...]"
This happens when referencing one of our types for the first time, which doesn't have an obvious dependency on this specific assembly, but it is part of a large project that probably has one.
The thing is, We do have System.Threading.Tasks.Extensions in the bin folder, it just appears to be a different version than the one that is expected by this code.
I have tried to consolidate versions and update this package and dependent ones, to no avail.
What I am looking for specifically, is how to figure out what project/file/etc is expecting the specific version, and why.
As far as I can tell, everything in the entire solution appears to expect the correct version, yet something obviously doesn't.
The answer may be a Visual Studio option, an external tool (I have access to Resharper and other Jetbrains software), or a Nuget tool that I am not aware of. Anything that allows me to pinpoint what or who is expecting this erroneous version, so that I can then fix it, will qualify as a valid answer.


text:
Q: MSSQL: reusable way of querying subset of all data in a table Suppose a system where People have access to Buildings and in the buildings, have access to certain Rooms.
Access is defined according to the associated Permissions tables or in the case of people with full access, full access.
The db tables are defined as follows:
buildings (id INT)
rooms (id INT, building_id INT)
people (id INT, has_full_access BIT)
building_permissions (building_id INT, person_id INT)
room_permissions (room_id INT, person_id INT)

Currently I have table-valued functions that return tables with the authorised ids of buildings and rooms based on the person's id and whether they have full access.
CREATE FUNCTION fn_get_authorised_buildings (@person_id INT, @has_full_access BIT)
RETURNS TABLE AS
RETURN
(
    SELECT b.id
    FROM buildings b
    WHERE @has_full_access = 1

    UNION

    SELECT b.id
    FROM buildings b
        INNER JOIN building_permissions bp ON bp.building_id = b.id
    WHERE bp.person_id = @person_id
);

CREATE FUNCTION fn_get_authorised_rooms (@person_id INT, @has_full_access BIT)
RETURNS TABLE AS
RETURN
(
    SELECT r.id
    FROM rooms r
    WHERE @has_full_access = 1

    UNION

    SELECT r.id
    FROM rooms r
        INNER JOIN room_permissions rp ON rp.room_id = r.id
    WHERE rp.person_id = @person_id
);

Throughout the system whenever buildings and rooms are involved I need to filter those tables based on the person's permissions. If the person has full access then all the rows must be included, otherwise only those that they have permission for.
My queries (simplified) look something like this:
DECLARE @person_id INT = 123
DECLARE @has_full_access BIT = 1

DECLARE @authorised_buildings TABLE (id INT)
INSERT INTO @authorised_buildings SELECT id FROM fn_get_authorised_buildings(@person_id , @has_full_access)

DECLARE @authorised_rooms TABLE (id INT)
INSERT INTO @authorised_rooms SELECT id FROM fn_get_authorised_rooms(@person_id, @has_full_access)

--Example A
SELECT *
FROM buildings b
    INNER JOIN rooms r ON r.building_id = b.id
WHERE 1 = 1
    AND b.id IN (SELECT id FROM @authorised_buildings)
    AND r.id IN (SELECT id FROM @authorised_rooms)

--Example B
SELECT *
FROM floors f -- or other tables that are related to rooms
    INNER JOIN rooms r ON r.floor_id = f.id
WHERE 1 = 1
    AND r.id IN (SELECT id FROM @authorised_rooms)

Is there a better way to do this?
EDIT:
Here is a fiddle with the setup

A: You can create a view like this that contains all the logic:
CREATE VIEW bulding_rooms_per_person AS
SELECT p.id AS person_id, b.id as building_id, r.id AS room_id
FROM people p
LEFT JOIN building_permissions bp ON bp.person_id = p.id
LEFT JOIN room_permissions rp ON rp.person_id = p.id
INNER JOIN buildings b ON b.id = bp.building_id OR p.has_full_access = 1
INNER JOIN rooms r ON r.building_id = b.id AND (r.id = rp.room_id OR p.has_full_access = 1)

And then just query over it:
SELECT * from bulding_rooms_per_person WHERE person_id = @person_id


text:
Q: Auto Increment for non primary key column in Oracle I want to insert the records for a particular column that would be increment by 1 whenever the new row gets inserted into table based on the following condition
For current year the first row with value :1
For current year the column value should be increment by 1
meaning  1 for 1st record of that current year and next available number for the matching year
Year  Value
2016    1
2016    2
2016    3
2017    1
2017    2
...

My approach will be somewhat like this:
INSERT INTO ABC(ANALYSIS_YEAR,ANALYSIS_NUMBER)
values (EXTRACT(YEAR FROM sysdate),
        case when ANALYSIS_YEAR=EXTRACT(YEAR FROM sysdate) then AutoIcreamt with starting value 1 else 1;
    )

A: Any solution that looks at current table values will not work in a 'real' environment with multiple users and multiple sessions and parallel transactions.
I think you need to separate out the two requirements:

*

*Have the ability to sequence records based on when they were created

*Have the ability to report on record sequencing within a year.

The first is handled using a sequence as these are designed exactly for this and handle concurrency (multiple users, multiple transactions, ...).
The second is a reporting requirement and has a number of options depending on performance requirements.
First of all create a sequence:
create sequence seq_analysis_id start with 1 increment by 1 nocache nocycle;

Not let's create a base table and a trigger to handle the auto-increment:
create table analysis_data (
    analysis_id integer not null,
    analysis_date date not null
    );

alter table analysis_data add constraint pk_analysis_data primary key (analysis_id);

create or replace trigger trg_analysis_data
before insert on analysis_data
for each row
begin
    :new.analysis_id := seq_analysis_id.nextval();
end trg_analysis_data;
/

insert into analysis_data (analysis_date) values (to_date('2015-12-28', 'YYYY-MM-DD'));

insert into analysis_data (analysis_date) values (to_date('2015-12-29', 'YYYY-MM-DD'));

insert into analysis_data (analysis_date) values (to_date('2015-12-30', 'YYYY-MM-DD'));

insert into analysis_data (analysis_date) values (to_date('2015-12-31', 'YYYY-MM-DD'));

insert into analysis_data (analysis_date) values (to_date('2016-01-01', 'YYYY-MM-DD'));

insert into analysis_data (analysis_date) values (to_date('2016-01-02', 'YYYY-MM-DD'));

insert into analysis_data (analysis_date) values (to_date('2016-01-03', 'YYYY-MM-DD'));

commit;

select * from analysis_data;

ANALYSIS_ID    ANALYSIS_DATE
    1           28/12/2015
    2           29/12/2015
    3           30/12/2015
    4           31/12/2015
    5           01/01/2016
    6           02/01/2016
    7           03/01/2016

Ok - so that all works fine but doesn't give you what you asked for :)
This is the second part - the reporting requirement:
The first option is just to get the numbers you need dynamically:
select
    analysis_id,
    analysis_date,
    extract(year from analysis_date) analysis_year,
    row_number()
        over (partition by trunc(analysis_date, 'YYYY')
        order by analysis_date, analysis_id) analysis_number
from
    analysis_data;

Using Analytic Functions (row_number in this case) is a great way to handle this sort of thing.
ANALYSIS_ID ANALYSIS_DATE   ANALYSIS_YEAR    ANALYSIS_NUMBER
    1         28/12/2015      2015              1
    2         29/12/2015      2015              2
    3         30/12/2015      2015              3
    4         31/12/2015      2015              4
    5         01/01/2016      2016              1
    6         02/01/2016      2016              2
    7         03/01/2016      2016              3

I've ordered by analysis_date, analysis_id in the row_number function. This probably isn't necessary but would be needed if you had to handle updates to the analysis_date (in which case the sequence no longer works for in-year ordering on its own).
You could make this a little more straightforward for reporting by wrapping it in a view:
create or replace view analysis_data_v as
select
    analysis_id,
    analysis_date,
    extract(year from analysis_date) analysis_year,
    row_number()
        over (partition by trunc(analysis_date, 'YYYY')
        order by analysis_date, analysis_id) analysis_number
from
    analysis_data;

This may be all you need, but if you have large data sets then you may need to pre-calculate some of these values. You have virtual columns in 11g, but these don't work for analytic functions. My option here would be to use a materialized view - lots of ways to handle materialized view refreshes and the simplest would be:
create materialized view analysis_data_mv
    build immediate
    refresh complete on demand
as
    select
        analysis_id,
        analysis_date,
        analysis_year,
        analysis_number
    from
        analysis_data_v;

select * from analysis_data_mv order by analysis_year, analysis_number;

ANALYSIS_ID ANALYSIS_DATE   ANALYSIS_YEAR    ANALYSIS_NUMBER
    1         28/12/2015      2015              1
    2         29/12/2015      2015              2
    3         30/12/2015      2015              3
    4         31/12/2015      2015              4
    5         01/01/2016      2016              1
    6         02/01/2016      2016              2
    7         03/01/2016      2016              3

In this case the materialized view would be manually refreshed:
exec dbms_mview.refresh('analysis_data_mv');

Hope this helps.

A: You will probably need a trigger on insert that looks like this (I guess you can't change the value of Year, in that case it will get more complicated).
Like @ibre5041 This won't work on a multi-user enviroment since you could have duplicates if a couple of transactions are executed at the same time on the same year:
CREATE OR REPLACE TRIGGER trg_bi_table1
before insert
ON table_1
Begin
  select nvl(max(value),0)+1 as value
    into :new.value
    from table_1
   where Year = :new.Year;
end;
/

In a multi-user enviroment you should use select for update


text:
Q: Can you hard code an Azure AD login into an application? I'm designing an application that uses embedded Power BI reports that requires an authentication token from an Azure AD account to view the report.
On navigating to the page that holds the report, the user is directed to a Azure AD portal login, and once they enter their credentials they are redirected back to the correct page with a url that contains the access token. The token is then pulled from the url and used in displaying the report.
So my question is (seemingly) simple: Can I skip the navigating to another page and somehow hard code an Azure login into my app?
I'm not sure if this requires any of my code, as it's more of an abstract/general question.
But here is the redirect to the Azure AD login portal:
 Response.Redirect(String.Format("https://login.windows.net/common/oauth2/authorize?{0}", queryString));

And here I fetch the code from the resulting URL after the user authenticates:
model.code = Request.Params.GetValues("code")[0];

A: Yes. AAD supports headless auth. Please see the example here: https://github.com/Azure-Samples/active-directory-dotnet-native-headless.


text:
Q: Asymmetric encryption and Decryption C# I have implemented this code for message encryption with public key and decryption with private key..Now i need to change it encryption with private key and decrypted with public key. What should i change in the following code,i am beginner.please help.
public static string Encrypt(string plainText, X509Certificate2 certificate)
    {
        if (string.IsNullOrEmpty(plainText))
            throw new ArgumentNullException("plainText");

        using (var aesManaged = new AesManaged())
        {
            aesManaged.KeySize = 256;
            aesManaged.BlockSize = 128;
            aesManaged.Mode = CipherMode.CBC;

            // Create the streams used for encryption.
            using (var memoryStream = new MemoryStream())
            {
                // Generate a Symmetric Key used to actually encrypt the data

                RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter((RSACryptoServiceProvider)certificate.PublicKey.Key);
                byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType());

                //byte[] LenSalt = new byte[_saltSize];

                // Create byte arrays to contain
                // the length values of the key and IV.
                byte[] LenK = new byte[_keyBytes];
                byte[] LenIV = new byte[_keyBytes];

                // Salt genration :
                // default iteration count is 1000 in .NET (this is the same as when using Constructor(string password, int salt))
                //using (var keyDerivationFunction = new Rfc2898DeriveBytes(keyEncrypted, LenSalt, _iterations))
                //{
                //    LenSalt = keyDerivationFunction.Salt;
                //}

                int lKey = keyEncrypted.Length;
                LenK = BitConverter.GetBytes(lKey);
                int lIV = aesManaged.IV.Length;
                LenIV = BitConverter.GetBytes(lIV);

                // Write the following to the Stream
                // for the encrypted file (outFs):
                // - length of the key
                // - length of the IV
                // - encrypted key
                // - the IV
                // - the encrypted cipher content
                memoryStream.Write(LenK, 0, 4);
                memoryStream.Write(LenIV, 0, 4);
                //memoryStream.Write(LenSalt, 0, 4);
                memoryStream.Write(keyEncrypted, 0, lKey);
                memoryStream.Write(aesManaged.IV, 0, lIV);
                //memoryStream.Write(LenSalt, 0, _saltSize);

                //using (var encryptor = aesManaged.CreateEncryptor(aesManaged.Key, aesManaged.IV))
                using (var encryptor = aesManaged.CreateEncryptor())
                using (var memoryStreamEnc = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(memoryStreamEnc, encryptor, CryptoStreamMode.Write))
                    using (var streamWriter = new StreamWriter(cryptoStream))
                    {
                        // Send the data through the StreamWriter, through the CryptoStream, to the underlying MemoryStream
                        streamWriter.Write(plainText);
                    }
                    memoryStream.Write(memoryStreamEnc.ToArray(), 0, memoryStreamEnc.ToArray().Length);
                }

                return Convert.ToBase64String(memoryStream.ToArray());

            }
        }
    }

    /// <summary>
    /// Decrypts the ciphertext using the public key.
    /// </summary>
    /// <param name="ciphertext">The ciphertext to decrypt.</param>
    /// <param name="certificate">The RSA certificate (need access to Private Key for decryption to work).</param>
    /// <returns>The decrypted text.</returns>
    public static string Decrypt(string ciphertext, X509Certificate2 certificate)
    {
        string outstring = string.Empty;

        if (string.IsNullOrEmpty(ciphertext))
            throw new ArgumentNullException("cipherText");

        if (!certificate.HasPrivateKey)
            throw new ApplicationException("The private key is not accessible.  Decryption is not supported.");

        var allTheBytes = Convert.FromBase64String(ciphertext);

        //using (var keyDerivationFunction = new Rfc2898DeriveBytes(UTF8Encoding.UTF8.GetString(symmetricKey), saltBytes))
        using (var aesManaged = new AesManaged())
        {

            aesManaged.KeySize = 256;
            aesManaged.BlockSize = 128;
            aesManaged.Mode = CipherMode.CBC;

            // Create byte arrays to get the length of
            // the encrypted key and IV.
            // These values were stored as 4 bytes each
            // at the beginning of the encrypted package.
            byte[] LenK = new byte[_keyBytes];
            byte[] LenIV = new byte[_keyBytes];

            using (MemoryStream InStr = new MemoryStream(allTheBytes))
            {
                InStr.Seek(0, SeekOrigin.Begin);
                InStr.Read(LenK, 0, _keyBytes - 1);
                InStr.Seek(_keyBytes, SeekOrigin.Begin);
                InStr.Read(LenIV, 0, _keyBytes - 1);

                // Convert the lengths to integer values.
                int lenK = BitConverter.ToInt32(LenK, 0);
                int lenIV = BitConverter.ToInt32(LenIV, 0);

                // Determine the start postition of
                // the ciphter text (startC)
                // and its length(lenC).
                int startC = lenK + lenIV + 8;
                int lenC = (int)InStr.Length - startC;

                // Create the byte arrays for
                // the encrypted AesManaged key,
                // the IV, and the cipher text.
                byte[] KeyEncrypted = new byte[lenK];
                byte[] IV = new byte[lenIV];

                // Extract the salt, key and IV
                // starting from index 8
                // after the length values.
                InStr.Seek(8, SeekOrigin.Begin);
                InStr.Read(KeyEncrypted, 0, lenK);
                InStr.Seek(8 + lenK, SeekOrigin.Begin);
                InStr.Read(IV, 0, lenIV);

                byte[] KeyDecrypted = ((RSACryptoServiceProvider)certificate.PrivateKey).Decrypt(KeyEncrypted, false);

                byte[] CipherTextBytes = new byte[lenC];
                InStr.Seek(startC, SeekOrigin.Begin);
                InStr.Read(CipherTextBytes, 0, lenC);

                using (var decryptor = aesManaged.CreateDecryptor(KeyDecrypted, IV))
                using (var memoryStream = new MemoryStream(CipherTextBytes))
                using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream))
                {
                    // Return the decrypted bytes from the decrypting stream.
                    return streamReader.ReadToEnd();
                }
            }
        }
    }


text:
Q: Counting the occurence of a word in a text file using python I copied the code from a tutorial to count the number of occurrences of a word in a text file but for some reason the program miscounts by a lot (it seems to max out at 6).  I have tested it using text from different files but for some reason it is not correctly counting.
This is my code:
search = input("Input your search term: ")
found = 0

with open ("search.txt", 'r') as data:
    for line in data:
        if search.casefold() in line.casefold():
            found += 1

    print(found)

Is the problem with my code?

A: what if you change your code to this:
search = input("Input your search term: ")
found = 0

with open ("search.txt", 'r') as data:
    for line in data:
        if search.casefold() in line.casefold():
            found += line.casefold().count(search.casefold())

    print(found)

Would this make a difference? Your code count only once if the word appears multiple times in a line.


text:
Q: How to inject HttpServletRequest or Session from CDI I have a class that perform as a class producers within my rest services which is so made:
public class WebResources{

    @Produces
    @RequestScoped
    public FacesContext produceFacesContext() {
        return FacesContext.getCurrentInstance();
    }

    @Produces
    public Logger produceLog(InjectionPoint injectionPoint) {
        return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
    }
}

Now I wish to produce an object of mine by using HttpServletRequest or HttpSession as a parameter. Something like this:
@Produces
@RequestScoped
public MyObject getSecurityContext(InjectionPoint injectionPoint)
{
    HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
    return Utils.getMyObject(request);
}

The error I receive on deploy phase is the following:

ERROR [org.jboss.as.cli.CommandContext] {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"zuora.ear\".WeldStartService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"zuora.ear\".WeldStartService: Failed to start service
      Caused by: org.jboss.weld.exceptions.DefinitionException: WELD-001406 Cannot inject [parameter 1] of [method] @Produces @RequestScoped public it.infocert.zuora.rest.util.WebResources.getSecurityContext(InjectionPoint) in a non @Dependent scoped bean"}}
  {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"zuora.ear\".WeldStartService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"zuora.ear\".WeldStartService: Failed to start service
      Caused by: org.jboss.weld.exceptions.DefinitionException: WELD-001406 Cannot inject [parameter 1] of [method] @Produces @RequestScoped public it.info

A: You should remove the InjectionPoint parameter from your method signature. You cannot us InjectionPoint if you are producing a request scoped bean as multiple injection points will get the same (request-scoped) instance. You aren't using the injection point in your code, so it is safe to remove it.


text:
Q: Xml to html using xslt of inspect code of VS Projects I have a an InspectionResults.xml which gets generated when I run inspectcode.exe from JetbrainsCommandLine Tool Analysis. Is there any xslt file provided by the Jetbrains to convert this xml to html. I was able to convert DuplicateReport.xml to html using the xslt provided by them. Does Jetbrains provide one for this conversion. If not please help me out.
My xml file is as follows:
<?xml version="1.0" encoding="utf-8"?>

<Report ToolsVersion="102.0">
<Information>
<Solution>Server\Server.sln</Solution>
<InspectionScope>
 <Element>Solution</Element>
</InspectionScope>
</Information>
<IssueTypes>
<IssueType Id="ArrangeStaticMemberQualifier" Category="Code Style" Description="Add/remove qualifier for static members" Severity="WARNING" />
<IssueType Id="ArrangeThisQualifier" Category="Code Style" Description="Add/remove 'this.' qualifier" Severity="WARNING" />
 <IssueType Id="CSharpErrors" Category="C# Compiler Errors" Description="" Severity="ERROR" />
 </IssueTypes>

  <Issues>
  <Project Name="Common">
  <Issue TypeId="RedundantUsingDirective" File="Common\AdapterAuthorizationException.cs" Offset="15-48" Line="2" Message="Using directive is not required by the code and can be safely removed" />
  <Issue TypeId="RedundantUsingDirective" File="Common\AdapterAuthorizationException.cs" Offset="50-68" Line="3" Message="Using directive is not required by the code and can be safely removed" />
  <Issue TypeId="CSharpErrors" File="Common\AdapterAuthorizationException.cs" Offset="63-67" Line="3" Message="Cannot resolve symbol 'Linq'" />
  </Project>
  </Issues>
  </Report>

A: I have found this inspectcode.xslt that is mentioned in the overview features of the Resharper Command Line Tools, and is working just fine.
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:key name="ISSUETYPES" match="/Report/Issues/Project/Issue" use="@TypeId"/>
  <xsl:output method="html" indent="yes"/>

  <xsl:template match="/" name="TopLevelReport">

        <title>Resharper InspectCode Report</title>

Resharper InspectCode Report

        <xsl:for-each select="/Report/IssueTypes/IssueType">

            <xsl:value-of select="@Severity"/>: <xsl:value-of select="@Description"/>

              File
              Line Number
              Message

            <xsl:for-each select="key('ISSUETYPES',@Id)">

                  <xsl:value-of select="@File"/>

                  <xsl:value-of select="@Line"/>

                  <xsl:value-of select="@Message"/>

            </xsl:for-each>

        </xsl:for-each>

  </xsl:template>
</xsl:stylesheet>

This content was taken from:
https://gist.github.com/maartenba/b7b1866d11a54cf3bc9f04316afa1a9e
The overview of the features is here:
https://www.jetbrains.com/help/resharper/ReSharper_Command_Line_Tools.html
and in that video is where this xslt is mentioned
And in case you need a Tools to apply this XSLT see this question and answers
Are there any XSLT processing command line tools?


text:
Q: communication between java server and javascript I have multithreaded chatting java server which can handle number of clients (java). They can simultaneous talk with each other. They are connected through network socket. Besides their own conversation words, my purpose is to display the conversation words they do in web browser through web application. I am thinking about JavaScript but couldn't figure out how to implement javascript for web application because I will need object or data to pass to javascript side from server( java) side.
Following is the multithreaded server and this works fine with multiple clients.
        public class GoodChatServer {
         ………
public static void main(String[] args) throws Exception {
    System.out.println("The chat server is running.");
    ServerSocket listener = new ServerSocket(PORT);
    try {
        ….
        }
    } finally {
    …..
    }
}
private static class Handler extends Thread {

   ……….
        this.socket = socket;
    }

   public void run() {
        try {

            in = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            while (true) {
                out.println("SUBMITNAME");
                name = in.readLine();
                if (name == null) {
               ..
                }

                synchronized (names) {
                    if (!names.contains(name)) {
                        names.add(name);
                        break;
                    }

A: There are a plethora of ways to display chat information from a Java server in a browser using JavaScript. Since you are already using sockets for your Java clients, one option would be to use WebSockets. Oracle provides an introduction to Java Websockets here, which should help you with the server side of things. Mozilla also has a tutorial for writing browser-based websockets here.
Another option you may consider is to relay your data across global real-time network, such as PubNub. PubNub provides a Java API and JavaScript API which will allow you to publish messages from your Java server to your JavaScript clients, using code such as:
<script src="http://cdn.pubnub.com/pubnub.min.js"></script>
<script>(function(){

var pubnub = PUBNUB.init({
    publish_key   : 'demo',
    subscribe_key : 'demo'
})

pubnub.subscribe({
    channel : "my_chat_channel",
    message : function(m){ alert(m) }, //Display the chat message
})});</script>

On the Java server, you'd write your publish code:
Pubnub pubnub = new Pubnub("demo", "demo");

Callback callback = new Callback() {
    public void successCallback(String channel, Object response) {
        System.out.println(response.toString());
    }
    public void errorCallback(String channel, PubnubError error) {
        System.out.println(error.toString());
    }
};
pubnub.publish("my_chat_channel", "Here is my amazing chat message!" , callback);

PubNub is currently free for up to 1 million messages per month. Good luck!


text:
Q: HostAuthenticationAttribute not found This error has been driving me insane all day. How do I fix it? I've updated NUGET with Microsoft.AspNet.WebApi.Owin but still no luck.
Error   11  The type or namespace name 'HostAuthenticationAttribute' could not be found (are you missing a using directive or an assembly reference?)
Error   12  The type or namespace name 'HostAuthentication' could not be found (are you missing a using directive or an assembly reference?)

// GET api/Account/ExternalLogin
        [OverrideAuthentication]
        **[HostAuthentication**(DefaultAuthenticationTypes.ExternalCookie)]

A: It turns out the packages had different versions and because I had multiple projects in 1 Solutions it wasn't easy to see. Yes can be mundane but recheck everything thrice please and get a second eye sometimes helps.


text:
Q: Open source Test case management tool I am looking for an open source test case management tool.
Is there anything which can take csv / xml / xls files and create test cases for me.

A: Recently found Nitrate\Kiwi, which is written in Python as Django app, may be interesting to take a look at https://github.com/kiwitcms/Kiwi

A: The free community edition of Klaros Testmanagement has support for importing test cases from xls and XML.
It is not open source but free to use and not time or user crippled.
Disclaimer: Being involved in the development I am biased


text:
Q: Logarithmic Liouville Theorem I am studying for a preliminary exam, and the following question has appeared on a previous exam:
Let $f$ be a holomorphic function on $\mathbb{C} \setminus \{ 0\}$. Suppose that for any $z \neq 0$, we have that
$$ |f(z)| \leq |\log (|z|) |.$$
Show that $f(z) \equiv 0$.
I am a bit stuck on how to solve this question. Certainly it is a Liouville like theorem, so the proof should follow like Liouville's proof. To this end, there are a few ideas that might help:
i) We could look at $g(z) = f(1/z)$, which is well defined on $\mathbb{C} \setminus 0$. This doesn't seem too helpful, since $|\log(|z|)| \rightarrow \infty$ as $|z| \rightarrow \infty$ and $|z| \rightarrow 0$.
ii) Expanding $f$ in a power series at $0$ gives $f(z) = \sum_{n=0}^\infty a_n z^n$, so we may use the fact that
$$|a_n| \leq \frac{1}{2 \pi r^n} \int_0^{2\pi} |f(re^{i \theta})| d \theta.$$
Using the bound $|f(z)| \leq |\log (|z|) |$ could show that $a_n =0$ for any $n $, proving that $f(z) \equiv 0$.
I think that the second approach is more promising than the first, but I still need some help putting it all together. Any assistance would be appreciated.

A: Proving it like Liouville (showing that all Laurent series coefficients are zero) or Riemann's theorem on removable singularities would be the standard way, and quite flexible for slight variations in the assumptions. Here there is another way, too: By assumption, $f(z)=0$ for $|z|=1$, so the set of zeros of $f$ contains the whole unit circle. By the uniqueness principle this implies that $f \equiv 0$.

A: We have
$$
 |z f(z) | \le |z| \cdot |\log |z|| \implies \lim_{z \to 0} z f(z) = 0
$$
and Riemann's theorem  implies that $f$ has a removable singularity at $z=0$.
The same argument can be applied to $g(z) = f(1/z)$ to show that $f$ has a removable singularity at $z = \infty$.
So $f$ is (the restriction of) an entire function with a finite limit at  $z = \infty$, and now you can apply Liouville's theorem to conclude that $f$ is constant.
Setting $z=1$ then shows that $f$ is identically zero.


text:
Q: C++ compare two strings bad code I have problem with my code.. i dont know what is wrong.. I need compare two strings. Error message:
error:'outputFile' does not name a type.
I am working with files.. write some text into it... My code for compare:
for (int i = 0; i < size; i++){
            if (PorovnaniKategorie(ArrayOfWorlds[i],"mzda")==true){
//do some code
            }
            }
        }

Function:
bool PorovnaniKategorie(string s1, string s2){
    bool porovnani1=true;
    int vel1 = s1.size();
    int vel2 = s2.size();
if (vel1 == vel2)
                    {
                    for ( int i = 0; i < vel1; i++)
                    {
                        if(tolower(s1[i])!= tolower(s2[i]))
                           porovnani1 = false;
                          }
                    }
else{
    porovnani1 = false;
}
return porovnani1;
}

It is working separately and when i delete for cycle from main function, all is working.. I dont know how to solve this problem..
In fact i need just compare if value at index i compare to "mzda"
edit:
outputFile << "" << endl;  //this line is error
        outputFile << "" << endl;
        outputFile.close();

I dont think  error is here.. (this code is under for). When i delete for all is working

A: Correct one. And please ask in google "std string compare ignore case".
bool PorovnaniKategorie( string s1, string s2 )
{
    if( s1.size() == s2.size() ) {
        for( std::string::size_type i = 0; i < s1.size(); i++ ) {
            if( tolower( s1[i] ) != tolower( s2[i] ) ) {
                return false;
            }
        }
        return true;
    }
    return false;
}


text:
Q: How can I print numbers in my assembly program I have a problem with my assembly program. My assembly compiler is NASM. The source and the outputs are in this picture:

The problem is that I can't print numbers from calculations with the extern C function printf(). How can I do it?
The output should be "Ergebnis: 8" but it isn't correct.

A: In NASM documentation it is pointed that NASM Requires Square Brackets For Memory References. When you write label name without bracket NASM gives its memory address (or offset as it is called sometimes). So, mov eax, val_1 it means that eax register gets val_1's offset. When you add eax, val_2, val_2 offset is added to val_1 offset and you get the result you see.
Write instead:
mov eax, [val_1]
add eax, [val_2]

And you shoul get 8 in eax.
P.S. It seems that you have just switched to NASM from MASM or TASM.
There are a lot of guides for switchers like you. See for example nice tutorials here and here.


text:
Q: How can I start Zookeper and Kafka both at the same time? I wrote a python app that uses Kafka to share data between producer and consumer. I am going to dockerize it and so I wrote the dockerfile. The problem is in the final steps, when I run the Zookeeper server, it says binding to port .... and it never exits, so that it would be possible to run Kafka server also.
FROM  ubuntu:18.04
ADD app.py /

RUN apt-get update -y && apt-get install -y apt-transport-https

RUN  apt-get update \
&& apt-get install -y wget \
&& rm -rf /var/lib/apt/lists/*

RUN apt-get install gzip

RUN  apt-get update \
&& apt-get install -y default-jdk \
&& rm -rf /var/lib/apt/lists/*

RUN wget http://mirrors.estointernet.in/apache/kafka/2.2.0/kafka_2.11-2.2.0.tgz

RUN tar -xvzf kafka_2.11-2.2.0.tgz
RUN cd kafka_2.11-2.2.0 \
&& ./bin/zookeeper-server-start.sh ./config/zookeeper.properties \
&& ./bin/kafka-server-start.sh ./config/server.properties

CMD [ "python", ".app.py"]

A: Typically, you would only need to create a container for your own application. There are already numerous containers available for Kafka and Zookeeper.
A suggestion would be to run a simple Kafka stack using docker compose and then either start your application externally (for instance via command-line or IDE) or create a docker container and run it.

A simple Kafka stack with just Kafka and Zookeeper would require a simple docker-compose file with the following (of course you will need to have docker-compose installed on your system):
version: '3'

services:
  zookeeper:
    image: confluentinc/cp-zookeeper:4.0.0
    restart: unless-stopped
    ports:
      - 2181:2181
    environment:
      ZOOKEEPER_SERVER_ID: 1
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
      ZOOKEEPER_INIT_LIMIT: 5
      ZOOKEEPER_SYNC_LIMIT: 2

  kafka:
    image: confluentinc/cp-kafka:4.0.0-2
    depends_on:
      - zookeeper
    ports:
      - 9092:9092
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
      KAFKA_LOG4J_LOGGERS: "kafka.controller=INFO,kafka.producer.async.DefaultEventHandler=INFO,state.change.logger=INFO"

If you put the above in a file named simple-kafka-stack.yml, you can execute it by running the command:
docker-compose -f simple-kafka-stack.yml up


text:
Q: When does a metric space have "infinite metric dimension"? (Definition of metric dimension)
Definition 1 A subset $B$ of a metric space $(M,d)$ is called a metric basis for $M$ if and only if $$[\forall b \in B,\,d(x,b)=d(y,b)] \implies x = y \,.$$
Definition 2 A metric space $(M,d)$ has "metric dimension" $n \in \mathbb{N}$ if there exists a minimal (in terms of cardinality) metric basis consisting of $n+1$ points. If $M$ does not have metric dimension $n$ for any $n \in \mathbb{N}$, then it has "infinite metric dimension".

Question: What general characteristics or properties of a metric space would automatically force it to have infinite metric dimension? (Perhaps any infinite set with the discrete metric?)
At the very least, are there any straightforward, but perhaps non-representative, examples of metric spaces which obviously must have infinite metric dimension?
(Perhaps unsurprisingly, Euclidean spaces have been shown to have finite metric dimension.)
Note: The definition 1 comes from the paper A Metric Basis Characterization of Euclidean Space by Grattan P. Murphy, Pacific Journal of Mathematics Vol.60, No. 2, 1975. Definition 2 is based on my (possibly faulty) understanding/interpretation of the following results in that paper.

A: As yet another example, there is a metric on the real line which induces the usual topology but is metrically infinite-dimensional.
Simply take the distance function $\rho(x,y) = \min(|x-y|,1)$. For any finite subset of $\mathbb{R}$, all points at Euclidean distance more than $1$ from the subset have the same distance vector $(1,1,\dots,1)$.

A: Let me add two other examples showing that diverse spaces have infinite metric dimension.
First, take any infinite ultrametric space, i.e. such that $d(x,z)\le \min(d(x,y),d(y,z))$ for all $x,y,z$. Knowing the distances to a finite set of points does not give more information than knowing the smallest one of these distances, if this distance is small enough (for concreteness, one can consider the case $X=\{0,1\}^\mathbb{N}$ with the distance $d(x, y) = 2^{i(x,y)}$ where if $x=(x_k), y=(y_k)$ we set $i(x,y)=\min\{k : x_k\neq y_k\}$; then if $S$ is finite subset, leting $\varepsilon$ be the smallest distance between two points of $S$, all points in the ball of radius $\varepsilon$ around any element of $S$ share the same distances to all points of $S$).
Second, consider a regular tree of valence $k\ge 3$, with all edges of length $1$ say. For any point outside the convex hull of a finite subset $S$, the distances to elements of $S$ are entirely determined by the connected component of the complement and the distance to $S$, and distances to $S$ cannot determine the point. Again the space has infinite metric dimension while it has topological and Hausdorff dimension $1$. Note that this example is a length space, but we need infinitely many branching point to ensure infinite-dimensionality.

A:
I'll try to make a couple of remarks. it'll be easier for me to write only a bit at a time.

The metric category of metric spaces and metric maps (i.e. Lipschitz with constant $1$, i.e. never stretching) has a certain rigidity to it so that the idea of a metric base seems attractive. However, I feel that the metric dimension makes sense only for a somewhat limited class of, rather than for all, metric spaces. (Possibly, more than one of several competing definitions can make sense).
Consider (see the Question above):
Property G   A subset $B$ of a metric space $(M,d)$ is called a metric g-set for $M$ if and only if
$$ \forall_{b \in B}\ d(x,b)=d(y,b)\ \ \implies\ \ x = y $$
Every such set $B$ was called a metric basis above. Let $B$ be one, and let $\ B\subseteq C\subseteq M.\ $ Then
$$ \forall_{c \in C}\ d(x,c)=d(y,c)\ \ \implies\ \ x = y $$
Thus, $\ C\ $ has the metric g-set property too. We see that declaring Property G as a definition of metric basis goes against the spirit of basis in general. Instead, Property G corresponds to the general notion of a generating set.

It took quite a long time to arrive at the topological definition of a curve and of the topological dimension (from Cantor's curves in $\ \mathbb R^2,\ $ to Brouwers-Urysohn-Menger, then to the algebraic topological dimensions, etc.).
It took also considerable time to arrive at a general definition of basis which ultimately led to matroids.
In this thread, the topic is rather something like the metric variations of the independent sets and of a basis. Perhaps one should eye matroids for a comparison. These days things go much faster than in the past but the process of obtaining one or more of such sound metric notions may still take some tries and patience.
Thus let's examine the property of a basis, and more generally, of independent sets for matroids: let $X$ be a matroid; then

*

*if $\ A\subseteq X\ $ is an independent set, and $\ b\in X,\ $ then there exists $\ a\in A\ $ such that $\ (A\setminus\{a\})\cup\{b\}\ $ is independent;

*if $\ A\subseteq X\ $ is an independent set (resp.  basis), and  $\ b\in X\ $ depends on $\ A\ $ (resp. $\ b\in X\ $ is arbitrary), then there exists $\ a\in A\ $ such that $\ (A\setminus\{a\})\cup\{b\}\ $ generates the same set as $\ A\ $ (resp. $\ (A\setminus\{a\})\cup\{b\}\ $ is a basis).
Now let's look at some metric spaces.
EXAMPLE 1   Let $\ X:=\{0\ 1\ 2\ 3\},\ $ and let $\ d\ $ be a metric (thus, symmetric, etc) in $\ X,\ $ such that:
\begin{eqnarray}
  d(0\ n) &:=& 2-\frac 1n&\qquad \mbox{for }\ \ n=1\ 2\ 3\\
  d(k\ n) &:=& 2&\qquad \mbox{for every}\ \ 0<k<n\le3
\end{eqnarray}
We see that there is a $1$-element basis $\ \{0\}\ $ in $\ (X\ d)\ $ in the sense of Question while there is no other $1$-element basis. However, in the spirit of matroids (see the above properties 1. and 2.), every $1$-element subset of $X$ should be a basis. Well, this is not so.
ALSO:   Every $2$-element set $\ X\subset\{0\ 1\ 2\}\ $ is a minimal G-set (basis). These three $2$-element sets and $\ \{0\}\ $ are the only minimal G-sets; thus, there are four of them altogether.

Turning to continuous spaces will not help:
EXAMPLE 2   Let $\ X:=[1;\infty)\ $ be a closed half-line, and let $\ d\ $ be a metric (thus, symmetric, etc) in $\ X,\ $ such that:
\begin{eqnarray}
  d(1\ x) &:=& 2-\frac 1x&\qquad \mbox{for every}\ \ x > 1\\
  d(x\ y) &:=& 2&\qquad \mbox{for every}\ \ 1<x<y
\end{eqnarray}
We see that there is a $1$-element basis $\ \{1\}\ $ in $\ (X\ d)\ $ in the sense of Question while there is no other $1$-element basis. Again, in the spirit of matroids, every $1$-element subset of $X$ should be a basis.
Thus, continuity didn't help.
ALSO:   In addition to $\ \{0\},\ $ the only other minimal G-sets are sets $\ X\subset[0;\infty)\ $ such that $\ |[0;\infty)\setminus X|=1$.

CONCLUSION If (a big if) we had to continue with the definition of basis from Question then we would have to restrict the class of the metric spaces under consideration. The first candidate which comes to mind would be the class of transitive space (i.e. such that for every two points there is an isometry of the space onto itself, which sends one of the points onto the other one).

(I might continue later on)

A: Well, if $M$ has a metric basis $\{b_1, \ldots, b_{n+1}\}$ then the map $$x \mapsto (d(x,b_1), \ldots, d(x,b_{n+1}))$$ is a continuous injection from $M$ into $\mathbb{R}^{n+1}$. So, for example, no infinite dimensional Banach space $E$ could have this property for any $n \in \mathbb{N}$: letting $K$ be the closed unit ball of an $n+2$ dimensional subspace of $E$, we restrict to a continuous injection from $K$ into $\mathbb{R}^{n+1}$, which since $K$ is compact must be a homeomorphism, and I think topologists know that an $n+2$ dimensional ball cannot be homeomorphic to a subset of $\mathbb{R}^{n+1}$.

A: Ok, yet another example prompted by previous ones and comments.
Consider $\ell_\infty^2$, the plane with the $\ell_\infty$ metric. Given any finite set $S$, all points on a given vertical line far enough at the right of $S$ have the same distances to all elements of $S$, since only their largest component will matter in the distance. So $\ell_\infty^2$ has infinite metric dimension.

A: Consider $(\mathbf{Z}\times[0,1])/(\mathbf{Z}\times\{0\})$, infinitely many spokes attached at a single point. Given a finite basis, the only points uniquely characterized by distances from it are the points on the same spokes as the basis.  So this space is infinite-dimensional.

A: Having infinite metric dimension is not bi-Lipschitz-invariant.
On the real line, consider the two metrics
$$
d(x,y)=\min(|x-y|,1)\quad\text{and}\\
\delta(x,y)=\arctan(|x-y|).
$$
The two metrics both give the usual topology, they are bi-Lipschitz to each other, but $\dim(\mathbb R,d)=\infty$ (as observed by Benoît Kloeckner) and $\dim(\mathbb R,\delta)=1$ (the $\delta$-distances from any two points uniquely determine the point).
Usually one might argue that if two metric spaces are bi-Lipschitz, they are essentially the same.
However, this does not guarantee that the metric dimensions coincide.
I don't know what would characterize infinite metric dimension, but it has to be "finer than Lipschitz properties" of the metric.
As Benoît Kloeckner's new answer indicates, it does not help if we restrict ourselves to length metrics.
On a tangential end note, consider the metric $d_\epsilon(x,y)=\min(|x-y|,\epsilon)$ on $S^1$ for any $\epsilon>0$.
Here the absolute value can be the metric inherited from $\mathbb R^2$ or $\mathbb R/2\pi\mathbb Z$, it doesn't really matter.
All these are bi-Lipschitz to each other, but the dimension for $d_\epsilon$ is roughly $2\pi/\epsilon$.
You can adjust the metric dimension of $S^1$ to be any positive integer with bi-Lipschitz changes.

A: As Benoit mentioned in one of his answers, ultrametric spaces are a class of metric spaces that can be analyzed, and there is a paper recently put on the arxiv, https://arxiv.org/abs/2003.10239, that carefully investigates when ultrametric spaces have finite metric dimension.
It also cites a considerable amount of literature where this concept appears in graphs with their distance metric.


text:
Q: Adding Facebook Application to a page through API with permissions How to add an application to a page(which I have created) through API with Publish_stream permissions?
Here is the Sequence of things I have tried sofar using app.
Adding App to a page using page access token code is adding app to page apps section but unable to add "publish_stream,manage_pages" permission.
For log in to Facebook
private const string Scope = "publish_stream,manage_pages";
   FacebookClient _fb = new FacebookClient();
   var fbLoginUrl = _fb.GetLoginUrl(
                new
                {
                    client_id = AppId,
                    client_secret = Appsecret,
                    redirect_uri = RedirectUri,
                    response_type = "code",
                    scope = Scope,
                    state = state
                });

To get short lived access token
if (Request.QueryString["code"] != null)
            code = Request.QueryString["code"];
           var result = _fb.Post("oauth/access_token",
                                  new
                                  {
                                      client_id = AppId,
                                      client_secret = Appsecret,
                                      redirect_uri = RedirectUri,
                                      code = code,
                                      scope = Scope,
                                      response_type="token"
                                  });

To get long lived access token
var  result1 = _fb.Post("oauth/access_token",
                              new
                              {
                                  client_id = AppId,
                                  client_secret = Appsecret,
                                  grant_type = "fb_exchange_token",
                                  fb_exchange_token= Session["fb_access_token"] as string
                              });
To get Page access Token
dynamic accounts = _fb.Get("me/accounts");

Add App to a Page using Page Access Token
var sResult = _fb.Post("<PAGE-ID>/tabs",
                                                    new
                                                    {
                                                        app_id = AppId,
                                                        access_token = <PAGE ACCESS TOKEN>,
                                                        scope = Scope
                                                    });

A: It seems from your comments you're trying to post 'as' the app onto a page - this is not possible. You need to post using a page access token retrieved from an admin of the page, and this page access token allows you to make posts on behalf of the page. Apps cannot post 'as themselves'.


text:
Q: Soft keyboard overlaps TextBoxes and makes them unreachable How is it possible to reach an input field within a ScrollViewer when the input field is overlapped by the soft keyboard?
This scenario is easily reproduced:

*

*Create a new page with a ScrollViewer containing some TextBoxes. Make as many TextBoxes as you need until you need to scroll the page to reach the last three TextBoxes.
<ScrollViewer>
  <StackPanel Orientation="Vertical">
    <TextBox Margin="20" />
    <TextBox Margin="20" />
    <TextBox Margin="20" />
    ..
    <TextBox Margin="20" />
    <TextBox Margin="20" />
    <TextBox Margin="20" PlaceholderText="3" />
    <TextBox Margin="20" PlaceholderText="2" />
    <TextBox Margin="20" PlaceholderText="1" />
  </StackPanel>
</ScrollViewer>

*Start the app and tap into "Placeholder 3". The keyboard pops up and overlaps "Paceholder 2" and "Placeholder 1".
How can I improve the layout so I can reach these TextBoxes ("1" and "2") without closing and re-opening the keyboard all the time?
An example that shows a working solution can be found on every WindowsPhone: Settings => VPN => Enable  VPN => Add new profile => Click in any of the TextBoxes and you'll see that you can scroll to every part of the layout although the soft keyboard is up.

A: Been awhile on this question but for others who may be looking for a good solution here is what I did.
Subscribe to the keyboard show and hide events and size the height of the scrollviewer based on when the keyboard is showing or hiding.
Xaml
<ScrollViewer x:Name="scrlvwrKBScroll" VerticalScrollMode="Enabled">
  <StackPanel Orientation="Vertical">
    <TextBox Margin="20" />
    <TextBox Margin="20" />
    <TextBox Margin="20" />
    ..
    <TextBox Margin="20" />
    <TextBox Margin="20" />
    <TextBox Margin="20" PlaceholderText="3" />
    <TextBox Margin="20" PlaceholderText="2" />
    <TextBox Margin="20" PlaceholderText="1" />
  </StackPanel>
</ScrollViewer>

C#
public Constructor()
{
  this.InitializeComponent()
  InputPane.GetForCurrentView().Showing += Keyboard_OnShow;
  InputPane.GetForCurrentView().Hiding += Keyboard_OnHide;
}

private void Keyboard_OnShow(InputPane sender, InputPaneVisibilityEventArgs args)
{
  this.scrllvwrKBScroll.Height = this.ActualHeight - args.OccludedRect.Height - 50;
}

private void Keyboard_OnHide(InputPane sender, InputPaneVisibilityEventArgs args)
{
  this.scrllvwrKBScroll.height = this.ActualHeight;
}

There may be a better way to adjust the height based on the heights of the containers you are using but this is what I used to get my application to work.

A: I also encountered this problem whenever a Page with a BottomAppBar is displaced in the layout from the root visual.  This can be caused by a Margin or Padding on a wrapper element.
Broken visual tree:

*

*Window.Current.Content Frame

*

*Border with 1px Margin

*

*ContentPresenter

*

*Page with BottomAppBar
I could find no "non-disgusting" workaround, but adjusting the offset directly on the root ScrollViewer did work for me.  See UWPMobileScrollIssue for a full repro and workaround.
// ...snip...
namespace UWPFocusTestApp
{
    sealed partial class App : Application
    {
        // ...snip...
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
            // ...snip...
            if (rootFrame == null)
            {
                // ...snip...

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;

                #region WORKAROUND
                if (AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Mobile")
                {
                    InputPane.GetForCurrentView().Showing += InputPane_Showing;
                }
                #endregion
            }

            // ...snip...
        }

        #region WORKAROUND
        private void InputPane_Showing(InputPane sender, InputPaneVisibilityEventArgs args)
        {
            // we only need to hook once
            InputPane.GetForCurrentView().Showing -= InputPane_Showing;

            var frame = (Frame)Window.Current.Content;

            // Find root ScrollViewer
            DependencyObject cNode = frame;
            while (true)
            {
                var parent = VisualTreeHelper.GetParent(cNode);
                if (parent == null)
                {
                    break;
                }
                cNode = parent;
            }
            var rootScrollViewer = (ScrollViewer)cNode;

            // Hook ViewChanged to update scroll offset
            bool hasBeenAdjusted = false;
            rootScrollViewer.ViewChanged += (_1, svargs) =>
            {
                // once the scroll is removed, clear flag
                if (rootScrollViewer.VerticalOffset == 0)
                {
                    hasBeenAdjusted = false;
                    return;
                }
                // if we've already adjusted, bail.
                else if (hasBeenAdjusted)
                {
                    return;
                }

                var appBar = ((Page)frame.Content)?.BottomAppBar;
                if (appBar == null)
                {
                    return;
                }

                hasBeenAdjusted = true;
                rootScrollViewer.ChangeView(null, rootScrollViewer.VerticalOffset + appBar.ActualHeight, null);
            };
        }
        #endregion

        // ...snip...
    }
}


text:
Q: SQL oracle - update one column based on multie condition I want to update a records based on multiple condition. My update ignores conditions (and updates for all records where doctype = 7).
UPDATE DOCUMENTS SET DOCTYPE = '2'
Where DOCTYPE IN (Select C.DOCTYPE
From
    CLIENTS A,
    AGREEMENTS B,
    DOCUMENTS C
where
    A.ID = B.CUSTOMERID
    and B.ID = C.AGREEMENTID
    and C.STATUS = 1
    and B.STATUS = 1
    and A.STATUS = 1
    and C.DOCTYPE = '7')

But select on itself returns what i want. What i did wrong in update?

A: You need to filter based on Documents.ID , try like below:
UPDATE DOCUMENTS SET DOCTYPE = '2'
Where ID IN (Select C.ID
From
    CLIENTS A,
    AGREEMENTS B,
    DOCUMENTS C
where
    A.ID = B.CUSTOMERID
    and B.ID = C.AGREEMENTID
    and C.STATUS = 1
    and B.STATUS = 1
    and A.STATUS = 1
    and C.DOCTYPE = '7')

A: You also need to co-relate your target table "DOCUMENTS" with sub-query. Try below and check it, hopefully, solves your issues.
UPDATE DOCUMENTS S SET DOCTYPE = '2'
Where (DOCTYPE,AGREEMENTID) IN (Select C.DOCTYPE,C.AGREEMENTID
From
    CLIENTS A,
    AGREEMENTS B,
    DOCUMENTS C
where
    A.ID = B.CUSTOMERID
    and B.ID = C.AGREEMENTID
    and C.STATUS = 1
    and B.STATUS = 1
    and A.STATUS = 1
    and C.DOCTYPE = '7')
and S.STATUS = 1
and S.DOCTYPE = '7'


text:
Q: How to get rid of unwanted line - multiple table of contents in "report" class using titletoc package I'm writing my thesis, and have stumbled upon a problem, I don't know how to fix.
I want two tables of contents - one for the actual thesis and one just before the appendix.
As the headline says, I'm writing in the report class with a separate file for each chapter of the thesis.
I have managed to get overleaf to create the two tables of contents that I want, but for some reason the first ends with a 'fun' line of the appendix content, while the last appendix table on contents starts with a line referencing to a bunch of chapters and sections. It's a little hard to explain - so I have attached some pictures - I have marked the unwanted lines with a red oval-thingy.
How can I get rid of these lines?

I have tried \startcontents and `\stopcontents`` without any changes happening.
Here is the code (since it is long document, I have narrowed it down to just a few chapters for exemplification):
\documentclass[a4paper, 12pt]{report}

%%%%%%%%%%%%
% Packages %
%%%%%%%%%%%%

\usepackage[danish]{babel}
\usepackage[noheader]{packages/sleek}
\usepackage{packages/sleek-title}
\usepackage{packages/sleek-theorems}
\usepackage{packages/sleek-listings}
\usepackage{subfiles}
\usepackage{pdfpages}
\usepackage{booktabs}
\usepackage[utf8]{inputenc}
\usepackage{tabularx}
\usepackage{float}
\usepackage{comment}
\usepackage{biblatex}
\usepackage{titletoc}
\usepackage[utf8]{inputenc}
\usepackage{fancyhdr}
\usepackage{lastpage}
\usepackage{etoolbox}
\usepackage{lipsum}

%%%%%%%%%%%%
% Document %
%%%%%%%%%%%%

\begin{document}
\setcounter{secnumdepth}{3} % default value for 'report' class is "2"
\maketitle
\pagenumbering{Roman}
\chapter*{Summary}

\startcontents[main]
\printcontents[main]{}{-1}{\chapter*{Indholdsfortegnelse}}
%\romantableofcontents %commented out since it provides the full table of content including all chapters and sections of appendix - which is not wanted %
\chapter{Introduktion}
\pagestyle{fancy}
\fancyhf{}
\rfoot{Side \thepage \hspace{1pt} af \pageref{LastPage}}
\pagenumbering{arabic}
\lipsum[1]
\chapter{Litteraturreview}
\lipsum[]
\chapter{Afhandlingens teorivalg}
\lipsum[]

\stopcontents[main]
\cleardoublepage
%%%%%%%%%%%%
% Appendix %
%%%%%%%%%%%%

\appendix

\chapter*{Bilagsoversigt}

\startcontents[bilag]
\printcontents[bilag]{}{-1}{}

\chapter{Interviewguides}
\lipsum[]

\chapter{Operationalisering af spørgeskema}
\lipsum[]
\section{SurveyXact spørgeskemaet}
\lipsum[]

\chapter{Kvalitativ analyse}
\section{Totaloversigt over NVivo koder}

\stopcontents[bilag]

\end{document}

I think the problem is something in the correlation between the sleek-packages and the titletoc, since the line doesn't show, if I remove the sleek-packages. But then I don't have the wished design of the document. So I seek a solution, where I can keep the sleek-packages for the document style.
If it's possible to get the first table of content (main document) to also contain the appendix-chapters (but not sections), that would be very nice.
If something needs to be elaborated please don't hesitate to tell me so, this is my first time posting a question - since the thesis is my first time working with overleaf.
Have a nice day and thanks in advance for any help :).

A: It all comes down to https://da.overleaf.com/latex/templates/sleek-template/hrksrrdywhfk being a sub optimal template, or at least not explaining it self very well.
\usepackage[noheader]{packages/sleek}

loads a lot of packages, including several the OP is also loading later on. Included in this OPs list if titletoc but packages/sleek  autoloads hyperref and we all know that with a few exceptions hyperref should always be loaded last. Is hyperref last in packages/sleek? nope, but it did not end in catastrophe.
The issue here seems to be titletoc being loaded after hyperref. If we move all the OPs packages up above the sleek packages (and remove biblatex as sleek loads it), the project seems to at least compile without error.
That is, this seems to help
\usepackage{subfiles}
\usepackage{pdfpages}
\usepackage{booktabs}
% \usepackage[utf8]{inputenc} % sleek
\usepackage{tabularx}
\usepackage{float}
\usepackage{comment}
% \usepackage{biblatex} % sleek
\usepackage{titletoc}
% \usepackage[utf8]{inputenc}
\usepackage{fancyhdr}
\usepackage{lastpage}
\usepackage{etoolbox}
\usepackage{lipsum}
\usepackage[danish]{babel}
\usepackage[noheader]{packages/sleek}
\usepackage{packages/sleek-title}
\usepackage{packages/sleek-theorems}
\usepackage{packages/sleek-listings}


text:
Q: Optimization of Complex Functions, No Use? During reading the appendix to an engineering text, I came across the following remark:
"Complex cost functions are of no interest, because in the field of complex numbers
no ordering (relations < and >) is defined and thus minimization or maximization
makes no sense."
Anyone care to explain this observation, why does minimization not make sense in complex domain?

A: Suppose you have a function $f\colon: \mathbb{R} \to \mathbb{C}$ and you want to minimize this function. Then you have to find an argument $x$ such that $f(x)$ is minimal which means that $f(x) \leq f(y)$ for all $y \in \mathbb{R}$. The problem is that $\mathbb{C}$ does not have a natural ordering like $\mathbb{R}$. If you have two complex numbers $a, b \in \mathbb{C}$, you can not say that $a \leq b$ or $b \leq a$.
Of course, you can minimize the absolute value $|f(x)|$ but this might be not that what you want and this is also not a complex valued function any more.


text:
Q: grub error "superfluous RAID member" on update-grub My system (wheezy/sid: 2.6.32-5-amd64 #1 SMP x86_64 GNU/Linux) is running fine - I'm just wondering what some messages mean.
I have two mdraid arrays running up on my system. Here's cat /proc/mdstat:
Personalities : [raid1] [raid6] [raid5] [raid4]
md1 : active (auto-read-only) raid5 sda3[0] sdc3[3] sdb3[1]
      823103488 blocks super 1.2 level 5, 512k chunk, algorithm 2 [3/3] [UUU]

md0 : active raid1 sda2[0] sdc2[2](S) sdb2[1]
      72628769 blocks super 1.2 [2/2] [UU]

I use /dev/md0 as / and /dev/md1 as /home.
Whenever update-grup is running - or while grub comes up, I receive the error:
error: superfluous RAID member (2 found)..
To understand why I'd like to remove this, have a look at the result of update-grub:
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
Generating grub.cfg ...
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
Found background image: /usr/share/images/desktop-base/desktop-grub.png
error: superfluous RAID member (2 found).
Found linux image: /boot/vmlinuz-2.6.32-5-amd64
Found initrd image: /boot/initrd.img-2.6.32-5-amd64
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
error: superfluous RAID member (2 found).
  No volume groups found
done

How can I get rid of these messages?

A: This is a bug on the update-grub script. After what is said in the Debian bug report, a patch has been applied upstream so it should be fixed in the Debian package at some time.


text:
Q: call a function in a python source code in jupyter notebook I have this in my python file (called myLib.py)
def add(x, y):
    return x + y

and in my jupeter notebook I have this code:
import myLib as myLib
y=myLib.add(1,2)
print(y)

when I run the jupyter cell,I m getting this error:
AttributeError                            Traceback (most recent call last)
<ipython-input-10-9b942a9ce18f> in <module>
      1 import myLib as myLib
----> 2 y=myLib.add(1,2)
      3 print(y)

AttributeError: module 'myLib' has no attribute 'add'

I am using visual studio
What is the problem and how I can fix it?


text:
Q: Error in MySQL Syntax; Problems Creating a Table and decimal(19,4) & bigint Datatypes First of all, I'm very new to MySQL.  I'm trying to create a table to store (historical) financial pricing data as part of an algorithmic trading system I'm developing.
So far, I have created 3 other tables with ease.  However, for this 4th table (daily_price), I have come up against issues.  These issues I feel, seem to arise around the use of the decimal(19,4) and bigint data types.
My code is found below.  I've had a look around online and books etc, but my problem seems quite unique.  Any help or advice is greatly appreciated! Matt
CREATE TABLE daily_price
(id INT NOT NULL AUTO_INCREMENT,
data_vendor_id INT NOT NULL,
symbol_id INT NOT NULL,
price_date datetime NOT NULL,
created_date datetime NOT NULL,
last_updated_date datetime NOT NULL,
open_price decimal(19,2) NULL,
high_price decimal(19,4) NULL,
adj_close_price decimal(19,4) NULL,
volume bigint NULL, PRIMARY KEY (id),
KEY index_data_vendor (data_vendor_id),
KEY index_symbol_id (symbol_id))
ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;