Mount NFS Azure fileshare on docker volume Posted: 13 Oct 2021 09:30 AM PDT I am running my docker on azure vm. I have created Azure NFS file share. Does anybody have idea how can NFS file share be mounted as named volume using docker compose file? |
Illustrator 2021 Character Panel Posted: 13 Oct 2021 09:30 AM PDT Does anyone know what file(s) within the Adobe Illustrator 2021 Program Directory is responsible for the Character Panel and its default settings? Thank you! |
Store details in MLFlow Posted: 13 Oct 2021 09:29 AM PDT Is there any options/mechanism available to store details/description about the model/parameter in each run of the MLFLow? |
How many socket.io requests to server per user is too many? Posted: 13 Oct 2021 09:29 AM PDT I was looking at my logs, and it seems on occasion, I have a great many socket.io get requests from the same user. Is this normal behavior or did I do something wrong? 12:24:29 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwU34x" dyno=web.1 connect=0ms service=1ms status=200 bytes=233 protocol=https 12:24:30 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwU38N" dyno=web.1 connect=0ms service=1ms status=200 bytes=233 protocol=https 12:24:37 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwU4Xd" dyno=web.1 connect=0ms service=2ms status=200 bytes=233 protocol=https 12:24:45 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwU6oG" dyno=web.1 connect=0ms service=1ms status=200 bytes=233 protocol=https 12:24:45 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwU6nE" dyno=web.1 connect=0ms service=1ms status=200 bytes=233 protocol=https 12:24:51 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwU8QL" dyno=web.1 connect=0ms service=1ms status=200 bytes=233 protocol=https 12:24:58 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwUA4O" dyno=web.1 connect=0ms service=2ms status=200 bytes=233 protocol=https 12:25:04 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwUBXz" dyno=web.1 connect=0ms service=1ms status=200 bytes=233 protocol=https 12:25:04 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwUBY-" dyno=web.1 connect=0ms service=1ms status=200 bytes=233 protocol=https 12:25:04 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwUBZq" dyno=web.1 connect=0ms service=7ms status=200 bytes=233 protocol=https 12:25:04 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwUBay" dyno=web.1 connect=0ms service=1ms status=200 bytes=233 protocol=https 12:25:12 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwUDPB" dyno=web.1 connect=0ms service=1ms status=200 bytes=233 protocol=https 12:25:12 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwUDNc" dyno=web.1 connect=0ms service=1ms status=200 bytes=233 protocol=https 12:25:12 method=GET path="/socket.io/?EIO=4&transport=polling&t=NnwUDOU" dyno=web.1 connect=0ms service=1ms status=200 bytes=233 protocol=https Everything seems to be working, but occasionally my server seems to be hammered by these requests. |
k8s network policy blocks DNS Posted: 13 Oct 2021 09:29 AM PDT I am trying to enable DNS for my pods with network policy. I am using https://kubernetes.io/docs/tasks/administer-cluster/dns-debugging-resolution/ I tried with apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: my_name namespace: my_namespace spec: podSelector: matchLabels: {} policyTypes: - Egress egress: - to: - namespaceSelector: matchLabels: name: kube-system ports: - protocol: UDP port: 53 - protocol: TCP port: 53 or egress: - to: - namespaceSelector:{} podSelector: {} ports: - protocol: UDP port: 53 - protocol: TCP port: 53 or egress: - ports: - protocol: UDP port: 53 - protocol: TCP port: 53 None of them works. Only thing I tried which works, is following: egress: - to: - namespaceSelector:{} podSelector: {} But it opens all egress. I tried those combination in my local k8s (minikube with cilium). All of them work as expected, but not in the production environment(AWS k8s 1.20 with calico ). I always have the DNS issue. I run out of ideas, please help~ |
Create view from dynamic JSON column in redshift Posted: 13 Oct 2021 09:29 AM PDT I am wondering if there is a way to create an view from a table that contains a JSON column in redshift AWS. It is important to note that there is no known schema of the JSON, so the view needs to be updated dynamically. Another thing, for every key in JSON a new column will be created (including nested keys) For example, I have this table: id | json_column | 1 | {"1":"a","2":"b"} | 2 | {"2":"c","3":"d","4":{"1":"e","2":"f"} | And I want as result this view: | id | 1 | 2 | 3 | 4 | 4.1 | 4.2 | | -------- | -------------- | -------- | -------------- | -------- | -------------- | -------------- | | 1 | a | b | | | | | | 2 | | c | d | {"1":"e","2":"f"} | e | d Does it possible? |
Flutter logs don't work in Xcode console after upgrading to Flutter 2.5 Posted: 13 Oct 2021 09:30 AM PDT I have updated Flutter to 2.5 and Xcode to 12.5.1. Since then, when I run the app on Xcode, no logs from Flutter code are displayed, only the logs in the native iOS code. This is the default log I use which doesn't work now: print('default print'); I have tried this log: import 'dart:developer'; log('test log'); and it also doesn't work. Any suggestions? |
Check if a text contains at least one string from a list of strings - Dart - Flutter Posted: 13 Oct 2021 09:30 AM PDT I have a list of strings var list = ['my name is', 'people call me', 'i am', 'you can call me']; I'd like to check if a text contains at least one expression from my list of strings before executing an if statement if (text.toLowerCase().contains("my name is") || text.toLowerCase().contains("people call me") || text.toLowerCase().contains("i am")) { //do something } Right now this is what I'm doing but it won't work in the long run as my list will get longer I need to return true if text.contains(anyStringfromMyList) |
How does variable setting work with await? Posted: 13 Oct 2021 09:30 AM PDT Can someone explain to me why this is not working the way I am expecting? I am expecting the last console.log to run after my functions run, but it is returning empty length string instead of the actual date. These are the variables I want to set after my function call. Declaring them now so the scope is set globally. var seasonStart = ''; var seasonID = ''; This function gets my json data. I have URL declared above in my code, its returning everything as expected. async function getCurrentSeasonapi(url) { //store response const response = await fetch(url); //store data in JSON var data = await response.json(); //I tried to set the variables here but it didn't work so I tried using a separate function setSeasonInfo(data); } The function that is called above: //set current season function setSeasonInfo(data) { seasonStart = data.seasons[0].regularSeasonStartDate; seasonID = data.seasons[0].seasonId; //this returns the correct date console.log(seasonStart); } calling the function, so my variables should be set correctly after this function runs getCurrentSeasonapi(getCurrentSeasonURL); //this is returning '' instead of the actual date set in the function console.log(seasonStart); I'm thinking this is a scope issue but I'm not sure why. Here is an example that I was testing the scope out on. This is how I was expecting my code to run: var test = 1; async function changeTest() { test =100; } document.getElementById("first").innerHTML = test + `<br>` + 'Run Function:' + `<br>`; changeTest(); document.getElementById("first").innerHTML += test <html> <body> <p> testing JS execution</p> <div id = 'first'> </div> </body> </html> |
JsPDF Uncaught ReferenceError: jsPDF is not defined" Posted: 13 Oct 2021 09:29 AM PDT I am trying to save a div as a PDF using jsPDF. Here is my fiddle: https://jsfiddle.net/waleedbinahmed/bfj6qktv/11/ and here is a fiddle that someone else has uploaded: https://jsfiddle.net/waleedbinahmed/8s4qvu27/ The second fiddle is working fine. I have tried to mimic the second fiddle i.e. including the same js and Jquery libraries. But on my fiddle, I am getting this error "Uncaught ReferenceError: jsPDF is not defined". I don't know what I am missing on my fiddle that is causing the issue. Please help me out with what needs to be updated with respect to the second fiddle so that I can save a div a PDF. JS library: https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js Here is my code: HTML: <div id="content"> <h3>Hello, this is a H3 tag</h3> <p>A paragraph</p> </div> <div id="editor"></div> <button onclick="javascript:createPdf()" id="cmd">generate PDF</button> Javascript: function createPdf() { var doc = new jsPDF(); source = $('#content')[0]; specialElementHandlers = { '#editor': function(element, renderer) { return true } }; doc.fromHTML( source, 15, 15, { 'width': 170, 'elementHandlers': specialElementHandlers } ); doc.save('sample-file.pdf') } thanks. |
HTML tags are displayed on the website - optiontree wordress Posted: 13 Oct 2021 09:29 AM PDT |
Searching for specific values in a string SQL Posted: 13 Oct 2021 09:30 AM PDT I need to search a string for a specific value that could appear anywhere within it, including at the beginning. It has to be an exact match on its own. select * from LeadTimeNodes where ParentCombination like '%293 %' So I need to find 293 as its own entity within the ParentCombination field. Some examples of strings in the field: '3293 >>> 671' should not find anything as 293 is part of a bigger number 3293 '293' should find it as it is on its own '479 >>> 12930' should not find anything as 293 is part of 12930 '6000 >>> 293' should find it '293 >>> 1600' should find it If I use my sample code above, it incorporates the empty space into the search and works for numbers after, but if I put a space before it '% 293 %' then it won't find the strings that start with 293 Hope this makes sense. |
transform item value in array/slice Posted: 13 Oct 2021 09:29 AM PDT I want to times 2 for every item in an array, what's wrong with my code? func main() { myArray := []string{"1", "2", "3"} var newArray = []string for i, arr := range myArray { newArray = newArray[i] * 2 } fmt.Println(newArray) } |
IntegrityError at /update_dept/1/ NOT NULL constraint failed: main_department.dept_name Posted: 13 Oct 2021 09:29 AM PDT I am creating a simple django models of doctors and department. there is not link between them and when I try to update the department then it is show me this error IntegrityError at /update_dept/1/ NOT NULL constraint failed: main_department.dept_name this error is new for me. I check other similar question also but didn't get much. so pls help me. here is my view.py file from django.shortcuts import render from .forms import Doctorslist,Departmentform from .models import Department, Doctor from django.shortcuts import redirect from django.views.generic import (CreateView, DetailView, UpdateView, ListView, TemplateView, DeleteView) from django.contrib.messages import constants as messages import os # Create your views here. def add_show(request): form = Doctorslist() if request.method == "POST": form = Doctorslist(request.POST, request.FILES) form.save() return redirect('/') else: form = Doctorslist() stud = Doctor.objects.all context = {'form':form, 'stu':stud } return render(request, 'main/index.html', context) def update_data(request, id): prod = Doctor.objects.get(id=id) if request.method == "POST": prod.doc_image = request.FILES['doc_image'] prod.kycdocument = request.FILES['kycdocument'] prod.name = request.POST.get('name') prod.phone_number = request.POST.get('phone_number') prod.email = request.POST.get('email') prod.city = request.POST.get('city') prod.speciality = request.POST.get('email') prod.save() messages.success(request, "Product Updated Successfully") return redirect('/') context = {'prod':prod} return render(request, 'main/update_doc.html', context) def delete_data(request,id): if request.method =='POST': pi = Doctor.objects.get(pk = id) pi.delete() return redirect('/') def add_show_dept(request): form = Departmentform() if request.method == "POST": form = Departmentform(request.POST) form.save() return redirect('/') else: form = Departmentform() dept = Department.objects.all context = {'form':form, 'stu':dept } return render(request, 'main/pages-profile.html', context) def update_dept_data(request, id): prod = Department.objects.get(id=id) if request.method == "POST": prod.dept_name = request.POST.get('dept_name') prod.dept_Email = request.POST.get('dept_Email') prod.save() messages.success(request, "Product Updated Successfully") return redirect('/') context = {'prod':prod} return render(request, 'main/update_dept.html', context) here is model.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField import os # Create your models here. import datetime def get_file_path(request, filename): filename_original = filename nowTime = datetime.datetime.now().strftime('%Y%m%d%H:%M:%S') filename = "%s%s" % (nowTime, filename_original) return os.path.join('uploads/', filename) class Doctor(models.Model): name = models.CharField(max_length=20) phone_number = PhoneNumberField(null=False, blank=False, unique=True) email = models.EmailField(max_length = 100) city = models.CharField(max_length=100) speciality = models.CharField(max_length=50) doc_image = models.ImageField(upload_to = get_file_path) kycdocument = models.ImageField(upload_to = get_file_path, null = True, blank = True) class Department(models.Model): dept_name = models.CharField(max_length=20) dept_Email = models.EmailField(max_length=100) dept_password = models.CharField(max_length=200) here is forms.py file from django import forms from phonenumber_field.modelfields import PhoneNumberField from .models import Doctor,Department class Doctorslist(forms.ModelForm): class Meta: model = Doctor fields = ('name','phone_number','email', 'city', 'speciality', 'doc_image', 'kycdocument') # widgets = { # 'name': forms.TextInput(attrs = {'class': 'form-control'}), # 'email': forms.EmailInput(attrs={'class': 'form-control'}), # 'city': forms.CharField(attrs={'class': 'form-control'}), # 'speciality': forms.CharField(attrs={'class': 'form-control'}), # } class Departmentform(forms.ModelForm): class Meta: model = Department fields = ('dept_name','dept_Email','dept_password') widgets = {'dept_password': forms.PasswordInput()} here is update_dept.html file {% extends 'base.html' %} {% block content %} <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header"> <h2 class="fw-bold">Edit Product</h2> </div> <div class="card-body"> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label for="" class="form-label">Name</label> <input type="text" Required name="name" value="{{ prod.dept_name }}" class="form-control"> </div> <div class="mb-3"> <label for="" class="form-label">Email</label> <input type="text" Required name="price" value="{{ prod.dept_Email }}" class="form-control"> </div> <button type="submit" class="btn btn-warning">Update</button> </form> </div> </div> </div> </div> {% endblock %} |
Hash trait does not work for Rc<RefCell<T>> in enum Posted: 13 Oct 2021 09:30 AM PDT I define a struct MyData and implement PartialEq and Hash traits for it manually. I define a enum which includes Rc<MyData> and Rc<RefCell<MyData>> . I want derive PartialEq and Hash for the enum, but fails: - The
PartialEq and Hash both work for Rc<MyData> ; - The
PartialEq works for Rc<RefCell<MyData>> too; - But the
Hash does not work for Rc<RefCell<MyData>> ! I have 2 questions: Why? Why only the Hash does not work only for Rc<RefCell<MyData>> ? How to fix it? I can not implement Hash for Rc<RefCell<MyData>> . After searching around I find a way: defining a new wrapper struct, like struct RRWrapper<T> (Rc<RefCell<T>>) , and then implement Hash for this RRWrapper . But this will bring much code. Is there an idiomatic way? I think this's a general usage. Thank in advance, Wu PS: In the real code of my program, there is only Rc<RefCell<MyData>> in the enum but no Rc<MyData> . I put Rc<MyData> here just for comparision. PS2: In the real code of my program, there are more than one Rc<RefCell<T>> in the enum. Original source code: use std::rc::Rc; use std::cell::RefCell; use std::hash::{Hash, Hasher}; struct MyData { i: i64, } impl Hash for MyData { fn hash<H: Hasher>(&self, state: &mut H) { self.hash(state); } } impl PartialEq for MyData { fn eq(&self, other: &Self) -> bool { self == other } } #[derive(PartialEq, Hash)] enum MyEnum { INT(i64), STR(String), MYDATA1(Rc<MyData>), // OK both MYDATA2(Rc<RefCell<MyData>>), // OK for PartialEq but not for Hash } fn main() { } Error: 20 | #[derive(PartialEq, Hash)] | ---- in this derive macro expansion ... 25 | MYDATA2(Rc<RefCell<MyData>>), // OK for PartialEq but not for Hash | ^^^^^^^^^^^^^^^^^^^ the trait `Hash` is not implemented for `RefCell<MyData>` | = note: required because of the requirements on the impl of `Hash` for `Rc<RefCell<MyData>>` = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) Source code of struct RRWrapper : #[derive(Debug, PartialEq, Eq)] pub struct RRWrapper<T: Hash+PartialEq+Eq>(Rc<RefCell<T>>); impl<T: Hash+PartialEq+Eq> Deref for RRWrapper<T> { type Target = Rc<RefCell<T>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T: Hash+PartialEq+Eq> Hash for RRWrapper<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.0.borrow().hash(state); } } impl<T: Hash+PartialEq+Eq> Clone for RRWrapper<T> { fn clone(&self) -> Self { RRWrapper(self.0.clone()) } } impl<T: Hash+PartialEq+Eq> RRWrapper<T> { pub fn new(inner: T) -> Self { RRWrapper(Rc::new(RefCell::new(inner))) } } |
Touching and Holding Behavior Issue in Android for React Native Posted: 13 Oct 2021 09:29 AM PDT I am running into a strange glitch in my react-native app where, in one of my components, when the component first loads in Android, the text can be highlighted, but touching and holding does NOT produce the usual Android treatment where a menu of options with the overlay options of "Cut Copy Paste Share" is rendering to the screen. However, if I simply "save" the file that is open in Visual Studio, this will refresh the screen, and then the usual, expected behavior is available - meaning the menu options allowing for "Cut Copy Paste Share" DO render to the screen when a user touches and holds on a part of the text. But if I use the back button to go back to a previous component and then re-load the component, or if I reload the entire app, I'm back to not having that standard Android overlay on this particular component. I have tried trimming the code down, but thus far nothing has helped me figure out what the problem/conflict is. What might be happening based on the behavior I am describing and how can I resolve it? Here is the code for the component in question: render() { return ( <View style={{ ...styles.layout.container, backgroundColor: styles.colors.background, padding: 0, }} > <ScrollView> <View style={styles.forms.sectionContainer}> {Object.entries(this.props.visit.goalNotes || []).map((goal, index) => { const key = parseInt(goal[0]); const item = goal[1]; return ( <View style={{ ...styles.forms.fieldContainer, flexDirection: 'column' }} key={key} > <Text style={{ ...styles.forms.fieldLabel, width: '100%', marginBottom: 5, }} >{item.goal.value}</Text> <TextInput style={styles.forms.textArea} multiline={true} editable={true} maxLength={1500} placeholder="enter progress made toward this goal" ref={`${index}`} returnKeyType={(() => { if(index < this.props.visit.goalNotes.length - 1) return 'next'; return 'done'; })()} blurOnSubmit={true} onSubmitEditing={() => { if(index < this.props.visit.goalNotes.length - 1) this.refs[`${index + 1}`].focus(); }} onChangeText={(value) => { processUpdate(`visitUpdateTextField-${key}`, () => { let visit = clone(this.props.visit); visit.goalNotes[key] = { ...visit.goalNotes[key], note: { value: value, lastUpdate: Date.serverTime() } } if(visit.goalNotes[key].goalGuid && visit.goalNotes[key].goalGuid.value) { visit.goalNotes[key].goalGuid.lastUpdate = Date.serverTime(); } this.props.updateVisit(visit); }); }} defaultValue={item.note.value} /> </View> ); })} </View> </ScrollView> </View> ); } } NOTE: I even tried switching out to use react-native-gesture-handler to handle the <ScrollView> , but I still end up with the exact same strange behavior. Also, to be clear, I have other components where I am not experiencing this issue. In other words, the expected Android overlay behavior is available on touch and hold on other components. But, in terms of the problem component, even after switching out large blocks of code, I have not been able to determine where the problem lies. Any insight as to what the issue is would be most appreciated. |
Cannot get owned object by cloning it Posted: 13 Oct 2021 09:30 AM PDT I have a reference to a vector of structs. I want to create a reference of an enumerated vector with given structs (but not struct references). I do a clone() to obtain the new instances but it doesn't seem to work. Here's a simplified version of my code: struct Item { name: String, } fn get_enumerated(data: &Vec<Item>) -> Vec<(usize, Item)> { data.iter() .enumerate() .map(|(i, item)| (i, item.clone())) .collect() } The error I get is: error[E0277]: a value of type `Vec<(usize, Item)>` cannot be built from an iterator over elements of type `(usize, &Item)` --> src/lib.rs:9:10 | 9 | .collect() | ^^^^^^^ value of type `Vec<(usize, Item)>` cannot be built from `std::iter::Iterator<Item=(usize, &Item)>` | = help: the trait `FromIterator<(usize, &Item)>` is not implemented for `Vec<(usize, Item)>` It doesn't matter how many clones I'll put there, even if I'll duplicate the line with map() multiple times, it's still a reference. Why the clone() doesn't work here? And how do I change the reference to an owned object here? |
Defer gzip.Close() doesn't write the footer Posted: 13 Oct 2021 09:30 AM PDT I am trying to use gzip.NewWriter to stream data in and write compressed data to a CSV file. Everything works except the footer doesn't seem to get written when I use defer gzip.Close() . I get an Unexpected end of data message when I try to open the file with 7-zip. Note: I have seen this question (and answer) but I feel like my problem is a little different, because I am writing to a file and not returning the bytes. As I understand it, OP in that question was returning the bytes before writing the footer. But because I am just writing to a file, I shouldn't be running into the same issue. Here is a snippet of my code. I have removed all error-checking for the sake of brevity. // Worker that reads invoices and compresses them into a single file. func compressWorker(c Config, archived <-chan Invoice, done chan<- int) { now := time.Now().Format("2006-01") path := filepath.Join(c.OutDir, now+".csv.gz") readColumns := false f, _ := os.Create(path) defer closeWriter("csv file", f) cw := gzip.NewWriter(f) cw.Name = now + ".csv" // * This is where I originally had my defer Close call. // defer closeWriter("compression stream", cw) for i := range archived { if !readColumns { b := []byte(i.CsvColumns() + ",DateLastSaved\n") cw.Write(b) readColumns = true } b := []byte(i.ToCsvString() + "," + time.Now().Format("2006-01-02") + "\n") cw.Write(b) } // Ordinarily I'd say we defer this earlier, but that doesn't work for some // reason. closeWriter("compression writer", cw) done <- 1 } // Print an error with a prefix string and exit. func HandleErrorWithPrefix(e error, p string) { if e != nil { log.Fatalf("Error: %v; %v\n", p, e) } } func closeWriter(n string, wc io.WriteCloser) { log.Printf("closing %v\n", n) err := wc.Close() HandleErrorWithPrefix(err, fmt.Sprintf("error closing writer '%v'", n)) } Interestingly, I get this from closeWriter with my original code and deferred closing: 2021/10/13 09:05:42 closing compression writer 2021/10/13 09:05:42 closing csv file However, I get this when I close cw without deferring: 2021/10/13 09:06:01 closing compression stream I get no errors in closeWriter though so I'm not sure why the file wouldn't be closing. Deferred works last-in-first-out right? |
LinkedIn API request with Python returns "Unpermitted fields present in PARAMETER: Data Processing Exception while processing fields" Posted: 13 Oct 2021 09:29 AM PDT I am trying to Retrieve Statistics for Specific UGC Posts using the official documentations My request looks like this: requests.get(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A00000&ugcPosts[0]=urn%3Ali%3AugcPost%3A111111&ugcPosts[1]=urn%3Ali%3AugcPost%3A222222', headers = headers) "00000" is the company ID "111111" and "222222" - are ugcPosts URNs The headers look like this: def headers(access_token): ''' Make the headers to attach to the API call. ''' headers = { 'Authorization': f'Bearer {access_token}', 'cache-control': 'no-cache', 'X-Restli-Protocol-Version': '2.0.0' } I have also passed the scope as one of the parameters, when authorizing: def authorize(api_url,client_id,client_secret,redirect_uri): # Request authentication URL csrf_token = create_CSRF_token() params = { 'response_type': 'code', 'client_id': client_id, 'redirect_uri': redirect_uri, 'state': csrf_token, 'scope': 'r_liteprofile,r_emailaddress,w_member_social,r_organization_social,r_1st_connections_size,r_ads_reporting,rw_organization_admin,r_basicprofile,r_ads,rw_ads,w_organization_social' } response = requests.get(f'{api_url}/authorization',params=params) Unfortunately this particular request doesn't give me the response I was expecting: {'serviceErrorCode': 100, 'message': 'Unpermitted fields present in PARAMETER: Data Processing Exception while processing fields [/ugcPosts[1], /ugcPosts[0]]', 'status': 403} It works ok, when requesting a list of all ugcPosts requests.get('https://api.linkedin.com/v2/ugcPosts?q=authors&authors=List(urn%3Ali%3Aorganization%3A00000)&sortBy=CREATED&count=100', headers = headers) I have no clue what am I don't wrong. Can you please help me with my predicament? The full request code is here import requests import json from liapiauth import auth, headers def organization_info(headers): response = requests.get(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A00000&ugcPosts[0]=urn%3Ali%3AugcPost%3A1111111&ugcPosts[1]=urn%3Ali%3AugcPost%3A2222222', headers = headers) organization_info = response.json() return organization_info if __name__ == '__main__': credentials = 'credentials.json' access_token = auth(credentials) headers = headers(access_token) organization_info = organization_info(headers) with open('lisharelist.json', 'w') as outfile: json.dump(organization_info, outfile) |
Pass a value via Ajax on onchange Posted: 13 Oct 2021 09:30 AM PDT Im trying to understand how to pass a value from a dropdown on a onChange state. Whats the best practice for this? This is what I get so far. Seems t be working, no errors. I cant get my if/else statement to fire though, so unsure how to check what varables is being caught. Not sure if Im on the right track - whats the best practice here? Form: <select id="dropdown_shop_order_language" name="wcml_shop_order_language"> <option value="nl" selected="selected">Niederländisch</option> <option value="en">Englisch</option> <option value="de">Deutsch</option> </select> My script so far: jQuery(document).ready(function () { jQuery('#dropdown_shop_order_language').change(function () { jQuery.ajax( { dataType: 'json', type: "post", url: myAjax.ajaxurl, data: { action: 'my_action', "dropdown_shop_order_language": jQuery('#dropdown_shop_order_language').val() }, success: function(data){ console.log(data); } }); }); }); Function: function my_enque_action( $hook ) { global $post; $postid = $post->ID; if ( $hook == 'post-new.php' || $hook == 'post.php' ) { if( get_post_type( $postid ) === 'shop_order' ) { wp_enqueue_script( 'lang_script', get_template_directory_uri() . '/assets/javascripts/language.js', array( 'jquery' ), '1.0.0', true ); wp_localize_script( 'lang_script', 'myAjax', array( 'ajaxurl' => admin_url('admin-ajax.php') ) ); } } } add_action( 'admin_enqueue_scripts', 'my_enque_action', 10, 1 ); function my_action( ) { $dropdown_shop_order_language = $_POST['dropdown_shop_order_language']; echo $dropdown_shop_order_language; if ( $dropdown_shop_order_language == 'en' ) { } elseif ( my_action() == 'nl' ) { } elseif ( my_action() == 'de' ) { } else { } echo json_encode(['responsekey' => 'responsevalue']); wp_die(); } add_action( 'wp_ajax_my_action', 'my_action' ); add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); |
Redux: cannot test dispatched actions Posted: 13 Oct 2021 09:29 AM PDT I have a CrudActions.js class: export default class CrudActions { constructor(entity, api) { this.setEntity(entity); this.setApi(api); } setEntity(entity) { this.entity = entity.toUpperCase(); } setApi(api) { this.api = api; }; getEntity() { return this.entity; }; getApi() { return this.api; }; fetchItems() { return dispatch => { dispatch( { type: `TRY_FETCH_${this.getEntity()}_ITEMS`, } ); this.getApi() .fetchItems() .then(data => { dispatch({ type: `FETCH_${this.getEntity()}_ITEMS_SUCCEEDED`, data }); }) .catch(error => { dispatch({ type: `FETCH_${this.getEntity()}_ITEMS_FAILED`, error, }); }) } }; } I extend it with a new class (one class for every route) import { instance as api } from "../../api/app/Ping"; import CrudActions from "../base/CrudActions"; export default class PingActions extends CrudActions { constructor() { super("ping", api); } } export const actions = new PingActions(); I want put under test fetchItems and test that right actions are dispatched. So, in a Ping.test.js : import { actions as pingActions } from "../../../../utils/actions/app/PingActions"; import { axiosInstance } from "../../../../utils/api/base/axiosInstance"; import MockAdapter from "axios-mock-adapter"; import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; const middlewares = [thunk]; const mockStore = configureMockStore(middlewares); const entity = 'ping'; const baseUrl = '/ping'; const dataFetchItems = [ { app_version: "9.8.7" } ]; describe('Test PingActions', () => { let mock; let store; beforeEach(() => { store = mockStore({ ping: { items: dataFetchItems } }) }) beforeAll(() => { mock = new MockAdapter(axiosInstance); }); afterEach(() => { mock.reset(); }); it ('Test can get entity name', () => { expect(pingActions.getEntity()).toBe(entity.toUpperCase()); }); it ('Test can fetch items', () => { mock.onGet('http://localhost:8000/api/v1'+baseUrl).reply(200, dataFetchItems); store.dispatch(pingActions.fetchItems()); expect(store.getActions()).toContainEqual({ type: "TRY_FETCH_PING_ITEMS", }); }) }); With these tests I can cover both case: "TRY_FETCH_PING_ITEMS" and "FETCH_PING_ITEMS_SUCCEEDED" . I cannot understand how get FETCH_PING_ITEMS_SUCCEEDED actions in store.getActions(). store.getActions() has only TRY_FETCH_PING_ITEMS inside. Thank you |
i have problem with {useDrawerProgress} Hook in react drawer navigator it is not working? Posted: 13 Oct 2021 09:30 AM PDT I am trying to make Drawer menu screen transitions but the animation don,t work and I think the problem is {useDrawerProgress} Hook but am not sure, This is my custom-Drawer code function StackScreens({ navigation }) { const progress = useDrawerProgress(); const scale = Animated.interpolateNode(progress, { inputRange: [0, 1], outputRange: [1, 0.8], }); const drawerAnimationStyle = { transform: [{ scale }], }; return ( <Animated.View style={{ flex: 1, ...drawerAnimationStyle }}> <ScreenStack.Navigator> <ScreenStack.Screen name="HomeScreen" options={{ headerShown: false, animation: "slide_from_bottom" }} component={HomeScreen} /> <ScreenStack.Screen name="Chapters" component={ChapterScreen} options={{ headerShown: false, animation: "slide_from_right", presentation: "modal", }} /> <ScreenStack.Screen name="Profile" component={ProfileScreen} options={{ headerShown: false, animation: "slide_from_right", presentation: "modal", }} /> <ScreenStack.Screen name="Setting" component={SettingScreen} options={{ headerShown: false, animation: "slide_from_right", presentation: "modal", }} /> </ScreenStack.Navigator> </Animated.View> ); } This my Drawer-Navigator Components am using react-navigation 6 and all the dependencies are the latest versions export const DrawerNavigation = () => { return ( <NavigationContainer> <Drawer.Navigator drawerContent={(props) => { return <DrawerContent {...props} />; }} > <Drawer.Screen name="Home" options={{ headerShown: false, swipeEdgeWidth: 50, drawerType: "slide", overlayColor: "transparent", drawerStyle: { width: "50%", backgroundColor: "transparent", }, sceneContainerStyle: { backgroundColor: "transparent" }, }} > {(props) => <StackScreens {...props} />} </Drawer.Screen> </Drawer.Navigator> </NavigationContainer> ); }; it just doesn't work I tried many ways but nothing works so please any help? |
three.js - can't see through transparent merged geometry Posted: 13 Oct 2021 09:29 AM PDT can somebody help to understand why when merging the geometries of these boxes, I can't see through them correctly from some angles? Blue are normal boxes, Orange are merged geometries. Using MeshLambertMaterial with an opacity of 0.5. Thanks in advance code: https://codesandbox.io/s/three-alpha-issue-bfdhk?file=/src/index.ts screenshot: code fragment: // create boxes and add them to the scene (right, blue) const boxGeo = new BoxGeometry(0.1, 0.1, 0.1); const mat = new MeshLambertMaterial({ transparent: true, opacity: 0.5, color: "#4469BE" }); const boxes = [ [ 0, 0, 0.1], [ 0, 0, -0.1], [ 0, 0.15, 0.1], [ 0, 0.15, -0.1], [0.15, 0, 0.1], [0.15, 0, -0.1], [0.15, 0.15, 0.1], [0.15, 0.15, -0.1] ].map((v) => { const box = new Mesh(boxGeo, mat); box.position.fromArray(v); box.updateMatrix(); return box; }); const group = new Group(); group.position.x = 0.1; group.add(...boxes); scene.add(group); // merge boxes and add them to the scene (left, orange) // issue: you can't see through some merged boxes from some angles const geos = boxes.map((m) => m.geometry.clone().applyMatrix4(m.matrix)); const geo = BufferGeometryUtils.mergeBufferGeometries(geos); const mergeMat = mat.clone(); mergeMat.color = new Color("#fa6900"); const merge = new Mesh(geo, mergeMat); merge.position.x -= 0.25; scene.add(merge); |
Calculate monthwise data in django/python Posted: 13 Oct 2021 09:29 AM PDT I am getting input as start_date and end_date, now I want to fetch data based on months between start_date and end_date. How that can be done in python/django? I am getting date in format as - start_date = '2021-5-5' #YYYY-MM-DD format end_date = '2021-6-5' Required results - result = [ { 'month' : 'may', 'data' : data_for_may # from date 5th of may to 31st of may }, { 'month' : 'june', 'data' : data_for_june # from date 1st of june to 5th of june } ] |
My wordpress page extremly slow loading (first load waiting before transfer data) Posted: 13 Oct 2021 09:30 AM PDT My web site extremely loading slow. Actually my image size and the other attachment's does not bother me. But when first loading, 4 sec later firefox start transferring data (It is occurred in 2-3 days, after routed second domain. I think it is not related but I just wanna add. Is it related hosting/domain issue, or should I check DNS/nameserver settings? PageSpeed Insights Actually I want to get rid of first 4 blank image in the test results. (My hosting's cpanel loads very fast. I think it is not hosting or domain related) |
Javascript variable memory allocation Posted: 13 Oct 2021 09:29 AM PDT At what stage is the memory allocated to variables in Javascript w.r.t declaration and initialisation? console.log(a); // Prints undefined var a; a = 20; For the above snippet, a = undefined even before the code execution starts. Does that imply that memory has been allocated during the creation of the variable environment with no value ( undefined )? If yes, during code execution phase, when the JS engine comes across a = 20 does a new memory block gets allocated to 20 to which a points ? |
How to install firebase extension in not-interactive way Posted: 13 Oct 2021 09:29 AM PDT I am trying to install firebase firestore-bigquery-export extension through firebase CLI . But I can not find how I can install an extension in non-interactive way. I need that because I have multiple environments and CI. The console contains information about , but where I can find parameters name? $ firebase ext:install firestore-bigquery-export -h Usage: firebase ext:install [options] [extensionName] install an official extension if [extensionName] or [extensionName@version] is provided; or run with `-i` to see all available extensions. Options: --params <paramsFile> name of params variables file with .env format. -h, --help output usage information Thank you for your help! |
My programs are blocked by Avast Antivirus Posted: 13 Oct 2021 09:30 AM PDT I'm an amateur programmer, and I'm getting desperate and mad because of a big issue: most of my programs are blocked by Avast Antivirus, while some aren't, and I don't understand why. The more I try to investigate, the less I understand what the problem could be. I'm requesting your help to find a solution so that my programs are no longer blocked, or, as a default, at least some strong clues that would explain why it might be the case. There are already many topics about that on the web. However, most of them give only superficial answers: they just explain how antivirus software works with signatures and detection heuristics, or state that you just have to add the offending application in the white list without asking any other question. While it is certainly correct, it's not acceptable answers in my sense, because I'm still left with my own programs that refuse to work without any concrete idea to start investigating. First of all, the only antivirus software that blocks my programs is Avast 7.x. No other antivirus software see any inconvenient to run my software. Secondly, I haven't installed Avast myself; it is installed on a friend's machine. I have Windows 7, and he has Windows XP. I'm completely sure that the problem is avast only: when it is temporarily disabled, or if the program is added to its white list, everything works nicely as expected. Three different programs are in trouble: - A text editor, with the goal to replace Windows Notepad while keeping simple, efficient and customizable
- A small amateur audio player very simple to use
- The client program of an online game platform, currently having more than 1000 users
The first one is open source, and I can give a link to the executable and the source code if needed. The two others are closed source but free to use, I can give a link to the executable of the current version only. The only obvious common things between these three programs are me as a developer, my Windows 7 machine that compiled them, the compiler family which is MinGW/GCC, and they are all Win32 GUI applications without any framework (no MFC, no WPF, no Qt, wxWidgets or whatever; just pure Win32/C GUI applications). Here are my observations and thoughts so far: - Versions 1.1, 1.2.1 and 1.3 of my text editor are blocked. They are in C, not C++, have been compiled with GCC 3.4.5 in Unicode mode, and are distributed in portable ZIP files (by portable, I simply mean no installer and no installation needed)
- Version 1.4.1 of the same text editor isn't blocked. It has been compiled with GCC 4.7.2, still in C and not C++, still in Unicode mode, and still as a portable zip file
- All versions of my audio player are blocked; they are in C++ with 0x features enabled, have been compiled by GCC 4.7.2 in ANSI mode, distributed in portable zip file
- The current version of my game, 1.7.2, isn't blocked. it is in C, has been compiled with GCC 3.4.5 in ANSI mode, and is distributed as an Inno Setup 5 installer.
- The new version of my game, 2.0.0, which is currently a private beta, is blocked. It is in C++ with 0x features enabled, has been compiled with GCC 4.7.2 in Unicode mode. I share it with my private beta-testing team as zip files within a private Dropbox folder
The problem is caused by Avast 7.x auto-sandbox. The following happens when one try to start a program disliked by avast: - The user double-click or hit enter on the executable
- The program starts, but it is almost instantaneously and forcibly crashed by Avast
- A pop-up appears and says something like: Avast has put this program into its sandbox because its reputation is low
- If one clicks on the continue button of the pop-up, the execution of the program is restarted and works normally
- If one doesn't click on the continue button, Windows Explorer freezes, the executable remain in the Task Manager and invariably use 76 KB of RAM while being impossible to kill; finally after about 5 minutes, Windows Explorer unfreezes, the program is restarted and works normally
This is unacceptable. Newbie users of my program, especially the game, don't know how antivirus software works; don't know how to put it into the white list and why it will unblock it; don't know how to change settings of their antivirus software; if they see the pop-up, won't understand it and will end up being afraid or disappointed because they can't play without knowing why; and if they don't see the pop-up, I can't expect them to wait 5 minutes with a half-freezing computer. each time they want to play. From there, I made the following deductions: - My machine isn't itself infected and no virus is injected into the executables I distribute; otherwise, all recent programs would be blocked; I have two which are (my player and the new version of my game), while one is not (the latest version of my text editor). The 1.7.2 of the game has been compiled in march 2012, while the 1.4.1 of the text editor is from October 2012.
- The newest version of GCC 4.7.2 is not in cause, by the same reasoning; same for ANSI vs Unicode compiling.
- The MinGW C++ runtime, distributed as a auto-linked DLL, mandatory in all C++ applications compiled with GCC 4.7.2, is probably not the cause, because many well-known programs use it; and my text editor is blocked and is in C, and thus don't use it.
- My audio player and my game have the audio library in common; this later is not the cause, because the version 1.7.2 of my game works and the newest private beta not. And of course, that audio library is also used in many other known or less known applications that aren't blocked.
- Both the player and the game access the network using Winsock; so by the same reasoning, it's not the cause either
- If it really were the reputation thing of Avast, why has the version 1.4.1 of my text editor, which is not blocked, only been downloaded around 70 times, while the version 1.3 which is blocked has been downloaded more than 300 times? It looks completely illogical. Are 70 users sufficient to claim something about reputation? Is it more with 300 users? I really don't think so... probably a critical mass of a dozens thousands users is necessary.
Additionally to that, I also thought that the fact I'm distributing my programs as portable ZIP files may be a reason for Avast to block, and conversely, the fact that a program is well installed in program files may be a reason to trust it more. So I made a simple experience: I compiled a new Inno Setup 5 installer for the beta 2.0.0 of my game, as well as one for the version 1.3 of my text editor, and discover that the installers themselves were blocked! I made another experience with my friend, where I tried to find exactly the place where the programs crash, based on using MessageBeep (MessageBox is also blocked!). I didn't noticed anything problematic. The game is blocked when SetDlgItemText is called for the first time in the login dialog box, but if I remove all SetDlgItemText it is blocked further down. In the text editor, it is blocked while populating the menu bar... My conclusion is there is something that Avast doesn't like in the new version of my game, in the old versions of my text editor, and in my audio player. Something that is absent in the newest version of my text editor. What could it be? Do you have any clue? Do you have only an idea on how I could proceed to find what it is so that I can hope to fix it? Is there only a way to analyse such a problem, or is the whole world screwed by Avast? Note that I'm a single person and not a company, all those programs are free to use, I have not pay any IDE to develop them, and I'm not paid by the users when they use them, so I assume that a certificate is probably not affordable at all. Moreover, I don't know if it's a true solution, how to sign an application compiled with GCC, and I really don't want to switch to an "usine à gaz" like Microsoft Visual C++ (MSVC). I would prefer strongly forget that option if there is any other solution, even a very dirty one. |
sharding a database with hierarchical data structure Posted: 13 Oct 2021 09:29 AM PDT I am using MySQL to store my parent-child relation. The data is in one table. I do not have any problem quering; however, the table has grown in size dramatically. I would like to shard or use some techniques to improve the performance of my queries (and joins). How would I do it? |
Function passed as template argument Posted: 13 Oct 2021 09:29 AM PDT I'm looking for the rules involving passing C++ templates functions as arguments. This is supported by C++ as shown by an example here: #include <iostream> void add1(int &v) { v+=1; } void add2(int &v) { v+=2; } template <void (*T)(int &)> void doOperation() { int temp=0; T(temp); std::cout << "Result is " << temp << std::endl; } int main() { doOperation<add1>(); doOperation<add2>(); } Learning about this technique is difficult, however. Googling for "function as a template argument" doesn't lead to much. And the classic C++ Templates The Complete Guide surprisingly also doesn't discuss it (at least not from my search). The questions I have are whether this is valid C++ (or just some widely supported extension). Also, is there a way to allow a functor with the same signature to be used interchangeably with explicit functions during this kind of template invocation? The following does not work in the above program, at least in Visual C++, because the syntax is obviously wrong. It'd be nice to be able to switch out a function for a functor and vice versa, similar to the way you can pass a function pointer or functor to the std::sort algorithm if you want to define a custom comparison operation. struct add3 { void operator() (int &v) {v+=3;} }; ... doOperation<add3>(); Pointers to a web link or two, or a page in the C++ Templates book would be appreciated! |
No comments:
Post a Comment