Saturday, September 25, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Failing to build pyhdf

Posted: 25 Sep 2021 08:13 AM PDT

I have been trying to install pyhdf however I get this error message which I can't seem to find the solution to.

ERROR: Command errored out with exit status 1:     command: /project/InSAR/user1/venv/test/bin/python /project/InSAR/user1/venv/test/lib/python3.7/site-packages/pip/_vendor/pep517/in_process/_in_process.py build_wheel /tmp/tmpwm9u6ko8         cwd: /tmp/pip-install-s90teiwu/pyhdf_0b2593bd32224d91a63b3304860de144    Complete output (40 lines):    running bdist_wheel    running build    running config_cc    unifing config_cc, config, build_clib, build_ext, build commands --compiler options    running config_fc    unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options    running build_src    build_src    building extension "pyhdf._hdfext" sources    build_src: building npy-pkg config files    running build_py    creating build    creating build/lib.linux-x86_64-3.7    creating build/lib.linux-x86_64-3.7/pyhdf    copying pyhdf/__init__.py -> build/lib.linux-x86_64-3.7/pyhdf    copying pyhdf/six.py -> build/lib.linux-x86_64-3.7/pyhdf    copying pyhdf/V.py -> build/lib.linux-x86_64-3.7/pyhdf    copying pyhdf/VS.py -> build/lib.linux-x86_64-3.7/pyhdf    copying pyhdf/test_SD.py -> build/lib.linux-x86_64-3.7/pyhdf    copying pyhdf/error.py -> build/lib.linux-x86_64-3.7/pyhdf    copying pyhdf/HDF.py -> build/lib.linux-x86_64-3.7/pyhdf    copying pyhdf/SD.py -> build/lib.linux-x86_64-3.7/pyhdf    copying pyhdf/HC.py -> build/lib.linux-x86_64-3.7/pyhdf    copying pyhdf/hdfext.py -> build/lib.linux-x86_64-3.7/pyhdf    running build_ext    customize UnixCCompiler    customize UnixCCompiler using build_ext    building 'pyhdf._hdfext' extension    compiling C sources    C compiler: gcc -pthread -DNDEBUG -g -fwrapv -O3 -Wall -I/usr/local/hdf5/1.8.14/include -I/usr/local/gcc/4.9.3/include -I/usr/local/mpfr/3.1.4/include -I/usr/local/gmp/5.1.3/include -I/usr/local/proj/4.9.1/include -I/usr/local/geos/3.5.0/include -I/usr/local/python/3.7.2/include -I/usr/local/sqlite/3080802/include -I/usr/local/python/2.7.9/include -I/usr/local/zlib/1.2.8/include -I/usr/local/hdf5/1.8.14/include -I/usr/local/gcc/4.9.3/include -I/usr/local/mpc/1.0.3/include -I/usr/local/mpfr/3.1.4/include -I/usr/local/gmp/5.1.3/include -I/usr/local/proj/4.9.1/include -I/usr/local/geos/3.5.0/include -I/usr/local/python/3.7.2/include -I/usr/local/sqlite/3080802/include -I/usr/local/python/2.7.9/include -I/usr/local/zlib/1.2.8/include -fPIC      creating build/temp.linux-x86_64-3.7/pyhdf    compile options: '-I/usr/local/python/3.7.2/lib/python3.7/site-packages/numpy/core/include -I/project/InSAR/user1/venv/test/include -I/usr/local/python/3.7.2/include/python3.7m -c'    extra options: '-DNOSZIP'    gcc: pyhdf/hdfext_wrap.c    pyhdf/hdfext_wrap.c:3681:17: fatal error: hdf.h: No such file or directory     #include "hdf.h"                     ^    compilation terminated.    error: Command "gcc -pthread -DNDEBUG -g -fwrapv -O3 -Wall -I/usr/local/hdf5/1.8.14/include -I/usr/local/gcc/4.9.3/include -I/usr/local/mpfr/3.1.4/include -I/usr/local/gmp/5.1.3/include -I/usr/local/proj/4.9.1/include -I/usr/local/geos/3.5.0/include -I/usr/local/python/3.7.2/include -I/usr/local/sqlite/3080802/include -I/usr/local/python/2.7.9/include -I/usr/local/zlib/1.2.8/include -I/usr/local/hdf5/1.8.14/include -I/usr/local/gcc/4.9.3/include -I/usr/local/mpc/1.0.3/include -I/usr/local/mpfr/3.1.4/include -I/usr/local/gmp/5.1.3/include -I/usr/local/proj/4.9.1/include -I/usr/local/geos/3.5.0/include -I/usr/local/python/3.7.2/include -I/usr/local/sqlite/3080802/include -I/usr/local/python/2.7.9/include -I/usr/local/zlib/1.2.8/include -fPIC -I/usr/local/python/3.7.2/lib/python3.7/site-packages/numpy/core/include -I/project/InSAR/user1/venv/test/include -I/usr/local/python/3.7.2/include/python3.7m -c pyhdf/hdfext_wrap.c -o build/temp.linux-x86_64-3.7/pyhdf/hdfext_wrap.o -MMD -MF build/temp.linux-x86_64-3.7/pyhdf/hdfext_wrap.o.d -DNOSZIP" failed with exit status 1    ----------------------------------------    ERROR: Failed building wheel for pyhdf  Failed to build pyhdf  ERROR: Could not build wheels for pyhdf which use PEP 517 and cannot be installed directly  

I cannot interpret what the paragraph before the dashed line means. The methods that I have tried include upgrading pip, upgrading pip setuptools wheel, installing PEP517. Any help would be greatly appreciated!

Thank you!

How to authenticate with Routes in React.js

Posted: 25 Sep 2021 08:13 AM PDT

I use this method to show private pages to the user. The problem is that no page is displayed to me, but the logs that I put in PrivatePage work properly.

Components are correct because when I simply call the routes, the components are returned correctly but it has a problem with PrivatePage and does nothing.

function Auth() {      return new Promise((resolve, reject) => {          let appData = GetAppData();          if (appData.UserToken.length == 0) {              reject(-2);          }        let request = {          Token: appData.UserToken,          UserId: appData.UserId      }        axios.post("****UserValidUrl****", request).then(response => {          switch (response.data.Type) {              case 10:                  resolve(10);                  break;              case -2:                  reject(-2);                  break;              case -13:                  reject(-13);          }      }).catch(err => {          reject(-13);      })  })  }    const PrivatePage = ({render, ...props}) => (       <Route {...props} render={(props) => {          Auth().then(resolve => {              Log("Pr OK" + resolve);              return render(props);          }).catch(reject => {              Log("Pr No" + reject);              return <Redirect to={"/Auth/Login"}/>          })      }}/>  )    export default function BasePage() {      return (          <div>              <BrowserRouter>                  <Switch>                      <Route exact path={"/Auth/Login"} component={Login}/>                      <PrivatePage path={"/"} render={() =>                          <Switch>                              <Route exact path={"/"} component={Home}/>                              <Route exact path={"/Dashboard/Home"} component={Home}/>                              <Route component={NotFound}/>                          </Switch>                      }/>                  </Switch>              </BrowserRouter>          </div>      );  }  

How to Consume Message from Azure Service Bus topics automatically

Posted: 25 Sep 2021 08:13 AM PDT

I am a newbie to Azure Service Bus. I want to make an application which will consume message from azure service bus subscription whenever a new message arrives and do some logics. The sample codes and tutorials are showing how to hit the application through a REST controller and consume the message or some tutorials are showing to call the consumer function from mail class which is only reading one message. I don't want to use any controller, application should read message and do stuff on it's own. Not able find any samples to get started. I am using JAVA.

UIImage(named: ) returns nil in cocoapod library on ios 12.4-5

Posted: 25 Sep 2021 08:12 AM PDT

I have my Cocoapod library, In this library I access my images this way:

let bundle = Bundle(identifier: "com.mylib.mylib")  let image = UIImage(named: "image_name", in: bundle, compatibleWith: nil)  

This works perfectly on devices 14.0 and above, but in IOS 12.4 this always returns the nil. I tried other way to get bundle like this: let bundle = Bundle(for: type(of: self)) result is same.

Interesting is that when I import library in project, from library project (as source code), it works without problem (on 12.4).

but when I try to import library from pod, it returns nil (only on 12.4). Also images from main bundle is not problem, it can display main bundle icons in my library. I'm out of ideas of what can be the case..

MoveWindow does not scale the window when moving to a different screen

Posted: 25 Sep 2021 08:12 AM PDT

I have a Windows application with floating windows that I am running on a multi-monitor setup (FHD, 4K). The application is marked as system-aware, so we pick the current DPI value for the primary monitor and scale according to that. After that the OS bitmap-scales it. The application is running on Windows 10.

Now when one of the floating window is dragged to another monitor then the OS bitmap scales it automatically an it all works fine. The problem is that we have some windows without a title bar and we have code to move those windows by dragging from the client area of the window. When the mouse is released, we call MoveWindow API to move the window to target location. This works fine on a single monitor but when we drop the window on a different monitor then it does not bitmap scale seems to lose its drop location. The OS only seems to bitmap-scale when we drag a window by its title bar and not when it is moved programmatically. Any ideas on how this automatic scaling can be achieved when moving a window programmatically?

Subtracting two sums

Posted: 25 Sep 2021 08:12 AM PDT

Please suppose this DB fiddle.

-- INVENTORY TABLE DECLARATION AND DATA INSERTION  DECLARE @COLORSIZEQTYS TABLE(ITEID int, COLORCODE varchar(15), QTYMODE smallint, SIZE4 float, SIZE5 float, SIZE6 float, SIZE7 float);    INSERT @COLORSIZEQTYS(ITEID, COLORCODE, QTYMODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(5594, 'Grey',  1, -2, -1,  3,  4);  INSERT @COLORSIZEQTYS(ITEID, COLORCODE, QTYMODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(5594, 'Red',   1,  2,  5,  5,  2);  INSERT @COLORSIZEQTYS(ITEID, COLORCODE, QTYMODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(5594, 'Green', 1,  2,  2,  4, -1);  INSERT @COLORSIZEQTYS(ITEID, COLORCODE, QTYMODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(5594, 'Grey',  0,  2,  0, -1,  1);  INSERT @COLORSIZEQTYS(ITEID, COLORCODE, QTYMODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(5594, 'White', 0,  2,  3,  3,  0);  INSERT @COLORSIZEQTYS(ITEID, COLORCODE, QTYMODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(5594, 'Blue',  1, -1,  6,  0,  3);  INSERT @COLORSIZEQTYS(ITEID, COLORCODE, QTYMODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(5594, 'Grey',  1,  7,  2, -1,  4);  INSERT @COLORSIZEQTYS(ITEID, COLORCODE, QTYMODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(5594, 'Grey',  1,  1,  0, -1, -1);    -- PURCHASES TABLE DECLARATION AND DATA INSERTION  DECLARE @STORECOLORSIZEEST TABLE(ID int, ITEID int, COLORCODE varchar(15), SIZE4 float, SIZE5 float, SIZE6 float, SIZE7 float);    INSERT @STORECOLORSIZEEST(ID, ITEID, COLORCODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(1703, 5594, 'Grey', 0, 1, 0, 1);  INSERT @STORECOLORSIZEEST(ID, ITEID, COLORCODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(1704, 6811, 'Red',  0, 1, 0, 1);  INSERT @STORECOLORSIZEEST(ID, ITEID, COLORCODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(1706, 5594, 'Grey', 0, 1, 1, 1);  INSERT @STORECOLORSIZEEST(ID, ITEID, COLORCODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(1707, 5594, 'Grey', 1, 1, 0, 1);  INSERT @STORECOLORSIZEEST(ID, ITEID, COLORCODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(1709, 8372, 'Blue', 0, 1, 0, 1);  INSERT @STORECOLORSIZEEST(ID, ITEID, COLORCODE, SIZE4, SIZE5, SIZE6, SIZE7) VALUES(1712, 5594, 'Grey', 0, 0, 1, 1);    -- QUERY SUMMING INVENTORY ROWS  SELECT SUM(SIZE4) AS QTY4,         SUM(SIZE5) AS QTY5,         SUM(SIZE6) AS QTY6,         SUM(SIZE7) AS QTY7  FROM @COLORSIZEQTYS  WHERE ITEID = 5594  AND COLORCODE = 'Grey'  AND QTYMODE = 1    -- QUERY SUMMING INVENTORY ROWS AND ZERO-ING NEGATIVE VALUES  SELECT SUM(CASE WHEN SIZE4 < 0 THEN 0 ELSE SIZE4 END) AS QTY4,         SUM(CASE WHEN SIZE5 < 0 THEN 0 ELSE SIZE5 END) AS QTY5,         SUM(CASE WHEN SIZE6 < 0 THEN 0 ELSE SIZE6 END) AS QTY6,         SUM(CASE WHEN SIZE7 < 0 THEN 0 ELSE SIZE7 END) AS QTY7  FROM @COLORSIZEQTYS  WHERE ITEID = 5594  AND COLORCODE = 'Grey'  AND QTYMODE = 1    -- QUERY SUMMING PURCHASE ROWS  SELECT SUM(SIZE4) AS RSV4,         SUM(SIZE5) AS RSV5,         SUM(SIZE6) AS RSV6,         SUM(SIZE7) AS RSV7  FROM @STORECOLORSIZEEST  WHERE ITEID = 5594  AND COLORCODE = 'Grey'    -- SUBTRACTING THE TWO SUMS TO FIND THE FINAL INVENTORY QUANTITIES - CLEARLY THIS DOESN'T WORK  SELECT (SUM(CASE WHEN inv.SIZE4 < 0 THEN 0 ELSE inv.SIZE4 END) - SUM(pcs.SIZE4)) AS TOT4,         (SUM(CASE WHEN inv.SIZE5 < 0 THEN 0 ELSE inv.SIZE5 END) - SUM(pcs.SIZE5)) AS TOT5,         (SUM(CASE WHEN inv.SIZE6 < 0 THEN 0 ELSE inv.SIZE6 END) - SUM(pcs.SIZE6)) AS TOT6,         (SUM(CASE WHEN inv.SIZE7 < 0 THEN 0 ELSE inv.SIZE7 END) - SUM(pcs.SIZE7)) AS TOT7  FROM @COLORSIZEQTYS AS inv  INNER JOIN @STORECOLORSIZEEST AS pcs ON pcs.ITEID = inv.ITEID AND pcs.COLORCODE = inv.COLORCODE  WHERE inv.ITEID = 5594 AND inv.COLORCODE = 'Grey' AND inv.QTYMODE = 1  

So I have two tables, one is an inventory of products with their quantities for each size, and the other is purchase lines of products with the purchased quantities of each size.

I want to calculate the final new inventory quantities of each size, zero-ing the over-sold sizes (this over-selling happens some times because the operator of the system fails to register some sales).

Anyway, for the fiddle's example, the totals should literally be like

TOT4 TOT5 TOT6 TOT7
7 -1 1 4

and after we zero the over-sold ones, they should become

TOT4 TOT5 TOT6 TOT7
7 0 1 4

In my fiddle I've attempted to calculate the subtraction of the two sums, but I don't know what I've dome wrong, as it calculates totally different results! I know I'm close, but I can't make it work.

Can someone correct the final query for me? Thanks in advance.

Summing multiple rows in data.tableand producing a new row in the same data.table

Posted: 25 Sep 2021 08:12 AM PDT

please help me if you have time,

i have a larger data.table , 1250 rows by 60 columns

and i need to add 100 rows together , adding together row values in each of the 60 columns, and producing a new row(with 60 columns), which would be part of the data.table

and i need to do this 10 times, so it would take a long time if not automated

i looked at the data.table manuals, and i saw usage of the keys, which i could use as the rows are periodically numbered (1-100), but i did not find how to use keys or summing

Thank you a lot

How to return null for a character returning method in java?

Posted: 25 Sep 2021 08:14 AM PDT

import java.util.*;    char[] characterArray1 = {'D', 'B', 'C', 'A', 'B', 'A'};  char[] characterArray2 = {'D', 'B', 'C', 'A', 'E', 'T'};  System.out.println(FRC(characterArray2));    public static char FRC(char[] array) {          HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();          for(char character: array) {                  if(hashMap.containsKey(character)) {                          return character;                  }else {                          hashMap.put(character, 1);                  }          }return null  }  

characterArray1 is able to return character 'B' as it is the first recurring character

So how am I able to return null from a character returning method when I use characterArray2 as the argument?

React JS: nested JSON / JSON arrays - updating value on a single property

Posted: 25 Sep 2021 08:12 AM PDT

I'm trying to make a function that will be called on click and update the value of a property inside local JSON file. It should only update the value of the clicked property and not others; but I don't even know where to start with this one.

JSON file:

{      "firstyear": {          "passed": [{ "name": "English", "points": 0 }, { "name": "History", "points": 0 }],          "failed": [{ "name": "Chemistry", "points": 0 }, { "name": "Agrictulture", "points": 0 }]      },      "secondyear": {          "passed": [{ "name": "Medicine", "points": 0 }, { "name": "Arts", "points": 0 }],          "failed": [{ "name": "Gym", "points": 0 }, { "name": "German", "points": 0 }]      },      "thirdyear": {          "passed": [{ "name": "Math", "points": 0 }, { "name": "Informatics", "points": 0 }],          "failed": [{ "name": "French", "points": 0 }, { "name": "Economics", "points": 0 }]      },      "fourthyear": {          "passed": [{ "name": "Litretarue", "points": 0 }, { "name": "Philosophy", "points": 0 }],          "failed": [{ "name": "Politics", "points": 0 }, { "name": "Gardening", "points": 0 }]      }  }  

Component that renders all names, points and adds buttons:

import {fetchAll} from '../AppFetch';  import {useEffect, useState} from 'react';    export default function Subjects() {        const [data, setData] = useState({});              useEffect(( ) => {        fetchAll("http://localhost:3000/example.json", setData)      }, []);        const failedanim = [];      const passedanim = [];        for(let i=0; i<Object.entries(data).length; i++){        const years = Object.entries(data)[i][0];        const status = Object.values(data)[i];            for(let j=0; j < Object.keys(status).length; j++){          const failed=Object.entries(status)[1][1]          const passed=Object.entries(status)[0][1]          failedanim.push(            <div className="item" key={failed[j]?.name}>              <button>&#8679;</button>              <p >{failed[j]?.name} ( {failed[j]?.points} )</p>              <button>&#8681;</button>            </div>          )          passedanim.push(            <div className="vote" key={passed[j]?.name}>              <button>&#8679;</button>              <p>{passed[j]?.name} ( {passed[j]?.points} )</p>              <button>&#8681;</button>            </div>          )        }      }      return <div className="row">        <div className="failed"><h1>failed</h1>{failedanim}</div>        <div className="passed"><h1>passed</h1>{passedanim}</div>      </div>;  }  

Please help.

Convert roman to integer - Python [duplicate]

Posted: 25 Sep 2021 08:14 AM PDT

I've tried the following Python 3 code that transform from Roman to Integer.

The code is working fine. But there is a problem happened when I input an integer number or string (ex: 1, 2 or any integer number, string) it shows the message "Invalid input! Try again!" and the program ends. I want if the program input is valid it will end but if the input is invalid the input message should continue till its become a valid input.

Here is my code:

class Solution(object):     def roman_to_int(self, s):        """        :type s: str        :rtype: int        """        roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}        i = 0        num = 0        while i < len(s):           if i+1<len(s) and s[i:i+2] in roman:              num+=roman[s[i:i+2]]              i+=2           else:              #print(i)              num+=roman[s[i]]              i+=1        return num  ob1 = Solution()    message = str(input("Please enter your roman number: "))  try:      n = ob1.roman_to_int(message)      if n > 3999: raise Exception()      print(n)  except Exception:      print("Invalid input! Try again!")  

Trouble registering a GenServer with a via tuple. ** (UndefinedFunctionError) function PokerServer.whereis_name/1 is undefined or private)

Posted: 25 Sep 2021 08:13 AM PDT

Here's a very simple GenServer. I am trying to register it on initialization using a via tuple.

defmodule PokerServer do    use GenServer      def start(id) do      GenServer.start(__MODULE__, id, name: {:via, __MODULE__, id})    end      @impl GenServer    def init(id) do      {:ok, id}    end  end  

Unless I missunderstood something in the documentation, I should be able to pass the via tuple as a name in the third argument of GenServer.start/3

Except that when I try to start the process in the iex shell, I trigger an error

iex(1)> PokerServer.start(123)  ** (UndefinedFunctionError) function PokerServer.whereis_name/1 is undefined or private  (live_draft 0.1.0) PokerServer.whereis_name(123)  (stdlib 3.14.2.2) gen.erl:83: :gen.start/6  

EDIT: I use elixir 1.12.3 and erlang/OTP 23

How to validate a complex nested data structure with Pydantic?

Posted: 25 Sep 2021 08:13 AM PDT

I had complex and nested data structure like below:

{   0: {   0: {'S': 'str1', 'T': 4, 'V': 0x3ff},             1: {'S': 'str2', 'T': 5, 'V': 0x2ff}},      1: {   0: {'S': 'str3', 'T': 8, 'V': 0x1ff},             1: {'S': 'str4', 'T': 7, 'V': 0x0ff}},  ......  }  

It's a 2D dictionary basically. The innermost dict follows {Str: str, str:int, str:int}, while its outer dict always has integer as the key to index.

Is there a way for Pydantic to validate the data-type and data structure? I mean if someone changes the data with a string as a key to the outer dict, the code should prompt an error. Or if someones tweaks the inner dict with putting 'V' value to a string, a checker needs to complain about it.

I am new to Pydantic, and found it always requires a str-type field for any data... Any ideas?

BeautifulSoup fails to tag HTML correctly

Posted: 25 Sep 2021 08:12 AM PDT

I'm using BeautifulSoup to parse a simple HTML table. Due to some inconsistency in the data BeautifulSoup seems to fail parsing and tagging the content correctly. Here is the code:

import requests  from bs4 import BeautifulSoup  page = 1  city = 'vantaa'.capitalize()  URL = 'https://asuntojen.hintatiedot.fi/haku/?cr=1&t=3&l=0&search=1&sf=0&so=a&renderType=renderTypeTable&print=1&z={}&c={}'.format(page, city)  page = requests.get(URL)  soup = BeautifulSoup(page.content, "html.parser")  tables = soup.find_all('tbody', attrs={'class':'odd'})  table = max(tables, key=len)  rows = table.find_all('tr')  

One correctly tagged row looks like this:

<tr>      <td class="area">Area 1</td>      <td>Random string 1+1q, d</td>      <td class="type">xb</td>      <td class="cellAlignRight">38,00</td>      <td class="cellAlignRight">132000</td>      <td class="cellAlignRight">3474</td>      <td class="cellAlignRight">1661</td>      <td>1/1</td>      <td>no</td>      <td>less.</td>      <td>oma      <td>G<sub>2013</sub></td>      </td>    </tr>  

However in the middle of the document something fails and the last rows are merged into one huge string

<tr>      <td class="neighborhood">Itä-hakkila</td>      <td>1h, avokeitti&amp;#...&lt;/td&gt;        &lt;td class="houseType"&gt;rt&lt;/td&gt;        &lt;td class="cellAlignRight"&gt;21,50&lt;/td&gt;        &lt;td class="cellAlignRight"&gt;149000&lt;/td&gt;        &lt;td class="cellAlignRight"&gt;6930&lt;/td&gt;        &lt;td class="cellAlignRight"&gt;2017&lt;/td&gt;        &lt;td&gt;1/2&lt;/td&gt;        &lt;td&gt;ei&lt;/td&gt;        &lt;td&gt;hyvä&lt;/td&gt;        &lt;td&gt;oma &lt;td&gt;C&lt;sub&gt;2013&lt;/sub&gt;&lt;/td&gt;        &lt;/tr&gt;        &lt;tr&gt;        &lt;td class="neighborhood"&gt;Kivist&amp;#246;&lt;/td&gt;        &lt;td&gt;1h+kt&lt;/td&gt;        &lt;td class="houseType"&gt;kt&lt;/td&gt;        &lt;td class="cellAlignRight"&gt;27,00&lt;/td&gt;        &lt;td class="cellAlignRight"&gt;132000&lt;/td&gt;        &lt;td class="cellAlignRight"&gt;4889&lt;/td&gt;        &lt;td class="cellAlignRight"&gt;2018&lt;/td&gt;        &lt;td&gt;5/6&lt;/td&gt;        &lt;td&gt;on&lt;/td&gt;        &lt;td&gt;hyvä&lt;/td&gt;        &lt;td&gt;vuokra &lt;td&gt;C&lt;sub&gt;2013&lt;/sub&gt;&lt;/td&gt;        &lt;/tr&gt;  

which seems to be caused by this cell 1h, avokeitti&#..., which BeautifulSoup turns into <td>1h, avokeitti&amp;#...&lt;/td&gt; where as in the actual HTML on the webpage there is no such issue

<tr>      <td class="neighborhood">It&#228;-hakkila</td>      <td>1h, avokeitti&#...</td>      <td class="houseType">rt</td>      <td class="cellAlignRight">21,50</td>      <td class="cellAlignRight">149000</td>      <td class="cellAlignRight">6930</td>      <td class="cellAlignRight">2017</td>      <td>1/2</td>      <td>ei</td>      <td>hyvä</td>      <td>oma                         <td>C<sub>2013</sub></td>  </tr>  

I've tried using unicode.unescape() to the whole table which gives TypeError: 'NoneType' object is not callable, I've tried using re.sub(r'&lt;', '<', text) to clean the whole table or single rows but that gives TypeError: expected string or bytes-like object.

I circumvented this issue by just doing df_list = pd.read_html(page.text) to get the table out as a dataframe (and had to deal with other formatting issues instead), but the original issue was not solved.

Why does C use FILE for stdin/stdout streams as well as file operations?

Posted: 25 Sep 2021 08:15 AM PDT

I have recently looked into files and input/output in C and quickly figured out that C uses a typedefed structure known as FILE which is commonly represented as a pointer to a structure.
This structure contains data about input and output so lower level parts of the operating system and kernel can easily manage input and output on a system, for example the size of the data being inputted, the type of data etc.
Basically is it purposefully made abstract since the way it works is very low level.

I also know that something like FILE* x is commonly used by C programmers to represent input and output streams. C also allows FILE to commonly be used to point to a file.

Why does C allow programmers to use FILE to represent files as well as input/output streams? To me this sounds very confusing as well as this the keyword FILE is literally called FILE and i would think it would often confuse new programmers into thinking it is used to ONLY point to files.

So why is FILE used for both files and input/output?

Unable to initialize UINavigationController in an iOS application

Posted: 25 Sep 2021 08:13 AM PDT

My application has the following design:

[Information view (UIViewController)] >       [Login/Signup View (UINavigationController)]  

After information view has delivered the essesntial information to user's screen, I am using following code to initialize Login/SignUp view as the root UINavigationController and display it on user's screen.

loginViewController *loginVC = [[loginViewController alloc] init];  UINavigationController *loginNVC = [[UINavigationController alloc] initWithRootViewController:loginVC];  loginVC.modalPresentationStyle=UIModalPresentationFullScreen;  loginVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;  [self showViewController:loginVC sender:self];   

But while running the application, Xcode says "Pushing a navigation controller is not supported" and points to the following code block:

UINavigationController *loginNVC = [[UINavigationController alloc] initWithRootViewController:loginVC];  

Is it an incorrect way of initializing UINavigationController?

AppDelgate code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {      ViewController *rootVC = [[ViewController alloc] init];//ViewController == Information View      self.window.rootViewController=rootVC;      [self.window makeKeyAndVisible];      return YES;  }  

10 plot for different variables

Posted: 25 Sep 2021 08:12 AM PDT

I would like to implement this code, which regards the visualization of some data. In particular I have produce 10 plots which has the same structure of the code below. The only difference between them is the range of x.

In plot n.1 x will go be in range(0, 100, 10) ---> in which 0 goes until 9 for the 10 subplots.

In plot n.2 x will go be in range(100, 200, 10) ---> in which 100 goes until 109 for the 10 subplots.

In plot n.3 x will go be in range(200, 300, 10) ---> in which 200 goes until 209 for the 10 subplots.

and so on until: Plot n.10 x will go be in range(900, 1000, 10) ---> in which 900 goes until 909 for the 10 subplots.

fig, ((ax1,ax2, ax3, ax4, ax5), (ax6,ax7, ax8, ax9, ax10)) = plt.subplots(2,5, figsize =(40,20))  axs = [ax1,ax2, ax3, ax4, ax5, ax6,ax7, ax8, ax9, ax10]  for ax in axs:      ax.grid()      ax.set_xlabel('Time [s]', fontsize = 22)      ax.set_ylabel('$C_{vv}(t)$', fontsize = 22)  ax1.title.set_text('$l_0 = 6.00$ $\mu$m')  ax2.title.set_text('$l_0 = 8.67$ $\mu$m')  ax3.title.set_text('$l_0 = 11.33$ $\mu$m')  ax4.title.set_text('$l_0 = 14.00$ $\mu$m')  ax5.title.set_text('$l_0 = 16.67$ $\mu$m')  ax6.title.set_text('$l_0 = 19.33$ $\mu$m')  ax7.title.set_text('$l_0 = 22.00$ $\mu$m')  ax8.title.set_text('$l_0 = 24.67$ $\mu$m')  ax9.title.set_text('$l_0 = 27.33$ $\mu$m')  ax10.title.set_text('$l_0 = 30.00$ $\mu$m')  fig.suptitle('$\lambda = 0.23 $', fontsize = 30)      for x in range(100, 200, 10):      ax1.plot(VACF[x][:1000,0], VACF[x][:1000,1], alpha=0.5)    for x in range(101, 200, 10):      ax2.plot(VACF[x][:1000,0], VACF[x][:1000,1], alpha=0.5)    for x in range(102, 200, 10):      ax3.plot(VACF[x][:1000,0], VACF[x][:1000,1], alpha=0.5)        for x in range(103, 200, 10):      ax4.plot(VACF[x][:1000,0], VACF[x][:1000,1], alpha=0.5)        for x in range(104, 200, 10):      ax5.plot(VACF[x][:1000,0], VACF[x][:1000,1], alpha=0.5)    for x in range(105, 200, 10):      ax6.plot(VACF[x][:1000,0], VACF[x][:1000,1], alpha=0.5)    for x in range(106, 200, 10):      ax7.plot(VACF[x][:1000,0], VACF[x][:1000,1], alpha=0.5)    for x in range(107, 200, 10):      ax8.plot(VACF[x][:1000,0], VACF[x][:1000,1], alpha=0.5)        for x in range(108, 200, 10):      ax9.plot(VACF[x][:1000,0], VACF[x][:1000,1], alpha=0.5)        for x in range(109, 200, 10):      ax10.plot(VACF[x][:1000,0], VACF[x][:1000,1], alpha=1)        plt.show()  

how do I implement and make the code a little bit shorter? Thank you for the help

Android Glide - How do I load another image if my original image takes too long to load?

Posted: 25 Sep 2021 08:13 AM PDT

I'm loading an image from a url like this. If the image is taking a really long time to load, I want to load another image in its place so I used .error() to load an error image if the load fails, but this fail never gets called. Instead, the original image will eventually load after a long time, but I don't want to wait this long for the image to load. I tried using .timeout() but that doesn't do anything.

                Glide.with(this)                  .load(url)                  .error(Glide.with(errorUrl).load(imageView))                  .into(imageView);  

Did I correctly understand the behaviour of next-redux-wrapper?

Posted: 25 Sep 2021 08:12 AM PDT

Tried to make counter with next-redux-wrapper, redux, Next.js.

I've watched that when I clicked few counter button, then move to other page and came back to counter page, getServerSideProps initializes the counter into 3 again. I understand this library as it helps merge the result of dispatch during SSR to client redux store, but does not sync client store state to server redux store.

Did I understand it correctly?

Here is my code of counter app

index.tsx

export const getServerSideProps = wrapper.getServerSideProps(      (store) => async () => {          store.dispatch(add(3));            return {              props: {},          };      }  );  const index = (props: any) => {      const count = useSelector((state: AppState) => state.counter.count);      const dispatch = useDispatch();      return (          <>              <Link href='/book'>// move to other page then come back                  <a>move</a>              </Link>              <div>{count}</div>              <button onClick={() => dispatch(add(1))}>+</button>              <button onClick={() => dispatch(deleter(2))}>-</button>          </>      );  };  

html 5 canvas optimize redrawing [closed]

Posted: 25 Sep 2021 08:12 AM PDT

I have only one canvas, that has two "virtual" layers, that I can move (not canvases, but rectangles: green, brown)

enter image description here

What I want to achieve in the future is a possibility to draw on "green" layer, and that it doesn't affect "brown" layer

Now I'm adding brush tool to my editor, while using brush I save all the coordinates in array. Now array looks like this:

[  {      "lastPoint": {          "x": 692,          "y": 212      },      "currentPoint": {          "x": 692,          "y": 214      }  },  {      "lastPoint": {          "x": 692,          "y": 214      },      "currentPoint": {          "x": 690,          "y": 219      }  }    ...    ]  

After saving new coordinates to array, I do redraw of the canvas (it's getting worse (freezing) as I add more coordinates to array, obviously)

My question on you is: how can I optimize this redraw on fly feature

Codepen: https://codepen.io/IGentlich/pen/ZEyqqeJ (don't forget to File -> New first)

How can I make a !say command for a discord bot

Posted: 25 Sep 2021 08:13 AM PDT

I can't seem to figure out how to make my bot say the message content without the prefix (!say). I probably need to add the prefix somehow else, but I don't know where. Also, how can I do so that I make the bot say something in a specific channel? This is my code right now:

@client.event  async def on_message(message):  if message.author == client.user:      return    if message.content.startswith('!say'):      await message.channel.send(message.content)        

how to reverse only numbers in a string

Posted: 25 Sep 2021 08:13 AM PDT

INPUT : 123ABC458 OUTPUT : 321ABC854

public static void main(String []args){      String str="123ABC564";      int count=0;      int ans=0;      int firstindex=0;      char[] ch = str.toCharArray();      for(int i=0;i<ch.length;i++){          if(Character.isDigit(ch[i])){              if(ans==0){                  firstindex=i;                }              count++;          }          else{              int lastindex=count+firstindex-1;              while(firstindex<lastindex){                  char temp=ch[firstindex];                  ch[firstindex]=ch[lastindex];                  ch[lastindex]=temp;                  firstindex++;                  lastindex--;              }              ans=0;              count=0;              firstindex=0;          }      }      for (char c : ch){          System.out.print(c);      }  }  

}

Can anyone tell me what's wrong with this code The output which I am getting using this code is 12BA3C564

Is there a way to match when the cell has several values

Posted: 25 Sep 2021 08:13 AM PDT

I am reading the data from one column F2:F11 of an excel worksheet that has this data

|SAT|  |SAT|  |SAT|  |SAT|  |M, T, TH, SAT|  |SUN, W|  |SUN, W, F|  |SAT|  |T, F, SUN|  |W|  

I'm using this vba code to get the matches to Saturday (SAT)

Sub Test()    Dim WaterDays As Range  Set myWKS = Worksheets("Water")  Set WaterDays = myWKS.Range("F2:F11")    For Each y In WaterDays     vParts = Split(y, ",")     For Each dy In vParts        If StrComp(dy, "SAT") = 0 Then          Debug.Print ("Yes")        End If     Next dy   Next y  End Sub  

When I do this it will give me 5 matches (Yes), when there are actually 6 SATs in the column. What am I doing wrong here? Any help would be appreciated. Thanks

How to help the Scala 3 compiler infer a path-dependent-type?

Posted: 25 Sep 2021 08:12 AM PDT

Suppose that, whenever type A can represent a less-than-perfectly-precise measurement of a physical value, I'll have an instance of Imprecise[A].

trait Imprecise[A]:    type Precision    val ord: Ordering[Precision]    def precision(a: A): Precision  

For example, this Bounds type has a given instance in its companion object:

case class Bounds[N: Numeric](min: N, max: N):    if summon[Ordering[N]].compare(min, max) > 1 then      throw new IllegalArgumentException    object Bounds:    import scala.math.Numeric.Implicits.infixNumericOps    import scala.math.Ordering.Implicits.infixOrderingOps    given [N: Numeric]: Imprecise[Bounds[N]] with      type Precision = N      val ord = summon[Ordering[N]]      def precision(rng: Bounds[N]) = rng.max - rng.min  

Now my program can start dealing with the physical features that need to be observed:

trait Feature[A:  Imprecise]:    type Observation = A    val imprecise = summon[Imprecise[A]]    type Precision = imprecise.Precision      def within(bound: Precision) = new RequiredFeature(this, bound)    class RequiredFeature(val feature: Feature[_], val min_precision: feature.Precision)      case class Temperature(chamber_id: Int) extends Feature[Bounds[Double]]  case class Pressure(chamber_id: Int) extends Feature[Bounds[Float]]  

But when, at last, I try to make a required feature:

val rf = Temperature(3).within(7.0)  

the compiler complains

Found:    (7.0d : Double)  Required: ?1.Precision    where:    ?1 is an unknown value of type exp.Temperature    val rf = Temperature(3).within(7.0)  

The code written so far can be made to compile if I forego any path-dependent types and pass the precision around everywhere as a regular generic type parameter. But what if I don't want to do that? Is there some strategy like the Aux pattern that will help the compiler see that this is a valid call to within?

How to checkbox enable/disable with Struts 2

Posted: 25 Sep 2021 08:13 AM PDT

I would like to show 2 checkboxs in my page (called box1 and box2). The default value is box1 = false and box2 = false. But I also have to enable box2 only if box1 = true. So I have created the following JS function :

function myTest() {    var check = document.getElementById('box1');    if (check.checked == false) {      $('#box2').prop('disabled', true);    } else {      $('#box2').prop('disabled', false);    }  }  

Now I don't really understand how to use myTest function in the JSP file. I have tried to use it with onload="myTest()" as follow, but it doesn't work (box2 is always disabled).

<body onload="myTest()" />    <div class="form-group row">      <label class="col-sm-3 col-form-label required">          <s:text name="box1" />      </label>      <div class="col-sm-9">          <s:checkbox id="box1" name="box1"> </s:checkbox>      </div>  </div>  <div class="form-group row">      <label class="col-sm-3 col-form-label required">          <s:text name="box2" />      </label>      <div class="col-sm-9">          <s:checkbox id="box2" name="box2"></s:checkbox>      </div>  </div>  

Flutter: Cast error in sku_details_wrapper.g.dart

Posted: 25 Sep 2021 08:13 AM PDT

i'm having some truble in Flutter.

flutter doctor -v output:

[✓] Flutter (Channel stable, 2.5.1, on macOS 11.6 20G165 darwin-x64, locale en-IT)      • Flutter version 2.5.1 at /Users/me/Developer/flutter      • Upstream repository https://github.com/flutter/flutter.git      • Framework revision ffb2ecea52 (6 days ago), 2021-09-17 15:26:33 -0400      • Engine revision b3af521a05      • Dart version 2.14.2    [✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)      • Android SDK at /Users/me/Library/Android/sdk      • Platform android-30, build-tools 29.0.3      • Java binary at: /Applications/AndroidStudio.app/Contents/jre/jdk/Contents/Home/bin/java      • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)      • All Android licenses accepted.    [✓] Xcode - develop for iOS and macOS      • Xcode at /Applications/Xcode.app/Contents/Developer      • Xcode 13.0, Build version 13A233      • CocoaPods version 1.11.2    [✓] Android Studio (version 4.1)      • Android Studio at /Applications/Android Studio.app/Contents      • Flutter plugin can be installed from:        🔨 https://plugins.jetbrains.com/plugin/9212-flutter      • Dart plugin can be installed from:        🔨 https://plugins.jetbrains.com/plugin/6351-dart      • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)    [✓] VS Code (version 1.60.1)      • VS Code at /Applications/Visual Studio Code.app/Contents      • Flutter extension version 3.26.0    [✓] Connected device (1 available)      • SM G930F (mobile) • android-arm64 • Android 8.0.0 (API 26)    • No issues found!  

I have recently updated and migrated my code to null safety and updated all the dependencies; since I do this, I have some problems with the in_app_purchase package version 1.0.8 (https://pub.dev/packages/in_app_purchase).

When i run the app on Android device (iOS devices works) i got an error:

Unhandled Exception: type 'int' is not a subtype of type 'String?' in type cast  

while calling:

ProductDetailsResponse response = await InAppPurchase.instance.queryProductDetails({'MY_PRODUCT_ID'});  

Right after the function got called, VSCode show me that the error happen in the sku_details_wrapper.g.dart file into the function that convert the json to SkuDetailsWrapper:

SkuDetailsWrapper _$SkuDetailsWrapperFromJson(Map json) {    return SkuDetailsWrapper(      description: json['description'] as String? ?? '',      freeTrialPeriod: json['freeTrialPeriod'] as String? ?? '',      introductoryPrice: json['introductoryPrice'] as String? ?? '',      introductoryPriceMicros: json['introductoryPriceAmountMicros'] as String? ?? '',      introductoryPriceCycles: json['introductoryPriceCycles'] as int? ?? 0,      introductoryPricePeriod: json['introductoryPricePeriod'] as String? ?? '',      price: json['price'] as String? ?? '',      priceAmountMicros: json['priceAmountMicros'] as int? ?? 0,      priceCurrencyCode: json['priceCurrencyCode'] as String? ?? '',      priceCurrencySymbol: json['priceCurrencySymbol'] as String? ?? '',      sku: json['sku'] as String? ?? '',      subscriptionPeriod: json['subscriptionPeriod'] as String? ?? '',      title: json['title'] as String? ?? '',      type: const SkuTypeConverter().fromJson(json['type'] as String?),      originalPrice: json['originalPrice'] as String? ?? '',      originalPriceAmountMicros: json['originalPriceAmountMicros'] as int? ?? 0,    );  }  

In particular the error line is:

introductoryPriceMicros: json['introductoryPriceAmountMicros'] as String? ?? '',  

where it try to convert an int (json['introductoryPriceAmountMicros']) to a String?.

Can you help me please? I'm not able to find any help online.

Issue with double-escaped entities in the link

Posted: 25 Sep 2021 08:12 AM PDT

I am getting double-escaped entities in the link in a post. For example, a link What's the difference becomes What&amp;rsquo;s the difference.

The problem is similar to this https://discourse.gohugo.io/t/solved-why-is-page-title-getting-double-escaped-entities/14935 however it didn't help me solve this.

Why is this happening? How do I solve it?

The code for the blog is available here - https://github.com/desecho/blog

the following html is not rendered by jinjia2

Posted: 25 Sep 2021 08:13 AM PDT

I find the following code in layuiadmin framework, but they are not rendered by jinjia2 in flask.

<script type="text/html" id="buttonTpl">

{{#  if(d.check == true){ }}  <button class="layui-btn layui-btn-xs">已审核</button>  {{#  } else { }}  <button class="layui-btn layui-btn-primary layui-btn-xs">未审核</button>  {{#  } }}  

How to render it?

Website monthly visits are (daily visits x 30)?

Posted: 25 Sep 2021 08:13 AM PDT

I'm trying to estimate if showing ads on my website can become the main source of income by estimating the traffic of somewhat similar sites.

There are several websites, offering traffic statistics and presenting similar data. For instance, here is their statistics for stackoverflow.com:

http://www.similarweb.com/website/stackoverflow.com http://www.trafficestimate.com/stackoverflow.com http://www.siteworthtraffic.com/report/stackoverflow.com

According to these data, stackoverflow.com receives just around 150 million monthly visits. Does it mean that I should divide this number by 30 in order to get the number of daily visits, resulting in only 5 million visits a day, which is worth only ~15 000$ income a day? Because that's quite a low number for such a monster.

Or in reality it receives around 150 million users each day, making around 500 000$ a day?


Another case - VK.com:

http://www.trafficestimate.com/vk.com

http://www.similarweb.com/website/vk.com#overview

http://www.siteworthtraffic.com/report/vk.com

According to vk.com they have 350 millions active users. So the data, presented by trafficestimate, similarweb and siteworthtraffic don't look consistent.


Another case - meduza.io.

meduza.io is a news site, which was created by ~30 people team, who left lenta.ru after polytical persecution of their chief editor. They're making ~3 million visitors a month or ~ 10 million page views.

http://www.trafficestimate.com/meduza.io

http://www.similarweb.com/website/meduza.io#overview

With 10$/1000 page views, they could achieve just 100 000$/month, which is barely or not enough to pay salaries to 30 people in Europe.

How to unset global variable in php?

Posted: 25 Sep 2021 08:13 AM PDT

I know very basic of php and web programming. Here is my php code. I have seen couple of similar questions. They unset global variable with unset function. I want every time user open the url, a username and password prompt and after entering username password if it is correct download the file and delete username and password and if is wrong delete username and password and again prompt for username password.

<?php          function destroy_foo()      {          if (isset($_SERVER['PHP_AUTH_USER'])) {              unset($_SERVER['PHP_AUTH_USER']);                 }          if (isset($_SERVER['PHP_AUTH_PW'])) {              unset($_SERVER['PHP_AUTH_PW']);          }      }        if (!isset($_SERVER['PHP_AUTH_USER'])) {            header('WWW-Authenticate: Basic realm="My Realm"');          header('HTTP/1.0 401 Unauthorized');          echo 'Text to send if user hits Cancel button';          exit;      } else {            echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";          echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";            $file = 'welcome.txt';          if($_SERVER['PHP_AUTH_PW'] == "admin" && $_SERVER['PHP_AUTH_USER'] =="admin"){              destroy_foo();                if (file_exists($file)) {                   //Do some task                  destroy_foo();                  exit;              }          }          else          {              //Do some task              destroy_foo();            }      }      ?>  

At the moment username and password stays in the global variables for some reason. I'd appreciate if you could give suggestion or hint.

EDIT

This did not work either:

function destroy_foo()  {        if (isset($_SERVER['PHP_AUTH_USER'])) {            unset($_SERVER['PHP_AUTH_USER']);          $_SERVER['PHP_AUTH_USER'] = null;        }       if (isset($_SERVER['PHP_AUTH_PW'])) {           unset($_SERVER['PHP_AUTH_PW']);         $_SERVER['PHP_AUTH_PW'] = null;       }  }  

Link to file: http://behzadgarekani.net16.net/

Get X and Y pixel coordinates when iterating over HTML5 canvas getImageData

Posted: 25 Sep 2021 08:12 AM PDT

I am iterating over some image data pulled from a canvas like so:

var imageData = this.context.getImageData(0, 0, this.el.width, this.el.height);  var data = imageData.data;    for (var i = data.length; i >= 0; i -= 4) {      if (data[i + 3] > 0) {          data[i] = this.colour.R;          data[i + 1] = this.colour.G;          data[i + 2] = this.colour.B;      }  }  

How do I calculate the current X and Y pixel coordinates that I am at?

No comments:

Post a Comment