Thursday, July 1, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Closing a iframe popup -cross domain

Posted: 01 Jul 2021 09:21 AM PDT

I have a jsp which opens a iframe loading an angular application. Both are on different domains. Once the user enters the data and clicks save on the iframe, i want the iframe to close and return to my application. But unfortunately as both are in different domains its now allowing it to close the iframe. Please let me know if there are any suggestions. Tried allowing the xframe options but its showing "uncaught domexception blocked a frame with origin angular"

jsp code :

How Can I add a cell double click event in PyQt5

Posted: 01 Jul 2021 09:21 AM PDT

I'm trying to add an on double click event to the table on my PyQt app, I'm not extremely clear on how signals work. Currently when I run this code and navigate to where the table will be generated, I am met with an error that reads:

"TypeError: native Qt signal is not callable"

I have the following things imported:

import sys  import os  import PyQt5  from PyQt5 import QtWidgets as qtw  from PyQt5.QtWidgets import QTableWidget,QTableWidgetItem  from PyQt5 import QtGui  

The Table is generated just fine, until I try to add the event:

def makeTable(self, dataSet, layout):      cols = len(dataSet[0]) #columns      rows = len(dataSet) #rows        table = qtw.QTableWidget()      table.setRowCount(rows)      table.setColumnCount(cols)        for i in range(len(dataSet)):          for j in range(len(dataSet[i])):              table.setItem(i,j, QTableWidgetItem(dataSet[i][j]))              table.cellDoubleClicked(i, j).connect(self.cellClick(i, j, dirList, layout)) #<-Line In Question      layout.addWidget(table)  

Current Test cellClick Function to test that the double click works:

    def cellClick(self, r, c, dirList, layout):          print('here: ', r, ' ', c)  

Note: I appologize for this not exactly being a "Minimum reproducible example", but I tried to include as little code as possible, especially because I'm fairly certain the issue is very small and has to do with my syntax. Thank you and please let me know if I need to make any edits.

Starshipit / DHL DEC does not import "commodity_code" from product

Posted: 01 Jul 2021 09:20 AM PDT

We are using DHL Express for shipping about half our orders. We have been using a magento extension for creating labels for a few years now. Since starting from this month it is a requirement to add HS codes to all order items we have been asked to move to DEC, which is a DHL branded version of starshipit. According to their customer service, all that is needed to do is to add the field "commodity_code" as a product attribute and it will be automatically be imported. But that is not the case. Starshipit support reported that the "commodity_code" fields appears "null" at the api. I have added a HS code to all products, so the issue must be with the api. Support says that if I can show them a way that this custom attribute can be called from api they will make it happen for us. Now the question is: How can this be done? I have no idea and really need to get this to work. Any advise is appreciated!!!

We are using magento 1.9.3.2

I am getting an error when I try "npm install gh-pages --save-dev". This is for hosting website on GitHub. Kindly assist

Posted: 01 Jul 2021 09:20 AM PDT

(base) XXXXXXX@XXXXs-MacBook-Pro portfolio copy % npm install gh-pages --save-dev

> npm ERR! code ENOTEMPTY  > npm ERR! syscall rename  > npm ERR! path /Users/xxxxxxxxx/Desktop/portfolio copy/node_modules/jest-changed-files/node_modules/which  > npm ERR! dest /Users/xxxxxxxxx/Desktop/portfolio copy/node_modules/jest-changed-files/node_modules/.which-D8F24LMI  > npm ERR! errno -66  > npm ERR! ENOTEMPTY: directory not empty, rename '/Users/XXXXX/Desktop/portfolio copy/node_modules/jest-changed-files/node_modules/which' -> '/Users/xxxxxxxx/Desktop/portfolio copy/node_modules/jest-changed-files/node_modules/.which-D8F24LMI'    > npm ERR! A complete log of this run can be found in:  > npm ERR!     /Users/XXXXXXXX/.npm/_logs/2021-07-01T16_12_29_442Z-debug.log  

Flutter isSBSettingEnabled

Posted: 01 Jul 2021 09:20 AM PDT

Samsung Android 9 is throwing isSBSettingEnabled false then not sending a multipart request. I have created a custom network security config, enabled HTTP legacy in android manifest, and tried allowing clear traffic. I have even tried using an HTTP Client lib such as Dio.

I get a successful http GET request, however when attempting to send a MultiPartRequest the isSBSettingEnabled false shows and the POST request is never sent. There is no error being logged.

Any help is appreciated.

Thank you :)

accessing methods of an object

Posted: 01 Jul 2021 09:20 AM PDT

First up some information about the system:

  • PHP 7.4
  • WordPress 5.7.2
  • WooCommerce 5.4.1
  • Germanized for WooCommerce 3.5.0 Github
  • Germanized for WooCommerce pro 3.2.3

I can't use WP_DEBUG, var_dump or echo unfortunately.

I use the "Germanized" plugin for the shipping provider DHL and other things but the problem is with DHL.
I am trying to set the customerReference on the label to the items that are inside. The good thing is, there is a filter for that so I wrote this in the functions.php in my child-theme:

<?php  ...other stuff...    add_filter( 'woocommerce_gzd_dhl_label_customer_reference', 'addItemsToLabelReference', 10, 3 );    function addItemsToLabelReference($ref, $label, $shipment ) {        return $ref;  }    ?>  

This code would just return the reference as it comes from the plugin. I can however access the $shipment object to retrieve the items.
I am able to call get_items() to get an array of ShipmentItems.
The problem starts when I want to get the sku. When I loop through the array with a foreach loop and I call get_sku the website just crashes and doesn't work anymore. I think this is more a PHP issue than a WooCommerce issue.
The code I tried is this:

function addItemsToLabelReference($ref, $label, $shipment ) {            foreach($shipment->get_items() as $item){          $sku = $item->get_sku();          $quantity = $item->get_quantity();       }      return $ref  }  

The source code for the $item class can be found here
I'm afraid I don't have an error message/code, I just get the White-Screen-of-Death.

Thanks for the help in advance!

How to fix "PermissionError: [Errno 13] Permission denied" in cx_Freeze?

Posted: 01 Jul 2021 09:20 AM PDT

I have a program that downloads youtube videos from their links. It uses PyTube and PySide. PyTube to download the video, and PySide to create the GUI. Then I use cx_Freeze to create an exe for the program and then use inno setup to create a proper installer. But when I create an exe for the app and run it and try to download a youtube video I get this error in the console of the cx_Freeze exe app.

Here is the error:

Traceback (most recent call last):    File "C:\Users\User\Desktop\PythonProjects\Personal Projects\YTDownloader\screens\download_screen.py", line 41, in <lambda>      self.download_button.clicked.connect(lambda: self.download_video())    File "C:\Users\User\Desktop\PythonProjects\Personal Projects\YTDownloader\screens\download_screen.py", line 112, in download_video      video.download(output_path=output_dir, filename=file_name)    File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\streams.py", line 256, in download      with open(file_path, "wb") as fh:  PermissionError: [Errno 13] Permission denied: 'C:/Users/User/Desktop\\test1.mp4'  

Here is the setup.py:

import sys  from cx_Freeze import setup, Executable    # ADD FILES  files = ['icons/icon.ico', 'icons/', 'menu_bar.py', 'main.qss', 'menu_bar.qss', 'screens/', 'menu_icons/']    build_exe_options = {"packages": ["os"], 'include_files': files}    target = Executable(      script="main.py",      icon="icons/icon.ico"  )    setup(      name="Test",      version="1.0",      description="Test",      author="Test",      options={'build_exe': build_exe_options},      executables=[target]  )  

and here is the code for downloading the video

    def download_video(self):          url = "https://yamiatem.github.io/YTDownloader/"          timeout = 5          link = self.link_entry.text()          file_name = self.filename_entry.text()          output_dir = self.output_directory          self.progress_bar.show()          self.app.processEvents()            try:              request = requests.get(url, timeout=timeout)          except (requests.ConnectionError, requests.Timeout) as exception:              self.progress_bar.hide()              ctypes.windll.user32.MessageBoxW(0, "You are not connected to the internet", "Error", 0)              return            if link == "":              self.progress_bar.hide()              ctypes.windll.user32.MessageBoxW(0, "Youtube link is required", "Error", 0)              return          elif file_name == "":              self.progress_bar.hide()              ctypes.windll.user32.MessageBoxW(0, "File name is required", "Error", 0)              return          elif file_name == "":              self.progress_bar.hide()              ctypes.windll.user32.MessageBoxW(0, "File name is required", "Error", 0)              return          elif output_dir == "":              self.progress_bar.hide()              ctypes.windll.user32.MessageBoxW(0, "Output directory is required", "Error", 0)              return            try:              yt = YouTube(link)          except exceptions.PytubeError as e:              self.progress_bar.hide()              ctypes.windll.user32.MessageBoxW(0, "YouTube video link is invalid", "Error", 0)              return            self.app.processEvents()            video = yt.streams.filter(progressive=True, mime_type="video/mp4", file_extension="mp4").first()          file_size = video.filesize            self.app.processEvents()            def video_progress(chunk, file_handler, bytes_remaining):              percent = abs(round((float(bytes_remaining) / float(file_size) * float(100)) - 100))              self.progress_bar.setValue(percent)              self.app.processEvents()            yt.register_on_progress_callback(video_progress)          video.download(output_path=output_dir, filename=file_name)            self.app.processEvents()            self.progress_bar.reset()          self.progress_bar.hide()          ctypes.windll.user32.MessageBoxW(0, "Done Downloading Video!", "Info", 0)            self.app.processEvents()  

So how can I fix this? or is there something I am doing wrong?

Python create a list with the values of another list

Posted: 01 Jul 2021 09:21 AM PDT

unfortunately i found an unexcepted issue in my code and i just cant fix it. Sorry for the simplicity of the problem, but i am just started to learn python.

Here's the prototype of my code:

a = [1,2,3,4]  b = a  b[0]=0  

Now my problem is, that this method change not just the variable b, but the variable a too.(I think, in this way i created a pointer, cause the id of the lists is the same.) I need a solution, where just the b list will change. I really hope, that you can help, thank you.

Javascript array push don't working on Ajax

Posted: 01 Jul 2021 09:21 AM PDT

Iam trying to get data from a text file through javascript Ajax response to a array but it doesn't work, I have tried many things to solve this but everything fails. How can I solve it?

Here is what I have done

const search = ["search"];    function toggleSearch() {    var x = document.getElementById("search");    if (x.style.display === "none") {      x.style.display = "block";    } else {      x.style.display = "none";    }  }    var xhttp = new XMLHttpRequest();  xhttp.onreadystatechange = function () {    if (this.readyState == 4 && this.status == 200) {      var adable = this.responseText;      search.push(adable);    }  };  xhttp.open("GET", "https://cloud.educlick.page/cloud/ATC.txt", true);  xhttp.send();  

ATC.txt file :

Banana, Orange, Apple, Mango  

I have also tried :

"Banana", "Orange", "Apple", "Mango"  

How can i resolve this?

selecting only NON NULL values in Oracle sql table

Posted: 01 Jul 2021 09:20 AM PDT

I have a table that has 40 columns/headers and 15 rows(may vary due to the high volume records); In the records/data, many columns which have NULL values or in other words, these columns were not in a production environment, so no validation required or to list in the output. I wanna list only the NON NULL values(Column vise) in the select table even if the entire Column is NULL.

Prevent macOS from populating application's "View" menu with its own options

Posted: 01 Jul 2021 09:21 AM PDT

While we're writing Mac App and populating the macOS (top)menu-bar with our application-specific options, we noticed macOS adds a few of its own options at runtime, in the "View" menu:

  1. Show Tab Bar
  2. Enter Full Screen

While these macOS' added options do nothing(when clicked) we found it's difficult to remove them as well since they seem to be get added during the "View" menu opening.

The only option we found is alter the menu label to something but "View", that prevents macOS from populating its own items in the menu. But we generally don't like to change the label "View".

Is there any way or entitlement is available by using which we can prevent macOS from populating in the "View" menu?

TypeScript conditional return type based on return value?

Posted: 01 Jul 2021 09:21 AM PDT

I have this code:

type SuccessResponse = {    success: true;    image: string;  };    type FailResponse = {    success: false;    message: string;  };    type OpenGraphScraperResponse = SuccessResponse | FailResponse;    export const useOpenGraphScraper = (text: string, guid: string) => {    return useQuery(['og', guid], () => {      return axios        .get<OpenGraphScraperResponse>(`/api/open-graph-scraper?content=${text}`)        .then((res) => res.data);    });  };  

I like the return type to be SuccessResponse whenever the data returned contains success: true and FailResponse whenever it's success: false.

In my template, I want to access the image property so I did it like this:

<div v-if="result.success">      <img :src="result.image" />  </div>  

Even though I wrapped it inside a condition where it should only render the img element when success: true, TypeScript still complains:

Property 'image' does not exist on type 'SuccessResponse | FailResponse'.    Property 'image' does not exist on type 'FailResponse'.  

How to combine rows in a dataframe in a pairwise fashion while applying some function

Posted: 01 Jul 2021 09:20 AM PDT

I have a dataframe that stores keys as ID, and some numerical values in Val1/Val2:

ID    Val1    Val2  id0     10      20  id0     11      19  id1      5       5  id1      1       1  id1      2       4  

I would like to go over this dataframe and combine the rows pairwise while getting the averages of Val1/Val2 for rows with the same ID. A suffix should be appended to the new row's ID based on which number pair it is.

Here is the resulting dataframe:

ID      Val1    Val2  id0_1   10.5    19.5  id1_1   3       3  id1_2   1.5     2.5  

In this example, there are only 3 rows left. (id0, 10, 20) gets averaged with (id0,11,19) and combined into one row.

(id1,5,5) gets averaged with (id1,1,1,) and (id1,1,1) gets averaged with (id1,2,4) to form 2 remaining rows.

I can think of an iterative approach to this, but that would be very slow. How could I do this in a proper pythonic/pandas way?

Code:

df = pd.DataFrame(columns=['ID', 'Val1', 'Val2'], data=[['id0', 10, 20], ['id0', 11, 19], ['id1', 5, 5], ['id1', 1, 1], ['id1', 2, 4]])  

Convert String Array to int using JOptionPane

Posted: 01 Jul 2021 09:21 AM PDT

I'm doing a train ticket program. I want to convert certain text in the string array to a certain price using JOptionPane.

ex.

String[] option_1 = {"location1","location2", "location3","location4","location5"};  

where location1 = $10, location2 = $23, etc.

all I know is I could use Interger.parseInt or double, but I don't know where to go next. Should I go with a loop or make a whole new array and make it equal to the string array. I'm wondering if there is a more easier method to execute this.

code :

public static void main (String [] args) {          String name;                                String[] option_1 = {"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};          String[] option_2 = {"North Avenue","Quezon Avenue", "Kamuning","Cubao","Santolan","Ortigas","Shaw","Boni","Guadalupe","Buendia","Ayala","Magallanes","Taft"};                    name = JOptionPane.showInputDialog("Welcome to DME Ticketing System!\n\nEnter your name:");          String leave = (String)JOptionPane.showInputDialog(null, "Leaving from",                   "Train Station", JOptionPane.QUESTION_MESSAGE, null, option_1, option_1[0]);                    String  going = (String)JOptionPane.showInputDialog(null, "Leaving from",                   "Train Station", JOptionPane.QUESTION_MESSAGE, null, option_2, option_2[0]);         // int  pay = (Integer)JOptionPane.showInputDialog(null, "From: "+leave+"\nTo: "+going+"\nFare Price: "+"\n\nEnter your payment amount:",              // null, JOptionPane.PLAIN_MESSAGE, null, null,null);              // int op1 = Integer.parseInt(going);          // int op2 = Integer.parseInt(leave);                               JOptionPane.showMessageDialog(null, "DME Ticketing System\nMalolos, Bulacan\n\n"                  + "Name: "+name                  +"\nLocation: "+leave                  +"\nDestination: "+going                  +"\nFare: "                  +"\nPayment: "//+pay                  +"\nChange: "                  , "RECEIPT",JOptionPane.INFORMATION_MESSAGE);      }  

-The codes I turned into comments are giving me errors

In VueJS version 3, What is the correct way to Show and Hide the Login & Logout <router-link> links and viceversa which is placed on Nav Bar?

Posted: 01 Jul 2021 09:20 AM PDT

I am newbie to VueJS. I have developed a simple Login Screen. After successful Login, Server will send userId in JSON format. I am storing this userId in localStorage. Using this, I thought of showing the Login (before Login). Post Login, 1. the Logout should be displayed and not Login & 2. Login Component should be displayed on logout click

In current code, Post Login, Logout link is not visible. I also tried v-else logic. That also did not worked. referce https://forum.vuejs.org/t/update-navbar-login-logout-button/103509

Let me know what mistake is there in the below code. Thanks in advance.

App.vue

<template>  <div id="app">    <Nav/>      <router-view />  </div>    </template>    <script>  import  Nav from './components/Nav.vue'        export default {    name: 'App',    components: {      Nav    },    data() {      return {        form: {                   username:'',          password:''        },        showError: false      };    },          };  </script>      <style>      @import url('htpp://fonts.googleapis.com/css?family=Fira+Sans:400,500,600,700,800');    * {  box-sizing:border-box;  }    body{    background: #fcfdfd !important;      }    body, html,#app, #root, .auth-wrapper{  width :100%;  height:100%;  padding-top:30px;  }      #app{  text-align:center;  }    .navbar-light{    background-color: #167bff;  box-shadow:0px 14px 80px rgba (34,35,58,0.2);    }      .custom-control-label{  font-weight:100;  }    .forgot-password, .forgot-password a{  text-align : right;  font-size : 13px;  padding-top:10px;  color:#7f7d7d;  margin:0;  }  .forgot-password a{   color:#167bff;  }  </style>  

Nav.vue

<template>      <nav class="navbar navbar-expand navbar-light fixed-top">       <div class="container">      <router-link to="/" class="navbar-brand" > Test Data Generator </router-link>        <div class="collapse navbar-collapse">        <ul class="navbar-nav ml-auto">                  <li class="nav-item" v-if="isLoggedIn==null">             <router-link to="/login" class="nav-link"> Login  </router-link>          </li>           <li class="nav-item" v-else >            <router-link @click="handleLogout" class="nav-link"> Logout   </router-link>          </li>        </ul>        </div>        </div>      </nav>  </template>      <script>  export default {    name:'Nav',      computed: {     isLoggedIn() {      return window.localStorage.getItem("userId");    }  },    methods:{            handleLogout(){              localStorage.removeItem('userId');              this.$router.push('/login');            }          }    }    </script>     <style>        nav .navbar-nav   li a{    color: white !important;    }    </style>  

Login.vue

<template>  <div class="auth-wrapper">    <div class="auth-inner">      <h4>Login</h4>                  <p>          <label>Username</label>          <input type="text"  v-model="state.username" placeholder="Username" class="form-control"/>                        </p>                 <p>          <label>Password</label>          <input type="password" class="form-control"  v-model="state.password"  placeholder="Password"/>                        </p>            <button @click="handleLogin"  class="btn btn-primary btn-block">Login</button>             </div>  </div>    </template>        <script>    import { required } from '@vuelidate/validators'  import useValidate from '@vuelidate/core'  import axios from 'axios'  import { apiHost } from '../config'  import {reactive, computed} from 'vue'    export default {      name:'Login',      setup() {          const state = reactive({              username:'',              password:'',          })            const rules=computed(() => {                   return {                  username: { required },                  password: { required },          }      })            const v$ =  useValidate(rules,state)            return{              state,v$,          }   },               methods:{          async  handleLogin(){              this.v$.$validate()              if (!this.v$.$error) {              const loginURL=apiHost+'authenticate';              const response = await axios.post(loginURL,{                      username:this.state.username,                      password: this.state.password              });              console.log(response);              localStorage.setItem('userId',response.data.userId);              this.$router.push('/hello');            }else{                alert('Please enter username and password.')            }          }      }  }  </script>    <style>  .auth-wrapper{  display:flex;  justify-content:center;  flex-direction:column;  text-align:left;    }      .auth-inner{    width:300px;  margin :auto;  background: #167bff;  box-shadow:0px 14px 80px rgba (34,35,58,0.2);  padding:40px 55px 45px 55px;  border-radius:15px;  transition: all .3s;   }  .auth-wrapper .form-control:focus{  border-color:#167bff;  box-shadow:none;  }      .auth-wrapper h4{  text-align:center;  margin:0;  line-height:1;  padding-bottom:20px;    }    </style>  

SCAPY method seems not to get called

Posted: 01 Jul 2021 09:20 AM PDT

I used some code from packetgeeks.com. I remember this be running correctly in the past. While digging it up now, i cant get it to give me any results.

from scapy.all import DNS, DNSQR, DNSRR, IP, send, sniff, sr1, UDP  IFACE = "lo0"   # Or your default interface  DNS_SERVER_IP = "127.0.0.1"  # Your local IP  BPF_FILTER = f"udp port 53 and ip dst {DNS_SERVER_IP}"    def dns_responder(local_ip: str):        def forward_dns(orig_pkt: IP):          print(f"Forwarding: {orig_pkt[DNSQR].qname}")          response = sr1(              IP(dst='8.8.8.8')/                  UDP(sport=orig_pkt[UDP].sport)/                  DNS(rd=1, id=orig_pkt[DNS].id, qd=DNSQR(qname=orig_pkt[DNSQR].qname)),              verbose=0,          )          resp_pkt = IP(dst=orig_pkt[IP].src, src=DNS_SERVER_IP)/UDP(dport=orig_pkt[UDP].sport)/DNS()          resp_pkt[DNS] = response[DNS]          send(resp_pkt, verbose=0)          return f"Responding to {orig_pkt[IP].src}"        def get_response(pkt: IP):          if (              DNS in pkt and              pkt[DNS].opcode == 0 and              pkt[DNS].ancount == 0          ):              if "trailers.apple.com" in str(pkt["DNS Question Record"].qname):                  spf_resp = IP(dst=pkt[IP].src)/UDP(dport=pkt[UDP].sport, sport=53)/DNS(id=pkt[DNS].id,ancount=1,an=DNSRR(rrname=pkt[DNSQR].qname, rdata=local_ip)/DNSRR(rrname="trailers.apple.com",rdata=local_ip))                  send(spf_resp, verbose=0, iface=IFACE)                  return f"Spoofed DNS Response Sent: {pkt[IP].src}"                else:                  # make DNS query, capturing the answer and send the answer                  return forward_dns(pkt)        return get_response    sniff(filter=BPF_FILTER, prn=dns_responder(DNS_SERVER_IP), iface=IFACE)  

Normally program returns info or interact when dns info is polled. If a DNS query for certain domain is called, the sender of the dns response will be changed. If not normall dns infor will be sent.

When code execution is monitored the dns_responder(local_ip: str) gets called. The call for get_response whithin does not take place. To trigger the dns_responder methode, I use ping "domainname" and nslookup "domainname".

Am i overseeing something? I can recall this code works correctly.

Can someone have a look what i missed? For me get_response attribute is not triggered.

Extract key value from free text using Regex

Posted: 01 Jul 2021 09:22 AM PDT

Let's say I have this free text

unitType:unit_failure;unitId:b7eb;unitTitle:L1-O VEN_ACC_SETTINGS>(30s)>EXCL(A);applicable:true;comment:Decline sender:SELLER;Decline reason:VEN_ACC_SETTINGS;triggered by user:495259708;Display reason: CON_FAILURE;modified by: log_res_mon  

I want to extract the values into an object that has the same property names.

public class Values  {      public string UnitType { get; set; }      public string UnitType { get; set; }      public string UnitTitle { get; set; }      public string Applicable { get; set; }      public string DeclineSender { get; set; }      public string DeclineReason { get; set; }      public string TriggeredByUser { get; set; }      public string DisplayReason { get; set; }      public string ModifiedBy { get; set; }  }  

so far I tried this code:

    string comment = "unitType:unit_failure;unitId:b7eb;unitTitle:L1-O VEN_ACC_SETTINGS>(30s)>EXCL(A);applicable:true;comment:Decline sender:SELLER;Decline reason:VEN_ACC_SETTINGS;triggered by user:495259708;Display reason: CON_FAILURE;modified by: log_res_mon";      string regex = @"(.*?:\s*)(\w*);?";        var matches = Regex.Matches(comment, regex);  

Which almost worked. but you can see that unitTitle was cut after L1-.

Another thing, comment: is an exception that can be dropped either by the expression, or I can simply drop it using .Replace.

enter image description here

  • How do I fix the expression to include the full value of unitTitle and to drop comment: (You can tell me it is easier to use .Replace)?

  • What is the best way to extract the values from matches and fill them in the object?

EDIT: I tried this, but it is really ugly, is there a better way? (Ignore that I'm using anonymous object, that is just for testing now).

    var obj = new      {          unitType = matches.Single(x => x.Groups[1].Value == "unitType").Groups[2].Value      };  

how to increase the value of a variable for each row

Posted: 01 Jul 2021 09:20 AM PDT

I have this dataframe,

dat= rep(c("A", "B", "C"),3)  tat=c(rep("ttt", 6), rep("aaa", 6), rep("ddd", 6))  pct=c(14,7,12,8,11,13,19,6,9,11,13,20,11,18,6,9,10,13)  data=data.frame(dat, tat, pct) %>% group_by(tat) %>% mutate(max= max(pct))    > data  # A tibble: 18 x 4  # Groups:   tat [3]     dat   tat     pct   max     <chr> <chr> <dbl> <dbl>   1 A     ttt      14    14   2 B     ttt       7    14   3 C     ttt      12    14   4 A     ttt       8    14   5 B     ttt      11    14   6 C     ttt      13    14   7 A     aaa      19    20   8 B     aaa       6    20   9 C     aaa       9    20  10 A     aaa      11    20  11 B     aaa      13    20  12 C     aaa      20    20  13 A     ddd      11    18  14 B     ddd      18    18  15 C     ddd       6    18  16 A     ddd       9    18  17 B     ddd      10    18  18 C     ddd      13    18  

And I would like to create another variable that would increase the value of max by 1 for each row (group by the variable tat). Please find an example of what I wand below. Is there someone that have an idea to do that ?

> data2  # A tibble: 18 x 5  # Groups:   tat [3]     dat   tat     pct   max  ...5     <chr> <chr> <dbl> <dbl> <dbl>   1 A     ttt      14    14    14   2 B     ttt       7    14    15   3 C     ttt      12    14    16   4 A     ttt       8    14    17   5 B     ttt      11    14    18   6 C     ttt      13    14    19   7 A     aaa      19    20    20   8 B     aaa       6    20    21   9 C     aaa       9    20    22  10 A     aaa      11    20    23  11 B     aaa      13    20    24  12 C     aaa      20    20    25  13 A     ddd      11    18    18  14 B     ddd      18    18    19  15 C     ddd       6    18    20  16 A     ddd       9    18    21  17 B     ddd      10    18    22  18 C     ddd      13    18    23      

time series forcasting/predictive maintenance [closed]

Posted: 01 Jul 2021 09:21 AM PDT

We have, like 1000 devices ( temperature censor) which send the temperature of an equipement every 10 min. which means that i ve got 1000 time series Data. and i want to build a model for predictive maintenance for those 1000 devices, knowing that each of those equipement has 5 components. ( those equipements are all the same). what im trying to do, is extract or search for some patterns in my data set and link it with it's defected component. I want to build a model for predictive maintenance, I want my model to give details about: -Failure state

  • Failure Time Prediction -the component that will fall
  • when the maintenance is needed to avoid possible failure.

I have the history of the maintenance that is done regulary, and the state of each component. the time series dataset and the history of the failure. history of the maintenance' columns :

-----------------------------------------------------------  Equipements |component's state | Date  | Type of maintenance  ----------------------------------------------------------  

I have search and I fount a lot of model such as HMM or LSTM OR MMMM or (POMDP that I can use to solve the problem, but what Im finding hard to do is how can I build one model for the all 1000 devices.

How do you evaluate z = x-- == y + 1;

Posted: 01 Jul 2021 09:21 AM PDT

given that

int w = 1;  int x = 6;  int y = 5;  int z = 0;     z = !z || !x && !y;  printf("%d\n", z);    z = x-- == y + 1;  printf("%d\n", z);  

Could someone explain how the line below would evaluate to 1 if x-- is 5 and y+1 is 6?

z = x-- == y + 1;  

Connection string in .NET app to MsSQL under docker on MacOS

Posted: 01 Jul 2021 09:20 AM PDT

I am working on MacOS and ran MsSQL under docker. The connection string in appsettings.js is:

"ConnectionStrings": {      "DefaultConnection": "Data Source=localhost;Initial Catalog=InAndOut;Integrated Security=True;User ID=sa;Password=reallyStrongPwd123;"    },  

I successfully executed update-database in the PM console. But the site fails:

ArgumentNullException: Value cannot be null. (Parameter 'source') ...

The google says it is usually a connection string issue. Could you help me please to figure put what is wrong. I am an absolutely newbie in .NET

Here is the connection in DBeaver: connection

Swift UI list not updating on Cloudkit sync

Posted: 01 Jul 2021 09:20 AM PDT

I am trying to create a simple application that leverages CloudKit to sync between multiple iOS devices (via iCloud) and possibly macOS devices (still via iCloud).

Problem: I have a core data entity which seems to work great locally in my app. When I switch to using Cloudkit I am unable to see changes on another device without closing/reopening the app.

I am using the Cloudkit template in Xcode with the SwiftUI lifecycle. ie, PersistenceController and managed object context.

I think this is a view not refreshing issue, but am not 100% sure. Once the app on a different device is closed and reopened then it loads the new data successfully. This applies to additions and deletes.

Testing: I have tested this using Testflight as well as running two simulators locally.

Code:

PersistenceController.swift

  import CoreData    struct PersistenceController {      static var shared = PersistenceController()        static var preview: PersistenceController = {          let result = PersistenceController(inMemory: true)          let viewContext = result.container.viewContext          for i in 0..<10 {              let newItem = Card(context: viewContext)              newItem.cardValue = String(i)              newItem.cardOrder = Int32(i)          }          do {              try viewContext.save()          } catch {              // Replace this implementation with code to handle the error appropriately.              // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.              let nsError = error as NSError              fatalError("Unresolved error \(nsError), \(nsError.userInfo)")          }          return result      }()                  //Is this needed?      lazy var updateContext: NSManagedObjectContext = {          let _updateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)          _updateContext.parent = PersistenceController.shared.updateContext          return _updateContext      }()        let container: NSPersistentCloudKitContainer        init(inMemory: Bool = false) {          container = NSPersistentCloudKitContainer(name: "Cards")          if inMemory {              container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")          }            container.loadPersistentStores(completionHandler: { (storeDescription, error) in              if let error = error as NSError? {                  fatalError("Unresolved error \(error), \(error.userInfo)")              }          })            container.viewContext.automaticallyMergesChangesFromParent = true          container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy      }        }    

ContentView.swift

  import SwiftUI  import CoreData    struct ContentView: View {      @Environment(\.managedObjectContext) var managedObjectContext            @FetchRequest(entity: Card.entity(),                    sortDescriptors: [NSSortDescriptor(key: "cardOrder", ascending: true)])      var cards: FetchedResults<Card>                  var body: some View {                    NavigationView {              VStack {                  Text("Scrum +")                      .font(.largeTitle)                      .fontWeight(.regular)                                    Spacer()                  List(cards, id: \.id)  {card in                          NavigationLink(destination: PointRow(card: card)) {                                  PointRow(card: card)                          }                  }                                    Spacer()                  NavigationLink(destination: SettingsView().environment(\.managedObjectContext, self.managedObjectContext)  ) {                      Text("Card Settings")                  }                  .padding(.bottom)                                }          }      }  }  

SettingsView.swift (where saving/deleting/reordering happens)

  import SwiftUI    struct SettingsView: View {                  @State private var editMode = EditMode.inactive            @State private var showModal = false            @Environment(\.managedObjectContext) var managedObjectContext            @FetchRequest(sortDescriptors: [NSSortDescriptor(key: "cardOrder", ascending: true)])      var cards: FetchedResults<Card>                  var body: some View {          VStack {              Text("Card Values")                  .font(.largeTitle)              HStack {                  EditButton()                      .padding(.leading)                  Spacer()                  addButton                      .padding(.trailing)              }              .padding(.vertical)              List {                  ForEach(cards) {                      item in                      Text(item.cardValue!)                  }                  .onDelete(perform: onDelete)                  .onMove(perform: onMove)                  .environment(\.editMode, $editMode)              }                            .sheet(isPresented: $showModal) {                  //Show the view to add a new card.                  SettingsModal(showModal: self.$showModal, numberOfCards: cards.count).environment(\.managedObjectContext, self.managedObjectContext)              }          }      }                  private var addButton: some View {          switch editMode {          case .inactive:              return AnyView(Button(action: onAdd) { Image(systemName: "plus") })          default:              return AnyView(EmptyView())          }      }                        func onAdd() {          showModal = true      }                  func onDelete(indexSet: IndexSet) {          //        print("Deleting card at index -> " + indexSet.first)                    let cardToDelete = self.cards[indexSet.first!]          self.managedObjectContext.delete(cardToDelete)                    do {              try self.managedObjectContext.save()          } catch {              print(error)          }                    reorder()      }                  private func onMove(source: IndexSet, destination: Int) {                    //        pointCards.points.move(fromOffsets: source, toOffset: destination)                    //        source.                    let firstCard = self.cards[source.first!]                    //If there is a card located in the destination.          if (destination < self.cards.count) {              let secondCard = self.cards[destination]                                          let tmp = Int(secondCard.cardOrder)                            //Increment all place holders from the destination on.              for i in tmp..<self.cards.count {                  self.cards[i].cardOrder += 1              }          }                    firstCard.cardOrder = Int32(destination)                    do {              try self.managedObjectContext.save()          } catch {              print(error)          }                    self.managedObjectContext.refreshAllObjects()                    //Reorder just in case moved to the end.          reorder()      }                  private func reorder() {                    for i in 0..<cards.count {              cards[i].cardOrder = Int32(i)          }                    do {              try self.managedObjectContext.save()          } catch {              print(error)          }      }  }  

Screenshots of my Core Data model using Cloudkit and of the Entitlement selection. Capabilities

CoreData Properties

UPDATE: I have found the solution. The Persistent Controller should have the following three lines added to the init function:

          //Setup auto merge of Cloudkit data          container.viewContext.automaticallyMergesChangesFromParent = true          container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy                    //Set the Query generation to .current. for dynamically updating views from Cloudkit          try? container.viewContext.setQueryGenerationFrom(.current)  

Then this must be ran on real devices. For whatever reason I am unable to get this working in the simulator, but on real devices it syncs in about 30 seconds without closing the app.

Thanks everyone for your help!

React-Native - my state being reset after adding values to the current from specific component (panResponder)

Posted: 01 Jul 2021 09:20 AM PDT

I have a component that I built with useContext.

The problem is that my State (named myCartItems) is always being reset and I don't know why. The idea is to add more elements by calling the function addToCart with a product id. then I am trying to copy the current state, and then add the new product to it. But after I check it, I only get the first element every time.

I tried to use this without useContext and it worked. For some reason, it doesn't work when I use it with useContext.

Here is my component:

import React, { useState, useEffect } from 'react'  import { StyleSheet, Text, View, Image } from 'react-native'    const CartContext = React.createContext();    function CartProvider(props) {      const [myCartItems, setCartItems] = useState([]);        const addToCart = (product_id) => {      let tempArray = [...myCartItems];      const found = tempArray.some(product => product.id === product_id);      if (!found) tempArray.push({ id: product_id, count: 1 });      else {          for (let i = 0; i < tempArray.length; i++) {              if (tempArray[i].id == product_id) {                  tempArray[i].count = tempArray[i].count + 1;                  break;              }          }      }      setCartItems(tempArray);  }    return (      <CartContext.Provider          value={{              myCartItems,              addToCart,              resetCart          }}      >          {props.children}      </CartContext.Provider>  )}  

Why do I end up with only one object in the state myCartItems?

EDIT: *** I think the problem is the component I send the data from, it looks like when I call the same function from the Homepage - it works perfectly, but when I call it from another component, it happens.

import React, { useContext, useEffect, useState, useRef } from 'react';  import { Animated, PanResponder, View } from 'react-native';    import { CartContext } from './provider/CartProvider.js';    export default function DragItem(props) {      const context = useContext(CartContext);        const pan = useRef(new Animated.ValueXY()).current;        const panResponder = useRef(          PanResponder.create({              onMoveShouldSetPanResponder: () => true,              onPanResponderGrant: () => {                  pan.setOffset({                      x: pan.x._value,                      y: pan.y._value                  });              },              onPanResponderMove: Animated.event(                  [                      null,                      { dx: pan.x, dy: pan.y }                  ],                  {                      useNativeDriver: false,                      listener: (evt, gestureState) => {                        }                  }              ),              onPanResponderRelease: (evt, gestureState) => {                  //pan.flattenOffset();                  if (gestureState.moveY > 300) {                        Animated.spring(pan, {                          toValue: 0,                          useNativeDriver: false                      },                      ).start();                      context.addToCart(props.product_id);                    }                  else {                      Animated.spring(pan, {                          toValue: 0,                          useNativeDriver: false                      },                      ).start();                  }                }          })      ).current;        return (          <Animated.View              style={{                  transform: [{ translateY: pan.y }]              }}              {...panResponder.panHandlers}          >              {props.children}          </Animated.View>      );  }  

**** EDIT This is the CartContext component (which holds the data)

import React, { useState, useEffect, useReducer } from 'react'    const CartContext = React.createContext();    function CartProvider(props) {      const [myCartItems, setCartItems] = useState([]);        const addToCart = (product_id) => {          console.log("Added " + product_id + " to cart");          const tempArray = [...myCartItems];          const found = tempArray.some(product => product.id === product_id);          if (!found) tempArray.push({ id: product_id, count: 1 });          else {              for (let i = 0; i < tempArray.length; i++) {                  if (tempArray[i].id == product_id) {                      tempArray[i].count = tempArray[i].count + 1;                      break;                  }              }          }          console.log(myCartItems);          setCartItems(tempArray);      }      const resetCart = () => {          setCartItems([]);      }        useEffect(() => {          console.log("CartProvider re-rendered with values: ");          console.log(myCartItems);      }, [myCartItems])        return (          <CartContext.Provider              value={{                  myCartItems,                  setCartItems,                  resetCart,                  addToCart              }}          >              {props.children}          </CartContext.Provider>      )  }  export { CartProvider, CartContext }  

Using the above component, I can't add the values properly to context. Why is that?

Github: https://github.com/ornakash/shelf Many thanks

Json case parse problem between Flutter and Net Core WebApi

Posted: 01 Jul 2021 09:21 AM PDT

I'm having this issue for a while between flutter and dotnet API communication, as the title says, I'm sending a request from flutter app with camelCase objects to dotnet core 3.1 API, but the object is always null, unless I modify my flutter object to PascalCase, which I don't want to. Its working with web, insomnia and others API calls. Literally everything "non-mobile" works.

Anyone had this issue? this also happened to me with angular PWA project as well. I tried to forcefully make dotnet parse json as camelcase or without a case at all, and nothing. It seems that if I send/receive from a non-mobile source the API doesn't care the case my object is, but if comes from mobile, it wont work unless its pascal case.

it may have nothing to do with casing at all, I'm assuming that's the problem because like I said, if the flutter object is on pascal everything works fine, the object passes through json parsing on the API call and my data is there. But if its not on pascal, object is always null, unless I change my objects inside dotnet to lowercase, again, I don't have to do this on any other web/api project that uses my webapi;

'Class Doctrine\Common\Cache\ArrayCache does not exist' when installing a symfony project

Posted: 01 Jul 2021 09:21 AM PDT

I'm trying to deploy a symfony project following the steps:

./composer.phar update  php bin/console cache:clear  

I've also tried to install manually doctrine driver ArrayCache running:

./composer.phar require doctrine/cache  

The results is always the same and I end up with the following error:

# ./composer.phar update --no-interaction  [...]  Script cache:clear returned with error code 255  !!  !!  In ContainerBuilder.php line 1089:  !!  !!    Class Doctrine\Common\Cache\ArrayCache does not exist  !!  !!  !!  Script @auto-scripts was called via post-update-cmd  

I'm new with symfony and I'm not able to understand why this class is missing.

I'm using the following versions:

"symfony/framework-bundle": "5.1.*",  "doctrine/doctrine-bundle": "^2.2",  

Thanks in advance for your help.

No mapping for static-resources Spring Boot

Posted: 01 Jul 2021 09:20 AM PDT

In my Spring-Boot application, js and css files do not work, it says 404 not found.

My html-page includes the following:

  <head>         <link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet">       <link href="/static/css/style.css" rel="stylesheet">       <script src="/webjars/jquery/jquery.min.js"></script>       <script src="/webjars/sockjs-client/sockjs.min.js"></script>       <script src="/webjars/stomp-websocket/stomp.min.js"></script>       <script src="/static/js/operations.js"></script>   </head>  

I configured resources so:

 @Configuration   @EnableWebMvc   public class MvcConfig implements WebMvcConfigurer {       @Override       public void addResourceHandlers(ResourceHandlerRegistry registry) {           registry                 .addResourceHandler("/resources/**")                 .addResourceLocations("/resources/");          }    }  

But in logs I receive:

  o.s.web.servlet.PageNotFound             : No mapping for GET /favicon.ico    o.s.web.servlet.PageNotFound             : No mapping for GET /favicon.ico    o.s.web.servlet.PageNotFound             : No mapping for GET /webjars/jquery/jquery.min.js    o.s.web.servlet.PageNotFound             : No mapping for GET /static/css/style.css    o.s.web.servlet.PageNotFound             : No mapping for GET /static/js/operations.js    o.s.web.servlet.PageNotFound             : No mapping for GET /favicon.ico  

This is the location of static-sources:

sources

What am I doing wrong?

Im getting error while tring to read .fasta file in python

Posted: 01 Jul 2021 09:20 AM PDT

im trying to read a .fasta file as a dictionary and extract the header and sequence separately.there are several headers and sequences in the file. an example below.

header= CMP12  sequence=agcgtmmnngucnncttsckkld  

but when i try to read a fasta file using the function read_f and test it using print(dict.keys()) i get an empty list.

def read_f(fasta):      '''Read a file from a FASTA format'''        dictionary = {}      with open(fasta) as file:          text = file.readlines()          print(text)        name=''      seq= ''      #Create blocks of fasta text for each sequence, EXCEPT the last one      for line in text:          if line[0]=='>':              dictionary[name] = seq              name=line[1:].strip()              seq=''            else: seq = seq + line.strip()      yield name,seq      fasta= ("sample.prot.fasta")  dict = read_f(fasta)    print(dict.keys())  

this is the error i get:

'generator' object has no attribute 'keys'  

Openshift: oc client inside a container

Posted: 01 Jul 2021 09:20 AM PDT

I need to use oc client inside a container in order to create secrets.

I've took a look over internet in order to look up which image might I use in order to use oc.

Any ideas?

Multiplying what's pointed to by pointers

Posted: 01 Jul 2021 09:20 AM PDT

Pointer1 points to 5.

Pointer2 points to 3.

I want to multiply 5*3, but I only have the pointers. How would I do this in C?

Also, what does uint32_t *pointer mean when:

pointer[2] = {1, 2};

Link to one of many divs with the same class?

Posted: 01 Jul 2021 09:21 AM PDT

Sometimes I want to send a link to e.g. an article in a newspaper and want the receiver to read a specific paragraph, chapter or similar. If the structure of the page is something like

<p class="h2">Some header      <p class="body">Body text  

etc. Is it possible to link to any of these element specifically? For example, I want someone to read the fourth paragraph, that is, the fourth time the class="h2" is used, something like . I know, but I don't recall the syntax ATM, that XPaths offers this functionality, but what about html?

No comments:

Post a Comment