Saturday, July 17, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to rebase a forked local branch?

Posted: 17 Jul 2021 09:08 AM PDT

There is an open source project that I forked. Then I created a copy of that fork in my local git.

When I want to rebase I do (I don't know if this is a good way but it does work):

git checkout main  git fetch project-name  git reset --project-name/main (This make my local like the upstream)  git push --force-with-lease (this makes my forked like the local)  

Now, say that I did:

git checkout mybranch  git commit  git push....  

I pushed the changes to my forked and opened a PR to the upstream project.

My question is how now I can rebase mybranch with upstream/main?

My Navbar collapse delay is adding to CLS in pagespeed insights. How to improve?

Posted: 17 Jul 2021 09:08 AM PDT

My website at https://propertymysore.com/ uses a template FindHouse from themeforest.

This is using the bootstrap 4.2.1

When I run pagespeed insights, I get a big CLS score of .716 in mobile and .37 in desktop.

I see that this is resulting in my pagespeed for mobile droping bellow 50 for mobile and below 90 for desktop.

the collapsing effect of the dropdown menu is the culprit.

Can someone help how can i reduce this effect or speed the process of collapsing the menu to its final place faster etc. to improve the CLS and hence the scores?

<ul id="respMenu" class="ace-responsive-menu text-left" data-menu-style="horizontal">                    <li><a href='https://propertymysore.com/about-us/'>About</a><ul><li><a href='https://propertymysore.com/our-team/'>Our Team</a></li></ul></li><li><a href='https://propertymysore.com/#'>Partners</a><ul><li><a href='https://propertymysore.com/top_realtors.php'>Realtors</a></li><li><a href='https://propertymysore.com/top_agencies.php'>Agencies</a></li></ul></li>                  <li><a href='https://propertymysore.com/listings/residential/'>Residential</a><ul><li><a href='https://propertymysore.com/listings/residential/sites/'>Sites</a></li><li><a href='https://propertymysore.com/listings/residential/house/'>House</a></li><li><a href='https://propertymysore.com/listings/residential/flats/'>Flats</a><ul><li><a href='https://propertymysore.com/listings/flats/luxury-apartments/'>Luxury Apartments</a></li><li><a href='https://propertymysore.com/listings/flats/budget-apartments/'>Budget Apartments</a></li></ul></li></ul></li><li><a href='https://propertymysore.com/listings/lands/'>Lands</a><ul><li><a href='https://propertymysore.com/listings/lands/converted/'>Converted</a></li><li><a href='https://propertymysore.com/listings/lands/agricultural/'>Agricultural</a></li></ul></li><li><a href='https://propertymysore.com/listings/commercial/'>Commercial</a><ul><li><a href='https://propertymysore.com/listings/commercial/buildings/'>Buildings</a></li><li><a href='https://propertymysore.com/listings/commercial/commercial-sites/'>Commercial Sites</a></li></ul></li><li><a href='https://propertymysore.com/listings/industrial/'>Industrial</a><ul><li><a href='https://propertymysore.com/listings/industrial/factories/'>Factories</a></li><li><a href='https://propertymysore.com/listings/industrial/lands-and-sites/'>Lands and Sites</a></li></ul></li>                                         <li class="list-inline-item list_s float-right">                                               <a href="#" class="btn flaticon-user" data-toggle="modal" data-target=".bd-example-modal-lg"> <span class="dn-lg">Login/Register</span></a>                                          </li>                  </ul>

Is it possible to read all files of the same format into one command in ffmpeg?

Posted: 17 Jul 2021 09:08 AM PDT

I have a python script which downloads a number of .ts and .aac files in the current working directory. I want to be able to concatenate them individually and then combine the final .ts and .aac files to produce the output.

Currently, I have around 90 files for both ts and aac. I understand it is possible to create a batch file containing the entirety of the related files which can be used to join them together, however, I wanted to find a solution that can ignore the creation of a batch file to increase the speed of the script.

Here is a basic interpretation of my request:

  • 1.ts, 2.ts, 3.ts, 4.ts, 5.ts, 6.ts

    ffmpeg -f concat -safe 0 -i 1.ts:6.ts -c copy output.ts

I've tried surfing the web for a solution, but all results lead me back to a batch file. Any help is appreciated

python help pulling info out of a file

Posted: 17 Jul 2021 09:08 AM PDT

I am trying to parse some data in a file and getting stuck:

here is my code:

   import re            with open('slo_id.txt', "r+") as f:      lines = f.readlines()      # pattern = re.compile(r"'id':")      # matches = pattern.finditer(lines)      # for match in matches:      #     print(matches)      #f.close()      for line in lines:          item = re.findall("\s'id':.*$",lines,re.MULTILINE)          for l in item:              print(l.strip())      f.close()  

The comments are other things I have tried.

This is a sample of what I am trying to parse

{'data': [{'created_at': 1623855546,             'creator': {'email': 'some_email',                         'handle': 'some_handle',                         'name': 'a_name'},             'description': 'description',             'id': '0eb2a314c6cc54fba2d7fc9e67c6d684',             'modified_at': 1623856440,             'monitor_ids': [35763088],             'monitor_tags': [],             'name': 'name',             'tags': [tags],             'thresholds': [{'target': 99.0,                             'target_display': '99.',                             'timeframe': '30d',                             'warning': 99.89,                             'warning_display': '99.89'}],             'type': 'monitor'},  

I know the file is saved as a json file, but it is not json, it is saved like this as I ran something else to pull data from an API call, which initially I thought was returning json, but it does not appear to be the case. I am unsure if changing to a .txt file will make any difference. MY goal is that I want to find all of the lines with

'id': 'some ID'

and cut the 'id' part out so it only prints the actual id and I can then send that to a new file. I am at a point with this where the code runs, but nothing outputs and I am lost as I am very new to coding. Any help is appriciated. TIA

signals and tasks file are not connecting in django celery

Posted: 17 Jul 2021 09:07 AM PDT

I am using Django signals to trigger a task (sending mass emails to subscribers using Django celery package)when an admin post a blogpost is created from Django admin. The signal is triggered but the task function in the task file is not called. It's because I put a print function which is not printing inside the task function.

My signlas.py file:

from apps.blogs.celery_files.tasks import send_mails  from apps.blogs.models import BlogPost,Subscribers  from django.db.models.signals import post_save  from django.dispatch import receiver    def email_task(sender, instance, created, **kwargs):      if created:          print("@signals.py")          send_mails.delay(5)      post_save.connect(email_task, sender=BlogPost,dispatch_uid="email_task")  

My task.py file

from __future__ import absolute_import, unicode_literals  from celery import shared_task  # from celery.decorators import task  from apps.blogs.models import BlogPost,Subscribers  from django.core.mail import send_mail  from travel_crm.settings import EMAIL_HOST_USER  from time import sleep    @shared_task  def send_mails(duration,*args, **kwargs):      print("@send_mails.py")      subscribers = Subscribers.objects.all()      blog = BlogPost.objects.latest('date_created')      for abc in subscribers:          sleep(duration)          print("i am inside loop")          emailad = abc.email          send_mail('New Blog Post ', f" Checkout our new blog with title {blog.title} ",                    EMAIL_HOST_USER, [emailad],                    fail_silently=False)  

Here. the print("@send_mails.py") is not executed but print("@signals.py") in signals.py file is executed. Hence, signals is received after the Blogpost model object is created but the function inside task.py which is send_mails is not executed.

I have installed both celery and redis server and both are working fine.

The main thing is if I remove .delay(5) from signal file and instead used just send_mails() inside email_task , it works perfectly and i am getting emails. But as soon as I add delay() function, the fucntion inside task file is not called. What is the issue??

How to iterate a function along a single column across multiple data frames in R

Posted: 17 Jul 2021 09:07 AM PDT

I have many data frames with identical column names (spectrophotometer data) and I want to apply a function along a single column of all the data frames at once, and append each data frame with the new column. That single column is named the same across data frames.

I have been trying lapply (and apply family) and then moved on to map to no avail. This solution seemed promising (R - Apply function on multiple data frames) but everything I put in position 3 inside the lapply function is ignored as an unused argument.

So for example if you use this simplified data

cola <- c(1,2,3)

colb <- c("x","y","z")

colc <- c(1.4,1.2,2.5)

df1 <- as.data.frame(colb %>% cbind(cola, colc))

colc <- 1.1*colc # just to change content of same column name for df2

df2 <- as.data.frame(colb %>% cbind(cola, colc))

And then put them in a list df.list <- list(df1, df2)

define a function calculation <- function(x){ sLd = x-2 z=log10(sLd) return(z) } then use lapply lapply(df.list, calculation, colc)

The third position inside lapply function is ignored regardless of how I list it as colc, "colc", [,3]

I'd also like to define a name for the new column, say cold.

kivy error from using a variable from python file to kv file

Posted: 17 Jul 2021 09:07 AM PDT

I'm making a Manga reader it uses the Images module in kivy and I found a bug that can be solved by using a variable from a py file to a kv file. I have a Variable in the App class called sourceToImage but when i call the sourceToImage variable in a kv file source: app.sourceToImage gives me a long error

py

class MyApp(App):      sourceToImage = "Source"         def build(self):          return sm  

kv

<ReaderApp>:      name: "reader"      im: page        canvas:          Color:              rgba: 1,1,1,0.17          Rectangle:              size: (root.width, root.height)              pos: (0,0)      Image:          size: 500, 600          pos: 0, 0          id: page          source: app.sourceToImage  

but when i use app.sourceToImage it gives me an Error saying:

Traceback (most recent call last):     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\builder.py", line 242, in create_handler       return eval(value, idmap), bound_list     File "D:\GameDev-Programming\Python\kivyProjects\firstKivy\my.kv", line 20, in <module>       source: app.sourceToImage     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\parser.py", line 75, in __getattribute__       object.__getattribute__(self, '_ensure_app')()     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\parser.py", line 70, in _ensure_app       app.bind(on_stop=lambda instance:   AttributeError: 'NoneType' object has no attribute 'bind'      During handling of the above exception, another exception occurred:      Traceback (most recent call last):     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\builder.py", line 695, in _apply_rule       value, bound = create_handler(     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\builder.py", line 245, in create_handler       raise BuilderException(rule.ctx, rule.line,   kivy.lang.builder.BuilderException: Parser: File "D:\GameDev-Programming\Python\kivyProjects\firstKivy\my.kv", line 20:   ...        18:        pos: 0, 0        19:        id: page   >>   20:        source: app.sourceToImage        21:        22:   ...   AttributeError: 'NoneType' object has no attribute 'bind'     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\builder.py", line 242, in create_handler       return eval(value, idmap), bound_list     File "D:\GameDev-Programming\Python\kivyProjects\firstKivy\my.kv", line 20, in <module>       source: app.sourceToImage     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\parser.py", line 75, in __getattribute__       object.__getattribute__(self, '_ensure_app')()     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\parser.py", line 70, in _ensure_app       app.bind(on_stop=lambda instance:         During handling of the above exception, another exception occurred:      Traceback (most recent call last):     File "D:\GameDev-Programming\Python\kivyProjects\firstKivy\main.py", line 87, in <module>       kv = Builder.load_file("my.kv")     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\builder.py", line 306, in load_file       return self.load_string(data, **kwargs)     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\builder.py", line 408, in load_string       self._apply_rule(     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\builder.py", line 661, in _apply_rule       child.apply_class_lang_rules(     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\uix\widget.py", line 463, in apply_class_lang_rules       Builder.apply(     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\builder.py", line 541, in apply       self._apply_rule(     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\builder.py", line 710, in _apply_rule       raise BuilderException(rule.ctx, rule.line,   kivy.lang.builder.BuilderException: Parser: File "D:\GameDev-Programming\Python\kivyProjects\firstKivy\my.kv", line 20:   ...        18:        pos: 0, 0        19:        id: page   >>   20:        source: app.sourceToImage        21:        22:   ...   BuilderException: Parser: File "D:\GameDev-Programming\Python\kivyProjects\firstKivy\my.kv", line 20:   ...        18:        pos: 0, 0        19:        id: page   >>   20:        source: app.sourceToImage        21:        22:   ...   AttributeError: 'NoneType' object has no attribute 'bind'     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\builder.py", line 242, in create_handler       return eval(value, idmap), bound_list     File "D:\GameDev-Programming\Python\kivyProjects\firstKivy\my.kv", line 20, in <module>       source: app.sourceToImage     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\parser.py", line 75, in __getattribute__       object.__getattribute__(self, '_ensure_app')()     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\parser.py", line 70, in _ensure_app       app.bind(on_stop=lambda instance:        File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\builder.py", line 695, in _apply_rule       value, bound = create_handler(     File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\lang\builder.py", line 245, in create_handler       raise BuilderException(rule.ctx, rule.line,  

full kv file:

WindowManager:      SelectingApp:      ReaderApp:      <ReaderApp>:      name: "reader"      im: page        canvas:          Color:              rgba: 1,1,1,0.17          Rectangle:              size: (root.width, root.height)              pos: (0,0)      Image:          size: 500, 600          pos: 0, 0          id: page          source: ""        <SelectingApp>      name: "selecting"      listSpin: spinnerId      canvas:          Color:              rgba: 1,1,1,0.17          Rectangle:              size: (root.width, root.height)              pos: (0,0)      FloatLayout:          Label:              text: app.sourceToImage              size_hint: 0.1,0.1              pos_hint: {"x": 0.4, "y": 0.5}          Button:              text: "Go to reader"              on_press: root.Change()              size_hint: 0.5, 0.05              pos_hint: {"x": 0.2}          Spinner:              id: spinnerId              text: "Choose Manga"              values: ["hey", "ey"]              size_hint: 0.3, 0.1              pos_hint: {"x":0.3, "y":0.4}          Button:              text: "refresh list"              size_hint: 0.5, 0.05              pos_hint: {"x": 0.2, "y": 0.2}              on_press: root.Refresh()  

full py file:

import os  from kivy.app import App  from kivy.properties import ObjectProperty  from kivy.config import Config  from kivy.uix.screenmanager import ScreenManager, Screen  from kivy.lang import Builder  from kivy.properties import StringProperty      width = 360  height = 640    # How the fuck does this make the resolution 641    Config.set('graphics', 'width', width)  Config.set('graphics', 'height', height)    Manga = "Seirei Gensouki - Konna Sekai De Deaeta Kimi Ni"  page = 0  arr = os.listdir(f"Manga/{Manga}")  MangaList = os.listdir("Manga")  fileCount = len(arr)      class WindowManager(ScreenManager):      pass      class ReaderApp(Screen):      im = ObjectProperty(None)        def NextPage(self):          global page          if fileCount > page:              page += 1              if arr[0] == "1.jpg":                  self.im.source = f"Manga/{Manga}/{page}.jpg"              else:                  self.im.source = f"Manga/{Manga}/{page}.png"              print("next page")        def PreviousPage(self):          global page          if page > 1:              page -= 1              if arr[0] == "1.jpg":                  self.im.source = f"Manga/{Manga}/{page}.jpg"              else:                  self.im.source = f"Manga/{Manga}/{page}.png"              print("previous page")        def on_touch_down(self, touch):          global page          xPos, yPos, = touch.pos          xPos = int(xPos)          yPos = int(yPos)          print(f"X: {xPos}\nY: {yPos}")          if xPos > 300 and yPos > 600:              sm.current = "selecting"              f = open("Records", "r+")              f.writelines(f"{Manga};{page}")              f.close()          elif self.width * .30 > xPos:              self.PreviousPage()          elif xPos > self.width * .70:              self.NextPage()      class SelectingApp(Screen):      listSpin = ObjectProperty(None)        def Refresh(self):          self.listSpin.values = MangaList        def Change(self):          global page          f = open("Records", "r")          records = f.read().split("\n")          print(records)          for lines in records:              print(lines)              mangaTitle, mangaPage = lines.split(";")              print(mangaTitle, mangaPage)              if mangaTitle == Manga:                  page = int(mangaPage)          sm.current = "reader"      kv = Builder.load_file("my.kv")    sm = WindowManager()  screens = [SelectingApp(name="selecting"), ReaderApp(name="reader")]  for screen in screens:      sm.add_widget(screen)      class MyApp(App):      sourceToImage = StringProperty(f"Manga/{Manga}/{page}.jpg")        def build(self):          return sm      if __name__ == "__main__":      MyApp().run()  

Restore deleted runs of a notebook in Databricks

Posted: 17 Jul 2021 09:06 AM PDT

I was trying to delete a few failed runs of a Notebook in order to clean up, but accidentally deleted one useful run. I went through Databricks documentation and community support, but couldn't find anything. So, is it possible to restore deleted runs of a Notebook?

Sum Digits in java [duplicate]

Posted: 17 Jul 2021 09:06 AM PDT

In this problem, he wants the sum of the digits of this number 10^6

I tried many solutions, but the end result wrong answer

https://codeforces.com/group/MWSDmqGsZm/contest/219774/problem/K

This is my code

 int n = in.nextInt();  String s = in.nextLine();  int num = 0;    for (int i = 0; i < s.length(); ++i) {      num += (s.charAt(i) - '0');  }    System.out.println(num);  

How to decrypt the hashed password of pbkdf

Posted: 17 Jul 2021 09:06 AM PDT

there I am trying to do a project where I hashed the password and store hashed password in database. Now I am facing problem in decrypting. How can I decrypt the password. Please help me to decrypt this pbkdf form of password.
Please help 🙏 . And I am trying to do in java.

can I write on file.txt in the same line

Posted: 17 Jul 2021 09:08 AM PDT

this is the code I wrote

echo "Positive count =" > file.txt | grep -o -i positive IMDB_Dataset.csv | wc -l >> file.txt  

on ubuntu and the result in the file was

Positive count =

26188

can I write it in the same line to become like this

Positive count = 26188

and thank you in advance

Add mysqli options in Codeigniter 4

Posted: 17 Jul 2021 09:07 AM PDT

I have several fields in my database that are DECIMAL(10,2) or INT values, when I return the results everything is returned as string.

Example:

    $sql = "SELECT id, operacion_id FROM operaciones";      $query = $this->db->query($sql);      $result = $query->getResultArray();        return $this->response->setStatusCode(200)                      ->setContentType('application/json')                      ->setJSON($result);  

And that returns:

[{      "id": "31",      "operacion_id": "ES-2021-0031"  },  {      "id": "30",      "operacion_id": "ES-2021-0030"  }]  

I tried to put directly in system\Database\MySQLi\Connection.php connect() method:

$this->mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, true);  

This works well but I know that it is not upgrade safe.

URL manipulation for weather rest api

Posted: 17 Jul 2021 09:08 AM PDT

Hi I'm trying to figure out how to change the city, based on the current location.Is there a way I can manipulate "{city}"? This is probably a really easy question. As of current, my app is aware of device location but I don't know how to manipulate the url. Should I use a different api?

interface ApiService {        @GET("weather/{city}")      suspend fun getWeather():Response<Weather>   }  

babel-node not lnclude .graphql files in build

Posted: 17 Jul 2021 09:06 AM PDT

I'm loading .graphql files like this:

import { join } from 'path'  import { loadSchemaSync } from '@graphql-tools/load'  import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader'  import { addResolversToSchema } from '@graphql-tools/schema'  import resolvers from './resolvers'  const schema = loadSchemaSync(join(__dirname, './typedefs/*.graphql'), { loaders: [new GraphQLFileLoader()] })    const schemaWithResolver = addResolversToSchema({    schema,    resolvers  })  export default schemaWithResolver  

When I build for production, the folder ./typedefs is not included in the build output (dist).

this is the build cmd: "build-babel": "babel ./src -s -d dist"

How do include .graphql extensions in the babel cmd above?

returning changes made in listener

Posted: 17 Jul 2021 09:06 AM PDT

private fun getMenuList(): List<MenuItem> {      val items = mutableListOf<MenuItem>()      FireBaseRefs.mFireStore.collection("menu").get().addOnSuccessListener {          for (document in it.documents) {              items.add(MenuItem(                  name = document.data?.get("name").toString(),                  category = document.data?.get("category").toString(),                  description = document.data?.get("description").toString(),                  image = document.data?.get("image").toString(),                  weight = document.data?.get("weight").toString(),              ))          }      }      return items  }  

Items within body of addOnSuccessListener contains data, but outside of it contains nothing. How should i return values from Listener

Bootstrap V5 Alert Dismissing: Asking for confirmation when "Close Button" is clicked

Posted: 17 Jul 2021 09:06 AM PDT

I'm trying to add a nice confirmation message using Sweetalert2 to the bootstrap version 5 alert component.

how does it work?

when I clicked to "Close Button" (X) it should display a confirmation message with two options (Yes) and (No) if I clicked to (Yes) the alert component should be closed if (No) the alert component should be displayed.

that's it.

the issue that I face is in the close event when I put this code inside it and clicked to (Yes) Option in sweatalert2 confirmation message it shows me an error message in my dev console!

reference: https://getbootstrap.com/docs/5.0/components/alerts/#dismissing

HTML code:

<div class="alert alert-warning alert-dismissible fade show" role="alert">    <strong>Holy guacamole!</strong> You should check in on some of those fields below.    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>  </div>  

JS code:

if ($(".alert").length) {      $(".alert").on("close.bs.alert", function (e) {          e.preventDefault();          var swalWithBootstrapButtons = Swal.mixin({              customClass: {                  confirmButton: "btn btn-primary",                  cancelButton: "btn btn-danger me-3",              },              buttonsStyling: false,          });          swalWithBootstrapButtons              .fire({                  title: "Are you sure?",                  text: "You won't be able to revert this!",                  icon: "warning",                  confirmButtonText: "<i class='fas fa-check-circle me-1'></i> Yes, I am!",                  cancelButtonText: "<i class='fas fa-times-circle me-1'></i> No, I'm Not",                  showCancelButton: true,                  reverseButtons: true,                  focusConfirm: false,              })              .then((result) => {                  if (result.isConfirmed) {                      var alertNode = document.querySelector(".alert");                      var alert = bootstrap.Alert.getInstance(alertNode);                      alert.close();                  }              });      });  }  

How to set a max rotation on an object in C# (Unity)

Posted: 17 Jul 2021 09:08 AM PDT

I am trying to make a space ship tilt upwards when it travels upwards or tilt downwards when it falls but I'm stuck this is what I have so far

 if (Input.GetKey(KeyCode.Space)) //If spacebar pressed          {              playerRb.AddForce(Vector3.up * floatForce, ForceMode.Impulse); // Add force upwards to player          }            // Rotates upwards          if (Input.GetKey(KeyCode.Space))          {              if (transform.rotation.x != -maxRotation)              {                  transform.Rotate(-rotationSpeed, 0f, 0f * Time.deltaTime);                  transform.Rotate(-maxRotation, 0f, 0f);              }          }  

It just spins infinitely when I press down on the space bar...

Any help? Thank you

Connect docker container to system's mongo: address already in use

Posted: 17 Jul 2021 09:06 AM PDT

Firt of all: I don't want to connect to a docker container, running mongo.

I am building a docker container that should access the mongo database I have installed in my running Ubuntu 18.04 machine.

Docker suggests this could be done fairly easy by just adding the flag -pto the run command, so I did this:

docker run -p 27017:27017 --name mycontainer myimage  

Port 27017 is the default port for mongo (see here) and running netstat -pna | grep 27017 confirms by returning the following:

tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      -                     tcp        0      0 127.0.0.1:27017         127.0.0.1:55880         ESTABLISHED -                     tcp        0      0 127.0.0.1:55882         127.0.0.1:27017         ESTABLISHED -                     tcp        0      0 127.0.0.1:55880         127.0.0.1:27017         ESTABLISHED -                     tcp        0      0 127.0.0.1:27017         127.0.0.1:55884         ESTABLISHED -                     tcp        0      0 127.0.0.1:27017         127.0.0.1:55882         ESTABLISHED -                     tcp        0      0 127.0.0.1:55884         127.0.0.1:27017         ESTABLISHED -                     unix  2      [ ACC ]     STREAM     LISTENING     77163    -                    /tmp/mongodb-27017.sock  

But running the docker command shown above, I get an error indicating that I can't connect to the port because it is already in use (which is actually the whole point of connecting to it):

docker: Error response from daemon: driver failed programming external connectivity on endpoint mycontainer (1c69e178b48ee51ab2765479e0ecf3eea8f43e6420e34b878882db8d8d5e07dd): Error starting userland proxy: listen tcp4 0.0.0.0:27017: bind: address already in use.  ERRO[0000] error waiting for container: context canceled   

How should I proceed? What did I do wrong?

Tkinter button text isn't shown

Posted: 17 Jul 2021 09:08 AM PDT

enter image description here

I want to run this example code I pasted but button text didn't show up. I don't know why. I tried another simple test and change textcolor, bicolor but all of them also doesn't work.

I doubt m1 Mac (no clue)

I am using silicon m1 pro.

In x86-64 Virtual Environments, Python 3.8.2

Jupyter notebook and python *.py in terminal

How to set different permissions depending on the request method?

Posted: 17 Jul 2021 09:06 AM PDT

I am creating an API for some polls. I need the author to be the only one who can view the votes, but the authenticated users to view the polls, questions, and to post votes. The author is just an instance of User, as like as the voters. I'm using Djoser to provide the authentication API, model serializers, and breaking my mind between CBVs and viewsets.

Here are my models, if it can help.

from django.db import models  from django.contrib.auth import get_user_model  from django.utils import timezone  import datetime    User = get_user_model()      class Poll(models.Model):      title = models.CharField(max_length=200, verbose_name="Naslov ankete")      description = models.TextField(verbose_name="Opis ankete")      author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="polls", verbose_name="Autor")        class Meta:          verbose_name = "Anketa"          verbose_name_plural = "Ankete"        def __str__(self):          return self.title      class Question(models.Model):      poll = models.ForeignKey(Poll, on_delete=models.CASCADE, related_name="questions", verbose_name="Anketa")      question_text = models.CharField(max_length=200, verbose_name="Tekst pitanja")      pub_date = models.DateTimeField(verbose_name="Datum objavljivanja")        class Meta:          ordering = ["pub_date", "question_text"]          verbose_name = "Pitanje"          verbose_name_plural = "Pitanja"        def __str__(self):          return self.question_text        def was_published_recently(self):          now = timezone.now()          return now - datetime.timedelta(days=1) <= self.pub_date <= now        def verbose_question_text(self):          return f"Pitanje: {self.question_text}"      class Choice(models.Model):      question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="choices", verbose_name="Pitanje")      choice_text = models.CharField(max_length=200, verbose_name="Tekst opcije")      # votes = models.IntegerField(default=0, verbose_name="Glasovi")        class Meta:          ordering = ["-votes", "pk"]          verbose_name = "Opcija"          verbose_name_plural = "Opcije"        def __str__(self):          return self.choice_text      class Vote(models.Model):      choice = models.ForeignKey(Choice, on_delete=models.CASCADE, related_name="votes", verbose_name="Opcija")        def __str__(self):          return self.choice.choice_text  

P. S.: If you think the voting could be solved in a better way, please suggest it too.

Django - JQuery autocomplete custom select from multiple fields

Posted: 17 Jul 2021 09:06 AM PDT

I have a user search that autocompletes by both ticker and name. The search results come back as "{{ticker}} - {{name}}". When a result is selected, I want it to fill with only the ticker, where as it currently fills with "{{ticker}} - {{name}}".

Here is my python code:

if 'term' in request.GET:      tickers = Company.objects.filter(ticker__istartswith = request.GET.get('term')) | Company.objects.filter(name__istartswith = request.GET.get('term'))      companies = []      for ticker in tickers:          companyTicker = ticker.ticker +  " - " + ticker.name          companies.append(companyTicker)      return JsonResponse(companies, safe=False)  

and here is my javascript:

    <script>      $( function() {        $( "#ticker3" ).autocomplete({          source: '{% url "financials:get_financials" %}',          select: function (event, ui) {              ticker.ticker          }        });      } );      </script>  

Any help greatly appreciated!

Why is movl preferred to movb when translating a C downcast from unsigned int to unsigned char

Posted: 17 Jul 2021 09:06 AM PDT

Considering a pared-down example of down-casting unsigned to unsigned char

void unsigned_to_unsigned_char(unsigned *sp, unsigned char *dp)  {    *dp = (unsigned char)*sp;  }  

The above C code is translated to assembly code with gcc -Og -S as

movl    (%rdi), %eax  movb    %al, (%rsi)  

I am wondering for what reason the C-to-assembly translation is not as below?

movb    (%rdi), %al  movb    %al, (%rsi)  

Is it because this is incorrect, or because movl is more conventional, or shorter in encoding, than is movb?

How can I : Read Text File with binary number using pandas in python and convert or keep (00001101)into binary as my function need as '0b00001101'?

Posted: 17 Jul 2021 09:08 AM PDT

from sgposit.pcposit import PCPosit  x = 0b00000011  y = 0b00000011  a = PCPosit(x, mode='bits', nbits=8, es=2)  

`Simple code, where I would like to get the value of "a" as 'Binary'. I have been trying to to do using pandas as CSV file. Also was trying to do as text file.

But The difficulties are the value of "x" & "y". For These, I have text_file.text of 256 data. Which I have to read into python and take those values as input for "a".

Here, the main question is how could I read a text_file.text file and have to keep it in this (0b00110001). It should not be an 'str' or '110001'- without initial zero or '0b00110001' or '0b110001'.

enter image description here

How can i convert python ssl cipher to php curl

Posted: 17 Jul 2021 09:08 AM PDT

I want to convert python ssl cipher code to php curl code. But in curl cipher not working, getting empty output. Where was the problem... Also i have not good knowledge about python and python module. I don't know about Cryptodome, urllib3, poolmanager and which cert uses in ssl.CERT_REQUIRED session.

Python:

from Cryptodome.Cipher import PKCS1_OAEP  from Cryptodome.PublicKey import RSA  from Cryptodome.PublicKey.RSA import RsaKey  import ssl  from typing import Any, Iterable  from urllib3.poolmanager import PoolManager    CIPHERS = [      "ECDHE+AESGCM",      "ECDHE+CHACHA20",      "DHE+AESGCM",      "DHE+CHACHA20",      "ECDH+AES",      "DH+AES",      "RSA+AESGCM",      "RSA+AES",      "!aNULL",      "!eNULL",      "!MD5",      "!DSS",  ]      class SSLContext(ssl.SSLContext):      """SSLContext wrapper."""        def set_alpn_protocols(self, alpn_protocols: Iterable[str]) -> None:          """          ALPN headers cause Google to return 403 Bad Authentication.          """    class AuthHTTPAdapter(requests.adapters.HTTPAdapter):      """HTTPAdapter wrapper."""        def init_poolmanager(self, *args: Any, **kwargs: Any) -> None:          """          Secure settings from ssl.create_default_context(), but without          ssl.OP_NO_TICKET which causes Google to return 403 Bad          Authentication.          """          context = SSLContext()          context.set_ciphers(":".join(CIPHERS))          context.options |= ssl.OP_NO_COMPRESSION          context.options |= ssl.OP_NO_SSLv2          context.options |= ssl.OP_NO_SSLv3          context.post_handshake_auth = True          context.verify_mode = ssl.CERT_REQUIRED          self.poolmanager = PoolManager(*args, ssl_context=context, **kwargs)  

Trying php curl:

$ciphers = implode(',', array(                  'ECDHE+AESGCM',                  'ECDHE+CHACHA20',                  'DHE+AESGCM',                  'DHE+CHACHA20',                  'ECDH+AES',                  'DH+AES',                  'RSA+AESGCM',                  'RSA+AES',                  '!aNULL',                  '!eNULL',                  '!MD5',                  '!DSS'              ));                curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, FALSE);              curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, true);              curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);              curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, TRUE);              curl_setopt ($ch, CURLOPT_SSL_CIPHER_LIST, $ciphers);  

How to correctly use clf.predict_proba?

Posted: 17 Jul 2021 09:08 AM PDT

My goal is to have the three most accurate predicted label.

By using this solution

clf = svm.SVC(                    kernel='rbf',                  C=51,                  gamma=1,                  probability=True                ).fit(X,y)    predictions=[]  with open('model.pkl', 'rb') as f:               clf = pickle.load(f)  for line in X:          output=clf.predict(X)                        #predictions.append(output)  df['prediction'] = output  # you add the list to the dataframe, then save the datframe to new csv    print(df)          

I'm able to retrive the predicted label. However, when I add the clf.predict_proba(X) as follows

clf = svm.SVC(                    kernel='rbf',                  C=51,                  gamma=1,                  probability=True                ).fit(X,y)    predictions=[]  with open('model.pkl', 'rb') as f:               clf = pickle.load(f)  for line in X:          output=clf.predict(X)          output_prob=clf.predict_proba(X)              #predictions.append(output)  df['prediction'] = output  # you add the list to the dataframe, then save the datframe to new csv    print(df)            

I'm having the following error:

AttributeError: predict_proba is not available when  probability=False  

According to the Scikit documentation the probability as True should be defined explicitly as I did in

clf = svm.SVC(                    kernel='rbf',                  C=51,                  gamma=1,                  probability=True                ).fit(X,y)  

How to fix this issue?

Thanks

No tests were found / Test events were not received

Posted: 17 Jul 2021 09:08 AM PDT

Hello I have a issue with Gradle and IntelliJ that appeared from nowhere. Everything was working but one day it stop to work. I am talking about any interaction with Gradle in IntelliJ. I have Spring Boot app, Gradle 6.7. When there is no .gradle directory in the root, everything works. If the directory is present I gets

Main class name has not been configured and it could not be resolved

for gradle build or

Test events were not received

for gradle test. If I delete .gradle directory one gradle task is completed fine and the some goes again and again. If I try to run test by IntelliJ runner with .gradle directory present I get

No tests were found

I noticed that after first build, build directory contains everything as expected. But when I run another task, build directory emptied somehow and I believe that the absence of compiled sources leads to the errors.

I have no vintage-engine on classpath, only jupiter for junit tests.

I tried to clear gradle cache, invalidate IntelliJ caches, both in the same time, reinstall IntelliJ with by older version, uninstall IntelliJ completely and install new one. Nothing helped.

Does anybody has an idea how to solve it?

Thanks

UPDATE:

build.gradle on what I am able to reproduce the issue:

plugins {      id 'org.springframework.boot' version '2.5.2'      id 'io.spring.dependency-management' version '1.0.11.RELEASE'      id 'java'  }    group = 'com.example'  version = '0.0.1-SNAPSHOT'  sourceCompatibility = '11'    repositories {      mavenCentral()  }    dependencies {      implementation 'org.springframework.boot:spring-boot-starter'      testImplementation 'org.springframework.boot:spring-boot-starter-test'  }    test {      useJUnitPlatform()  }  

I found that the file which is causing the behavior is executionHistory.bin. If the file is present, it ruins a build.

Axon - PostgreSQL - Where is the payload in the event store?

Posted: 17 Jul 2021 09:06 AM PDT

I am currently setting up an event-store with Axon-framework in PostgreSQL (spring boot, axon-spring-boot-starter, axon-server-connector removed from the dependency).

The system loads as expected and I am able to see commands, events and event handlers working as expected.

The issue is when I want to see the contents of my events in the event table (domain_event_entry) .

I would expect that the 'payload' column in the table containing all the events that I persisted in the event store, but I am just seeing numbers: something like this:

global_index | event_identifier | metadata |payload_type | 1 | 7c23e693-558b-4013-b64f-3f272cb0102a |19435 |19436|

Also, I believe that the metadata should contain something other tha n an integer.

Is this correct? Am I missing some extra configuration?

Gradle not building java application consistently

Posted: 17 Jul 2021 09:06 AM PDT

I am trying to understand gradle.

I followed the gradle tutorial here: https://docs.gradle.org/current/samples/sample_building_java_applications.html#what_youll_build

In short:

  1. I created a folder: mkdir demo
  2. cd demo
  3. gradle init (so far so good)

Now, I tried to run my application like this: gradlew run.

The first run of the application was successful. However, the subsequent runs kept failing and I got a very non descript error.

> Task :app:run FAILED  Error: Could not find or load main class demo.App    FAILURE: Build failed with an exception.    * What went wrong:  Execution failed for task ':app:run'.  > Process 'command 'C:\Program Files\Java\jdk1.8.0_211\bin\java.exe'' finished with non-zero exit value 1    * Try:  Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.    * Get more help at https://help.gradle.org    BUILD FAILED in 3s  2 actionable tasks: 1 executed, 1 up-to-date  

Then, I deleted the files inside "Z:\Projects\demo\ .gradle\6.7.1\executionHistory" and I was able to run the application again.

This was happening again and again. Please see attached screenshot:

enter image description here

What am I doing wrong -- how do I fix this so that all calls to 'gradlew run' give me a successful build?

Edit:

I tried it on C: and was able to do 'gradlew run' consistently and get the 'Hello World' output without any issues. My Z drive is actually an encrypted VeraCrypt file which has been loaded with letter 'Z'. Not sure if that is causing problems.

Thanks!

Why does npx install webpack every time?

Posted: 17 Jul 2021 09:07 AM PDT

I have a JavaScript app I'm bundling with webpack. Per the docs, I'm using this command to start bundling:

npx webpack  

Each time I get this output:

npx: installed 1 in 2.775s  

I've verified that the webpack command exists in my ./node_modules/.bin directory where npx is looking. Can anyone think of why it's downloading webpack every time? It can take up to 7 seconds to complete this step, which is slowing down my builds.

Get a list of dates between two dates

Posted: 17 Jul 2021 09:07 AM PDT

Using standard mysql functions is there a way to write a query that will return a list of days between two dates.

eg given 2009-01-01 and 2009-01-13 it would return a one column table with the values:

 2009-01-01    2009-01-02    2009-01-03   2009-01-04    2009-01-05   2009-01-06   2009-01-07   2009-01-08    2009-01-09   2009-01-10   2009-01-11   2009-01-12   2009-01-13  

Edit: It appears I have not been clear. I want to GENERATE this list. I have values stored in the database (by datetime) but want them to be aggregated on a left outer join to a list of dates as above (I am expecting null from the right side of some of this join for some days and will handle this).

No comments:

Post a Comment