Posts

Showing posts from May, 2022

DefaultDict in twinBASIC crashes compiler

I'm trying to make a defaultdict in twinBASIC - this is one where if a key does not exist in a dictionary then it is populated by a default value according to some type. This is what I've tried: Private Class DefaultDict(Of T) Implements Scripting.Dictionary Via dict Private dict As Dictionary Private defaultValue As T Public Property Get Item(ByVal key As Variant) As Variant Implements Scripting.Dictionary.Item If Not dict.Exists(key) Then dict(key) = defaultValue End If Return dict(key) End Property End Class Called like: Dim dict As New DefaultDict(Of Long) dict("foo") += 1 'foo key defaults to 0 Debug.Print dict("foo") 'should be 1 However this just crashes the compiler. What's the proper approach here?

How to use enrich with foreach/iterate to modify SOAP request body?

I want to add multiple tags to SOAP request body from JSON input array. It should be added under the ActionProperties tag, so I tried to use the enrich mediator with foreach as follows : <payloadFactory media-type="xml"> <format> <soapenv:Envelope xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Header> <Security xmlns="http://schemas.xmlsoap.org/ws/2002/12/secext"> <hd:UsernameToken xmlns:hd="http://schemas.xmlsoap.org/ws/2002/12/secext"> <hd:Username>$1</hd:Username> <hd:Passwor...

Laravel get attribute with hasMany

I'm making shop online with Laravel. I made Cart with records user_id and product_id with relations hasMany to products. My problem is that I can't get for example product's name or price, I can only get whole array with products and cart data. Can someone tell me how to get it? Maybe there is a problem with a query or just view syntax. My migration: public function up() { Schema::create('carts', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('user_id'); $table->unsignedBigInteger('product_id'); $table->timestamps(); $table->foreign('user_id')->references('id')->on('users'); $table->foreign('product_id')->references('id')->on('products'); }); Here is my controller function: public function index(Request $request) { ...

Filter (Triple) Nested Collection using Linq C#

I need to filter a List of collections > Repos > Workflows and return the result in the same format Hopefully the example is fairly clear please shout if you think it needs more detail. // All classes have a property 'Name' // Filter along the branch for any that match and return only the matching items List<Collection> AllCollections = new List<Collection>(); Collection CollectionA = new Collection(); Collection CollectionB = new Collection(); CollectionA.Repos = new List<Repo>{new Repo{Name = "FirstRepo", Workflows = new List<Workflow>{new Workflow{Name = "CI-CD"}, new Workflow{Name = "Tests"}, new Workflow{Name = "First-Ops"}}}, new Repo{Name = "SecondRepo", Workflows = new List<Workflow>{new Workflow{Name = "CI-CD"}, new Workflow{Name = "Testing"}, new Workflow{Name = "Second-Ops"}}}, new Repo{Name = "ThirdRepo", Workflows...

how to fill missing date with certain time frequency?

Image
I have a dataframe with columns being date time every 30min or sometime every 10 min. There are missing data and dates for few days. I'd like to fill missing data with zero or NaN with same time frequency. How to do it? I found below similar question. But difference of my question is time frequency. I'd like to keep using same 30 minutes rather than using period_range for daily data filling. sometimes, my data has 10 min time frequency. Basically I'd like to fill missing dates with same existing time frequency. pandas fill missing dates in time series I am pasting some data here for your reference. Depth 5/19/2022 18:51 5/19/2022 19:21 5/19/2022 19:51 5/19/2022 20:21 5/19/2022 20:51 5/19/2022 21:21 5/19/2022 21:51 5/25/2022 0:22 5/25/2022 0:52 5/25/2022 1:22 5/25/2022 1:52 5/25/2022 2:22 5/25/2022 2:52 600 200.6 200.6 200.5 200.7 201.2 201 200.7 171.7 171.7 171.4 171 170.7 170.7 601 200.6 200.7 200.6 200.8 201.3 201.1 200.8 171....

Error: Uncaught (in promise): true in jasmine test case for Angular

I'm new to angular unit testing , was trying to fix the already existing unit test case which fails the error that I getting is Error: Uncaught (in promise): true The code for the unit test case is as follows it('ngOnInit', fakeAsync(() => { // fixture.detectChanges(); component.ngOnInit(); tick(); expect(component.dataConfig.industries.length).toEqual(3); expect(component.dataConfig.fonts.length).toEqual(2); })); now within ngOnInit a call is made to the function which is as below checkUserRole=()=>{ const requiredRoles = ['admin','developer']; this.hasAdminRole = this.service.checkRequiredRoles( requiredRoles, false ); } and within the spec.ts file they have created the stub and provided it in the provider as below TestBed.configureTestingModule({ declarations: [ClientConfigComponent], imports: [TestingModule, ngfModule, MatDialogModule, MaterialModul...

powershell cannot change directory if path contains [ whereas dos command can [duplicate]

I don't understand why I cannot in Powershell go into a folder with [] for example cd c:\test\[demo] wheras I have created in Powershell with md [demo] and I can actually cd with dos command. So what can I do if I want to navigate in this folder from Powershell ?

Query sqlalchemy and count distinct results

I want to write a query to count how many items a User has organized by Product.title. This function gives exactly what I want. I feel like there is a way I can use func.count to make this into 1 line. def cart(self): items = {} for product in Product.query.join(Item).filter(Item.user==self): item=Item.query.filter(Item.user==self, Item.product==product) items[product.title] = {'id': product.id,'count': item.count(), 'cost': product.cost} return items This is my desired return. I've tried joining Product and Item, but I just get the distinct Product returns with no ability to count. Any suggestions? Product.title: count Apples: 10 Bananas: 5 Hotdogs: 1 Tables: class Item(db.Model): __tablename__ = 'item' id = db.Column(db.Integer, primary_key=True) product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False) product = db.relationship...

Is there any way to export pandas dataframe into database with existing tables?

Dear Stackoverflow Community, i'm trying to export my dataframe into postgresql database, i used SQLAlchemy but it doesnt give me the opportunity to map the dataframe with the existing tables in the database, for exemple this mt dataframe: ClientNumber ClientName Amout 1000 Albert 5000 2000 John 4000 1200 Cristian 1000 and the database have this table : id_client client_name client_amount 1000 Albert 5000 2000 John 4000 1200 Cristian 1000 The question is how to link my dataframe to postgresql without forcing to change the name columns of the dataframe ? Thanks in advance

svelte can't display image from fastify

i want to fetch image from fastify and display it in svelte, when i visit the server url(http://localhost:3000/image/Darkaron.jpg), it worked, but when i visit it from svelte url(http://localhost:8080/image/Darkaron.jpg), it refuse to show and give me this error. https://i.postimg.cc/HsKwYkpK/image-error.png server code: import fastify from "fastify" import fstatic from "@fastify/static" import cors from "@fastify/cors"; const imagePath = '/storage' type FileResponse = { filename: string } const server = fastify({ logger: true }) server.register(fstatic, { root: imagePath }) server.register(FastifyMultipart) server.register(cors, { origin: "*", methods: ["OPTIONS", "GET", "POST"] }) server.get("/image/:filename", (req, res) => { res.sendFile((req.params as FileResponse).filename) }) const start = async () => { try { await server.listen(3000) } ca...

Click (Meta) Command to run a list of commands

I need to be able to trigger multiple click commands from one command on the CLI Let's say I have a click group @click.group() def cli(): pass @cli.command() def a(): print("A") @cli.command() def b(): print ("B") What functionality should I add to run an ordered list of the commands like the following? $ python -m my_cli_module a,b A B The goal is that there are shared variables which get initialized for each of my commands. The init is expensive and I'd like to run the init exactly once.

i'm trying to make a axiosGET request to my react component, i get the object on the console.log. But when i try to render it i get a "is not defined"

//component const Clientslist = () => { const classes = useStyles() axios.get('/api/clients').then(resp => { const {clients} = resp.data console.log(clients) // i get the data on the terminal }) return( ... { clients.map(client => ( //clients is not defined <Grid key={client._id} item xs={12} sm={6} md={4}> <Card clientName={client.clientName} ... ) } //controller const get = async (req, res) => { await dbConnect() const clients = await ClientsModel.find() res.status(200).json({ success: true, clients}) } I thing my request code is poor, if someone helps me fix the problem and even a code refactor for a better and clean code. It would be great. Thanks.

Is it possible to do USB-debugging on Android when Phone's USB port is already used?

Problem: I'd like to run an app on my Phone from my laptop, via USB, using Android Studio, while my phone is physically connected to another USB device (a remote controller for a drone). In this case, I have: My Laptop (MacBook running Android Studio Bumblebee) My Phone (Samsung Galaxy with Android 11) A controller for a DJI drone (which plugs directly into the Phone) Problem is the phone obviously only has 1 USB port, so can't connect to both the laptop and the controller. Question: Is it possible (with a USB hub or maybe connecting both phone and controller to computer?) to do usb debugging on phone from laptop while phone communicates via USB to controller? Note: I have successfully connected laptop-to-phone with WIFI-debugging before, but the connection can be a bit slow and laggy so it would be nice if it was possible with USB. Additionally I am not able to do this while my phone is working as the internet hotspot for the laptop (so I need to bring in yet another ...

OpenCV - How to create webM with a transparent background?

Image
When I'm using COLOR_RGBA2BGR all works fine, but transparent background of the GIF become black Example gif url: https://i.stack.imgur.com/WYOQB.gif When I'm using COLOR_RGBA2BGRA , then OpenCV will generate an invalid video. How can I write webM with transparent background? Conversion works here https://www.aconvert.com/video/gif-to-webm/ so it's possible somehow import cv2 import imageio as imageio fourcc = cv2.VideoWriter_fourcc(*'vp09') output = cv2.VideoWriter("video.webm", fourcc, 30.0, (512, 500)) frames_ = imageio.mimread("crazy.gif") # frames = [cv2.cvtColor(frame, cv2.COLOR_RGBA2BGRA) for frame in frames_] frames = [cv2.cvtColor(frame, cv2.COLOR_RGBA2BGR) for frame in frames_] for frame in frames: frame = cv2.resize(frame, (512, 500)) output.write(frame) output.release()

Cannot set service data inside subscribe in Angular

Image
I want to set shared service data inside subscribe method my page structure is i have to access data set from one component app.component in home component and header component . this.sharedService.setData({title: this.title, logo: this.logo}); app.component.ts setData(): void { this.http.get(this.baseUrl+'api/content').subscribe(result => { this.title=result['response'].title; this.logo=result['response'].logo; this.sharedService.setData({title: this.title, logo: this.logo}); }); } but in this case service data is set when i access it in any other component getting blank data for title and logo but when i pass static data (Not is subscribe method API call) then it's value is getting passed to other components. Service: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { environment } from '....

is this a result of firestore latency or normal behavior

Image
I have a form I am using to allow users to add comments to my site. The form has an input field, a textarea field, and a button. When the button is clicked it runs my addComment() function which adds the name, comment, and timestamp to my firestore collection as a new doc. It seems like after I click the button to add a comment I have to wait a few seconds before I can post another one. If I try to add a new comment too quickly then request doesn't get sent to my firestore collection, but if I wait a few seconds everything works as expected. I am curious if this is normal behavior? How can I set it up so users can always post comments without having to wait a few seconds? Can someone explain to me what is happening? Thanks Update: I have been doing some debugging, and I have noticed that both of the functions getVisitorCount() and getUserComments() from the first useEffect run every time I type something into the name or comment input boxes. I have attached screenshots to showca...

Changing x axis scale on the fly

I am using the following gnuplot script to plot data from a set of files that are being added to constantly, once every five minutes: set terminal x11 size 1900, 900 # The plot will not jump to the current window on update. set term x11 1 noraise set obj 1 rectangle behind from screen 0,0 to screen 1,1 set obj 1 fillstyle solid 1.0 fillcolor rgbcolor "black" set grid lc rgb "white" set key left top set key textcolor rgb "white" set border lc rgb "white" set xtics textcolor rgb "white" set xtics font "Times,12" set xtics 1 set xlabel "Hours" textcolor rgb "white" set ytics textcolor rgb "white" set ytics font "Times,12" set ytics 5 set ylabel "Hits" textcolor rgb "white" set yrange [0:50] set y2tics font "Times,10" set y2tics 1 # Figures on the right side of the plot as well set y2range [0:50] plot "/tmp/Stats/One" using ($1)...

Azure Container Apps Restarts every 30 seconds

I have an Azure Container App that's based on the hosted BackgroundService model . It's essentially just a long running console app that overrides the BackgroundService.ExecuteAsync method and waits for the stop signal (via the passed cancellation token). When I run locally in Docker, it's perfect - everything runs as expected. When I deploy as an Azure Container App, it deploys and runs - although I manually had to set the scale minimum to 1 to get it to run at all - but it restarts every 30 secs or so which is obviously not ideal. My guess is that the Azure Container Apps docker host is somehow checking my instance for health and isn't satisfied so tries to restart it? Just a guess. What am I missing? using FR911.DataAccess.Repository; using FR911.Infrastructure.Commands; using FR911.Utils; using FR911.Utils.Extensions; using SimpleInjector; IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices(services => { services.AddFR911Log4NetConf...

How to enforce the shape of a JSON/JSONB in Postgres?

I am trying to store the response of questions of a survey in JSON, as they could be in boolean(Is this Bar? Yes/No), number(How much is Foo?), string(Describe what is Foo). It is working fine, but how can I enforce that for a certain question, the JSON will be of identical shape? For example, for the question "How many Foo or Bar do you eat everyday?", I am expecting the following structure(let say it is column answer ): { foo: number, bar: number } How can I enforce that and keep my data consistent?

Need help implementing ZILN custom loss function in lightGBM

Im trying to implement this zero-inflated log normal loss function based on this paper in lightGBM ( https://arxiv.org/pdf/1912.07753.pdf ) (page 5). But, admittedly, I just don’t know how. I don’t understand how to get the gradient and hessian of this function in order to implement it in LGBM and I’ve never needed to implement a custom loss function in the past. The authors of this paper have open sourced their code, and the function is available in tensorflow ( https://github.com/google/lifetime_value/blob/master/lifetime_value/zero_inflated_lognormal.py ), but I’m unable to translate this to fit the parameters required for a custom loss function in LightGBM. An example of how LGBM accepts custom loss functions— loglikelihood loss would be written as: def loglikelihood(preds, train_data): labels = train_data.get_label() preds = 1. / (1. + np.exp(-preds)) grad = preds - labels hess = preds * (1. - preds) return grad, hess Similarly, I would need to define a cust...

Using Yarn v3.1.1 and GitHub Actions CI with node.js.yml?

I use Yarn v3.1.1 package manager and recently setup a Node.js CI pipeline with GitHub Actions. How do I get the CI test to use the dependencies generated by yarn install instead of looking for package-lock.json generated by npm install ? Below is my node.js.yml file. I've tried changing the npm references to yarn and deleting the package-lock.json file, but the runner still looks for the package-lock.json file. My end goal is to use one package manager, preferably Yarn. EDIT: For clarification, my current workflow requires me to run npm install before pushing to origin so that the CI runs correctly and running yarn install before I can serve my repo locally. name: Node.js CI on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest strategy: matrix: node-version: [16.x] # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ steps: - uses: actions/...

Placing 3 pictures under big picture [closed]

Plan was to have 3 pictures direct under the hero picture. I think it is possible, but do not know how to do it...))) Thank you for your help and time!

Why Solana RPC write Transaction failed to sanitize accounts offsets correctly?

I tried to copy my token swap transaction. And I get an error: solana.rpc.core.RPCException: {'code': -32602, 'message': 'invalid transaction: Transaction failed to sanitize accounts offsets correctly'} Successful Transaction - https://solscan.io/tx/5yL5MnDyLmDGu3xeR4gz8y3pJWGg5qXTzxMgd9qUPgYsPQ5ZUPkJt1DVHkmRAoqZUenHtDqgb4vsfkC1P2vjmKW9 Code: from solana.transaction import AccountMeta, Transaction, TransactionInstruction from solana.rpc.types import TxOpts from solana.account import Account from solana.rpc.api import Client from solana.publickey import PublicKey from solana.rpc.commitment import Recent, Root from solana.keypair import Keypair import base58 from spl.token.instructions import transfer, TransferParams url = 'https://api.mainnet-beta.solana.com' client = Client(url) txn = Transaction(recent_blockhash=client.get_recent_blockhash()['result']['value']['blockhash'], fee_payer='8noB4Wv7rpUsz17eRD833G7VHnnmfp1Jd...

Oracle - drill down the records

I have a table with services and each combination of the services have a specific cost amount. I want to filter one service and get to know, what are the services one level to the left and then choose another service from that subpart, etc. Please see an example picture: On the left is the process of the "drill down" and on the right is the desired output. Please ignore the sum of the amounts (they are not correct). example picture CREATE TABLE test_table ( id INTEGER, costcenter VARCHAR2(20), service_level1 VARCHAR2(40), service_level2 VARCHAR2(40), service_level3 VARCHAR2(40), service_level4 VARCHAR2(40), amount INTEGER); INSERT INTO test_table (id,costcenter, service_level1, service_level2, service_level3, service_level4, amount) VALUES ( 1, '10016831', 'U00 COGNOS AL', NULL, NUll, NULL, 50000); INSERT INTO test_table (id,costcenter, service_level1, service_level2, service_level3, service_level4, amount) VALUES ( 2, '...

React Testing Library userEvent.type recognizing only the first letter

I'm using "@testing-library/user-event": "^14.2.0" with Next.js 12. Here is my test it('test search input', async () => { const searchInput = screen.getByPlaceholderText('Search assets'); expect(searchInput).toBeInTheDocument(); await userEvent.type(searchInput, 'test{Enter}'); expect(searchInput).toHaveValue('test'); Test fails with below error expect(element).toHaveValue(test) Expected the element to have value: test Received: t 195 | 196 | await userEvent.type(searchInput, 'test{Enter}'); > 197 | expect(searchInput).toHaveValue('test'); | ^ 198 | }); 199 | }); 200 | UPDATE: Here is my component code. Component is very simple with an input box with onKeyDown event. const SearchBox = () => { const router = useRouter(); const handleKeyDown = (event: React.KeyboardEvent<H...

Spring boot and logstash tcp link dosent work with docker compose "localhost/

It works for me in local but i had an error when using docker : error is : localhost/<unresolved>:5000: connection, how can i set this unresolved value for logstash destination id docker-compose version: '3.2' services: elasticsearch: image: elasticsearch:$ELK_VERSION volumes: - elasticsearch:/usr/share/elasticsearch/data environment: ES_JAVA_OPTS: "-Xmx256m -Xms256m" # Note: currently there doesn't seem to be a way to change the default user for Elasticsearch ELASTIC_PASSWORD: $ELASTIC_PASSWORD # Use single node discovery in order to disable production mode and avoid bootstrap checks # see https://www.elastic.co/guide/en/elasticsearch/reference/current/bootstrap-checks.html discovery.type: single-node # X-Pack security needs to be enabled for Elasticsearch to actually authenticate requests xpack.security.enabled: "true"...

callback is not a function - castv2

I'm following this http://siglerdev.us/blog/2021/02/26/google-home-message-broadcast-system-node-js/31 which uses this library castv2-client to send messages to my google home. It works. I get the messages no problem, but the code throws C:\Users\Phil\Documents\google home\node_modules\castv2-client\lib\controllers\receiver.js:72 callback(null, response.status.volume); ^ TypeError: callback is not a function at C:\Users\Phil\Documents\google home\node_modules\castv2-client\lib\controllers\receiver.js:72:5 ver.js:72 at fn.onmessage (C:\Users\Phil\Documents\google home\node_modules\castv2-client\lib\controllers\request-response.js:27:7) at fn.emit (events.js:203:15) at Channel.onmessage (C:\Users\Phil\Documents\google home\node_modules\castv2-client\lib\controllers\controller.js:16:10) s\receiver.js:72:5 at Channel.emit (events.js:198:13) ...

How to compare two double precision real numbers in Fortran?

I wrote a Fortran subroutine to compute the time of flight(TOF) between two points on elliptical orbit. Obviously this TOF has to be a positive number. I tested my subroutine with different data but in some cases I get negative result despite of I coded a possible way to solve this problem. Here is my subroutine: !************************************************************* subroutine TOF_between_2TA(e,xn,theta1,theta2,delta_t) !************************************************************* ! Compute time of flight bewteen two points (point 1 and point 2) on elliptical orbits. !************************************************************* ! Input: ! xn = mean motion, any units ! e = eccentricity ! theta1 = true anomaly of first point, in interval [0, twopi] ! theta2 = true anomaly of second point, in interval [0, twopi] ! ! Output: ! delta_t = time of flight between two points (same units as given by xn) !**********************************************************...

Using selenium to find text of a specific size

I am trying to develop a web scraper in Python to scan messari.io and I am trying to get each cell under the Type field. Using dev tools and inspect, it seems like the text-size is 0.7em. How would I go about using the text size to get the text? I have tried to do h4, h5, and h6 and none of those return anything. Here is my code: types = WebDriverWait(driver, 10).until( EC.presence_of_all_elements_located((By.TAG_NAME, "h6"))) for type in types: if type.text: print(type.text) And here is the site for reference: https://messari.io/governor/daos

Create % comparison value between two visuals

I am trying to create a new dynamic comparison metric between two table visuals with identical metrics and custom date slicers that create a period A/B view. Both tables and date slicers reference the same dataset (tableA). I want to create a measure that can calculate the % difference for all metrics between periods A and B, either as a new table or a series of scorecards under the period B table. For simplicity, I am only using  Cost  and  Date  from the table to create these different periods for comparison. I am not a DAX expert, so I am running into issues with creating my measure since it relies on the same data set. The closest I got was by duplicating my dataset (tableA (1)) so that I could reference the same metric in my calculation, i.e. %_Change_Cost=(SUM(('tableA'[Cost])/('tableA (1)'[Cost]))-1. But when the date filters do not overlap, the calculation breaks. Period A vs B tables Thank you!

Merge multiple list of string in unique list in java 8

Edit2: : I have main data(list or array,it's no matter) like this: {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20} I want to: 1-replace all values containing 3 with "julie" 2-all values that are val % 15 == 0 should be replaced with "jack" . 3-also replace all values that are val % 5 == 0 should be replaced with "john" , Note: Without If Else Just With Java 8. In the end I should have this data : ("1","2","julie","4","john","6","7","8","9","john","11","12","julie","14","jack","16","17","18","19","john") for this issue I use stream and replaced these values with related string and i created 3 related list for each string: 1-Result for need1(replace all values containing 3 with "julie" ): ("1","2","juli...

FCM Custom Notification Icon in flutter

good morning all, I'm using firebase cloud messaging to send notifications but I'm trying to change its icon and can't do it I'm trying a lot of solutions but no one is working for me such as : 1- <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/ic_notification" /> 2- changing launcher icon 3- modify the launch_background.xml and make the transparent and a lot of solution, could anyone help me, please?

find Mount point from cat /etc/fstab with ansible

i would create a playbook that Check Mount_points for fstype:ext related to the vars: whitelist so it will iterate through the vars to check if mount_point exists or not if it exists an output should be similar to this, else it will be ignored / /boot /home /opt /var /var/opt /var/tmp /var/log /var/log/audit here is my playbook which was using 'xfs' as i don't have ext in my machine. Could you advise about more efficient way to achieve the desired result - hosts: all vars: whitelist: - '/' - '/boot' - '/home' - '/opt' - '/var' - '/bin' - '/usr' tasks: - set_fact: mount_point: "Liquid error: wrong number of arguments (given 1, expected 2)" - debug: var: mount_point loop: "" when: item in mount_point TASK [set_fact] ********************************************************...

How to use own out variable instead of gl_FragColor? [solved]

I want to write a simple shader (I am using Three.js with WebGL as shader language) that colors a cube. here is an image of this cube It's working as long as I use gl_FragColor in my FragmentShader, but apparently gl_FragColor should not be used anymore as it is deprecated, so I created my own out variable: in vec3 pos; out vec4 outColor; void main() { float r = pos.x; float g = pos.y; float b = pos.z; outColor = vec4(r,g,b,1.0); } However, this results in the following error message: ERROR: 0:44: 'outColor' : must explicitly specify all locations when using multiple fragment outputs I looked for possible answers and don't really understand this approach: layout(location = 0) out vec4 outColor; This gives me the error message ERROR: 0:44: 'outColor' : conflicting output locations with previously defined output 'pc_fragColor' but I never declared pc_fragColor. When I use other numbers than 0 (e.g. layout(location = 1)) then the ...

vue-advanced-cropper image croped sized is bigger than the original

I'm implementing a system where user choose image, he must crop it before save; i'm using vue-advance-cropper plugin; all system is setted up but the result image sized is bigger than the original; example: i insert image at 307ko i got 448ko; i insert image at 40ko i got 206ko; is there any option that i missed to make the result lesser size than the original or is there not anything can be done?

How to get the return value of a task coming from an event loop?

The purpose of this implementation is to be able to call async functions without the "await" keyword I have a code that is mixing some sync and async functions, I am calling an async function (B) from a sync function (A) inside an event loop and I am unable to get the return value of the async function. An example as follows: import asyncio import time async def B(x): print(f'before_delay {x}') await asyncio.sleep(1.0) print(f'after_delay {x}') return x*x def A(x): task = asyncio.create_task(B(x)) print(task) asyncio.get_event_loop().run_until_complete(task) //did not work return 0 async def loop_func(): res = A(9) print(f'after calling function {res}') async def main(): while True: await loop_func() await asyncio.sleep(3.0) asyncio.run(main()) The error I am getting is quite understandable; RuntimeError: Cannot run the event loop while another loop is running The problem is that o...

How to permanently fix chmod changes to an app deployed on Heroku? [duplicate]

I just made a post yesterday - How to solve "500 internal server error" on a deployed python app on Heroku? And today I actually have discovered the problem. The program isn't missing, but instead program's access on Heroku has been denied. So, I just did a SSH to Heroku and chmod the exiftool and now it works fine. But then comes an another problem. This chmod change is only temporary. After a few minutes, the error comes again and I have to do the chmod thing again to make it work. Is there any way to permanently fix this?

What is predict value of GBM model in R? and why NaN residual?

Well, I have a GBM model for nematode density with some predictor variables (SI = Spectral Index). However, my model showed "NaN" residual with poisson distribution, and when I used predicted(gbm.fit) or gbm.fit$fit showed continuous values, but I have discrete values. What should I use, predicted(gbm.fit) or gbm.fit$fit? What does gbm.fit$fit give me? Can anyone help me with a problem? This is the gbm algorithm used: gbm.fit <- gbm( formula = juv ~ NDRE + WI + GRAY + RSVI + VDVI, distribution = "poisson", data = data_base, n.trees = 5000, interaction.depth = 15, bag.fraction = 3, shrinkage = 0.01, cv.folds = 5, n.cores = NULL, # will use all cores by default verbose = FALSE ) Then I do: sqrt(min(gbm.fit$fit)) Which produces this error: Warning in sqrt(min(gbm.fit$cv.error)) : NaNs produced [1] NaN measure = read_xlsx("quantification.xlsx")

KStream disable local state strore

I am using Kafka Stream with Spring cloud Stream. Our application is stateful as it does some aggregation. When I run the app, I see the below ERROR message on the console. I am running this app in a Remote Desktop Windows machine. Failed to change permissions for the directory C:\Users\andy\project\tmp Failed to change permissions for the directory C:\Users\andy\project\tmp\my-local-local But when the same code is deployed in a Linux box, I don't see the error. So I assume it an access issue. As per our company policy, we do not have access to the change a folder's permission and hence chmod 777 did not work as well. My question is, is there a way to disable creating the state store locally and instead use the Kafka change log topic to maintain the state. I understand this is not ideal, but it only for my local development. TIA.

Togglz with Kotlin: Problem to inject some dependency in my custom ActivationStrategy

I have defined the file that references my custom ActivationStrategy in META-INF/Services/ as explained by the Togglz library for custom strategy ( https://www.togglz.org/documentation/activation-strategies.html ), since I need to resolve whether or not it is activated through another logic that is in another Service. Now how do I inject this service that I need to consume? Since when trying the following: @Component class ActivationStrategyByProfile(private val profileService : ProfileService) : ActivationStrategy { override fun getId(): String { return ID } override fun getName(): String { return NAME } override fun isActive( featureState: FeatureState, user: FeatureUser? ): Boolean { val profileId = user?.name return profileService.validateProfile(profileId) } ... My file in /META-INF/services/org.togglz.core.spi.ActivationStrategy contain: com.saraza.application.config.ActivationStrategy...

Can {0} initialize a stucture (local) variable several times correctly

I've noticed that inside a library of STM32, there is a piece of the code which initialize a stucture variable with {0}. Below is a simplified example: typedef struct { uint16_t val_a; uint16_t val_b; uint16_t val_c; } dataset_t; dataset_t Dataset = {0}; The goal of this code is to initialize all the elements of the variable Dataset to 0. Is this a correct way to initialize this variable ? Is it possible that this method initialize only the first element (val_a) to 0, but not all the elements if we initialize this many times ?

Machine Learning Question on missing values in training and test data

I'm training a text classifier for binary classification. In my training data, there are null values in the .csv file in the text portion, and there are also null values in my test file. I have converted both files to a dataframe (Pandas). This is a small percentage of the overall data (less than 0.01). Knowing this - is it better to replace the null text fields with an empty string or leave it as as empty? And if the answer is replace with empty string, is it "acceptable" to do the same for the test csv file before running it against the model?

Why doesn't my sslstream get the certificate from a mail server?

From my code below, I should be getting the certificate of the mail server "mailgw.th-nuernberg.de" . That didn't work and I get the error "the handshake failed due to an unexpected packet format" by calling the method "AuthenticateAsClient". I tried the same code with the mail server "smtp.gmail.com" on port 993 . That works and I get the full certificate. The mail server "mailgw.th-nuernberg.de" exists but I don't know why Google's mail server is working and it isn't. Here is my Code: X509Certificate2 cert = null; var client = new TcpClient("mailgw.th-nuernberg.de", 25); var certValidation = new RemoteCertificateValidationCallback(delegate (object snd, X509Certificate certificate, X509Chain chainLocal, SslPolicyErrors sslPolicyErrors) { return true; //Accept every certificate, even if it's invalid }); // Create an SSL stream and takeover client's stream using (var sslStream = ne...

How can I restrict a time input value?

I want to display an input type hour from 08:00 to 20:00. I tried this: <input type="time" id="timeAppointment" name = "timeAppointment" min="08:00" max="20:00" placeholder="hour" required/> But when I display it I can still select any time, it does not restrict me as I indicate. What is the problem? If is necessary some code I work with Javascript.

Why does this code execute more slowly after strength-reducing multiplications to loop-carried additions?

Image
I am reading Agner Fog's optimization manuals, and I came across this example: double data[LEN]; void compute() { const double A = 1.1, B = 2.2, C = 3.3; int i; for(i=0; i<LEN; i++) { data[i] = A*i*i + B*i + C; } } Agner indicates that there's a way to optimize this code - by realizing that the loop can avoid using costly multiplications, and instead use the "deltas" that are applied per iteration. I use a piece of paper to confirm the theory, first... ...and of course, he is right - in each loop iteration we can compute the new result based on the old one, by adding a "delta". This delta starts at value "A+B", and is then incremented by "2*A" on each step. So we update the code to look like this: void compute() { const double A = 1.1, B = 2.2, C = 3.3; const double A2 = A+A; double Z = A+B; double Y = C; int i; for(i=0; i<LEN; i++) { data[i] = Y; Y += Z; ...

Python world analog of Rails encrypted credentials feature (to store secrets securely)

Are the Python analogs of encrypted credentials Rails feature ? Quote from Rails Guides on subject : Rails stores secrets in config/credentials.yml.enc , which is encrypted and hence cannot be edited directly. Rails uses config/master.key or alternatively looks for the environment variable ENV["RAILS_MASTER_KEY"] to encrypt the credentials file. Because the credentials file is encrypted, it can be stored in version control , as long as the master key is kept safe. To edit the credentials file, run bin/rails credentials:edit . This command will create the credentials file if it does not exist. Additionally, this command will create config/master.key if no master key is defined. Secrets kept in the credentials file are accessible via Rails.application.credentials . My idea is: to have all the secrets encrypted in repository; to have locally only master.key (or only one env variable); to once pass manually to production server master.key ; then pass other secre...

Get value from joined tables, Codeigniter

I'm trying to get and display the data from joined tables but I can't get anything in return. I reference this and it worked on my other function, but when I tried it again on a different function, I can't get any results. Here's the Model: public function viewReview($id) { $this->db->select('clients.firstname, clients.lastname, packages.title, rate_review.review, rate_review.date_created'); $this->db->where('rate_review.id', $id); $this->db->join('clients', 'clients.id = rate_review.user_id'); $this->db->join('packages', 'rate_review.package_id = packages.id'); $this->db->from('rate_review'); $query = $this->db->get(); return $query->row_array(); } Controller: public function view_review($id) { $data['title'] = 'Rate & Reviews'; $data['review'] = $this->Admin_model->viewReview($id); $this->loa...