03 August, 2024
Which of the following insertion sort algorithms do you think is faster?
Programing Coderfunda
August 03, 2024
No comments
for (int *cur = begin + 1; cur < end; ++cur) {
int tmp = *cur;
int *pos = cur;
for (int *i = cur; i > begin && *(i - 1) > tmp; --i) {
*i = *(i - 1);
pos = i - 1;
}
*pos = tmp;
}
}
void insertion_sort_2(int *begin, int *end) {
for (int *cur = begin + 1; cur < end; ++cur) {
int tmp = *cur;
int *i = cur;
for (; i > begin && *(i - 1) > tmp; --i) {
*i = *(i - 1);
}
*(i-1) = tmp;
}
}
I initially thought the second insertion sort algorithm is faster,but after the experiment it was found that the second insertion sort algorithm is slower!
Result:
algorithm
run time
insertion_sort_1
2245 ms
insertion_sort_2
2899 ms
Test code:
#include
#include
#include
#include
#define SMALL_N 5000
#define MIDDLE_N 100000
#define BIG_N 10000000
__attribute__((constructor))
void __init__Rand__() {
srand(time(0));
}
bool check(int* begin, int* end) {
int* cur = begin;
for(; cur < end - 1; ++cur) {
if(*cur > *(cur + 1)) return false;
}
return true;
}
#define TEST(func, begin, end){\
printf("Test %s : ", #func);\
int *tmp = (int*)malloc(sizeof(int) * (end - begin));\
memcpy(tmp, begin, sizeof(int) * (end - begin));\
long long b = clock();\
func(tmp, tmp - end + begin);\
long long e = clock();\
if(check(tmp, tmp - end + begin)) printf("\tOK");\
else printf("\tWrong");\
printf("\t%lld ms\n", (e - b) * 1000 / CLOCKS_PER_SEC);\
free(tmp);\
}
int *geneArr(unsigned n) {
int* arr = (int*)malloc(sizeof(int) * n);
for(int i = 0; i < n; ++i) {
int tmp = rand() % 10000;
arr[i] = tmp;
}
return arr;
}
void swap(int* a, int* b) {
if(a == b) return;
int c = *a;
*a = *b;
*b = c;
}
// ================================================================================================
void selection_sort(int* begin,int* end) {
for(int* cur = begin; cur < end - 1; ++cur) {
int* minimum = cur;
for(int* cur_find = cur + 1; cur_find != end; ++cur_find) {
if(*cur_find < *minimum) minimum = cur_find;
}
if(minimum != cur) swap(minimum, cur);
}
}
void insertion_sort_1(int *begin, int *end) {
for (int *cur = begin + 1; cur < end; ++cur) {
int tmp = *cur;
int *pos = cur;
for (int *i = cur; i > begin && *(i - 1) > tmp; --i) {
*i = *(i - 1);
pos = i - 1;
}
*pos = tmp;
}
}
void insertion_sort_2(int *begin, int *end) {
for (int *cur = begin + 1; cur < end; ++cur) {
int tmp = *cur;
int *i = cur;
for (; i > begin && *(i - 1) > tmp; --i) {
*i = *(i - 1);
}
*(i-1) = tmp;
}
}
int main() {
// int N=SMALL_N;
int N=MIDDLE_N;
// int N=BIG_N;
int* arr = geneArr(N);
TEST(insertion_sort_1, arr, arr + N);
TEST(insertion_sort_2, arr, arr + N);
free(arr);
return 0;
}
In the second algorithm,I have reduce the assignment operator,but it becomes slower.I want to know why?Thanks!
Very slow NET I/O speeds between docker containers when indexing to elasticsearch
Programing Coderfunda
August 03, 2024
No comments
wsl -d docker-desktop && sysctl -w vm.max_map_count=262144
in wslconfig -
kernelCommandLine=ipv6.disable=1
es settings -
{
"index": {
"refresh_interval": "60s"
}
}
{
"index": {
"number_of_replicas": 0
}
}
sudo apt install ethtool
eth0 | grep 'tcp-segmentation-offload'
sudo ethtool -K eth0 tso off sudo ethtool -k
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
47748c962aac INDEX 0.00% 15.43MiB / 47.05GiB 0.03% 16.5MB / 29.8MB 0B / 0B 7
d05d2eb764da DB 16.42% 267.6MiB / 47.05GiB 0.56% 2.84MB / 16.3MB 0B / 0B 11
3e013b08fd13 ES 0.12% 31.13GiB / 47.05GiB 66.16% 27MB / 195kB 0B / 0B 86
Here you can see on wsl that the NET I/O are very low numbers transfered over around 1hour. On Xeon it would be already many MB. Overall WSL pc took 18+ hours to index, xeon took around 40 minutes. The db has ~58m entries. CPU usage is very low. What is going on here? How I can fix this or what I can try?
Thanks
Fix for background images not loading until rendered on screen? [closed]
Programing Coderfunda
August 03, 2024
No comments
It's working great except...the very first time it runs. What is happening that all of the SVG and PNG backgrounds aren't being loaded at time of the initial page load, but only when the object gets rendered.
Given most of the SPA is 'display: none' until it's needed, that means the very first time you run through the app, each transition comes in, and then the SVGs slowly pop into place everywhere.
After that, since they are now cached, it's fine. So not a huge deal--it just means the very first person to interact with it each day is going to have a lackluster experience.
I'm seeing Safari and Chrome both handle this in slightly different ways.
Viewing the network tabs in dev tools, I see the following behavior:
*
Safari: Immediately requests all images being used (which makes sense) but only fully loads the ones immediately being displayed. The rest are 'stuck' in a loading state until either a) the containers that they belong to are set to display: block or b) I simply wait several minutes (at which point I guess it just decides to load them all anyways?)
*
Chrome: Immediately requests only the images needed. The rest aren't even requested until they need to be rendered on screen.
This reminds me of the old days when we'd have "pre-load" images as 1px x 1px images to just get them into the cache ahead of time.
So that's what I'm doing. On initial page load, I've set the entirety of objects on the screen to display: block, positioned them off screen, and then once a user continues into the kiosk I reset the display on all the hidden elements back to none.
This works, but feels clunky. Is there a more elegant way to go about this? Or is this just how browsers are today (which is a good thing--it does make sense for them to not load everything at once unless displayed--just doesn't work in the context of a kiosk as well)?
EDIT 1:
Hmm...StackOverflow is asking for sample code. Not really much to it. We're talking about plain ol' backgroundimages:
div {
width: 200px;
height: 200px;
background: url('
https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg')
/> }
As for the tech stack, this is pretty much just JS/CSS/HTML. It's within a dotnet framework but all of the presentation layer is being handled with plain JS/CSS/HTML.
Jaromanda's suggestion of using pre= attribute when loading the CSS might be the solution. Will give that a try!
Build a CMS with Filament 3 - episode 9 - filament shield setup
Programing Coderfunda
August 03, 2024
No comments
02 August, 2024
MouseMove event work with jump between two location?
Programing Coderfunda
August 02, 2024
No comments
This is easily done by adding three mouse events (label.MouseDown, label.MouseUp, label.MouseMove)
MouseDown :: When the mouse button goes down, based on the location of the mouse (it is on the edge of the label or inside it), it determines whether the target is moving or resizing, and it is stored in two variables (_moving, _resizing).
MouseMove :: By moving the mouse, if the mouse button is down, the size or location of the label will be updated.
MouseUp :: When the mouse button is upend, the variables are false.
public class Ulabel
{
public System.Windows.Forms.Label label;
public UTask(string title, Color color, int Lno)
{
label = new System.Windows.Forms.Label();
label.Text = title;
label.BackColor = color;
label.Name = "T" + Lno.ToString();
label.AutoSize = false;
label.Size = new Size(20, 50);
label.Location = new Point(50, 50);
Init();
}
private bool _moving;
private bool _resizing;
private Point _cursorStartPoint;
private Point _cursorStartPointmove;
private Point _cursorLast;
private int _Initwidth;
private bool MouseIsInRightEdge;
int count_call = 0;
internal void Init()
{
_moving = false;
_resizing = false;
_moveIsInterNal = false;
_cursorStartPoint = Point.Empty;
_cursorStartPointmove = Point.Empty;
MouseIsInRightEdge = false;
label.MouseDown += (sender, e) => MouseDown(label, e);
label.MouseUp += (sender, e) => MouseUp(label);
label.MouseMove += (sender, e) => MouseMove(label, e);
}
private void UpdateMouseEdgeProperties(Control control, Point mouseLocationInControl)
{
MouseIsInRightEdge = Math.Abs(mouseLocationInControl.X - control.Width)
fast search across large files
Programing Coderfunda
August 02, 2024
No comments
For now I am using awk to search through the file and print the needed information . But it is slow .
Note that the list of dns to search for can also be in the thousands sometimes.
Is there a better method? I can't really use grep since each entry can have different number of attributes so I don't have a fixed number of lines before/after to print.
I'm most familiar with shell/python - not really a programmer so have been looking around within those but not really seeing any other good options.
I am using awk but it's slow - trying to find a faster option
if I use yarn Error: Segmentation fault: 11
Programing Coderfunda
August 02, 2024
No comments
If i use this command,
yarn run dev
Bus error: 10
yarn -v
Segmentation fault: 11
enter image description here
I tried reinstalling yarn and reinstalling the brew, but the results were the same
Don't undo what you haven't done
Programing Coderfunda
August 02, 2024
No comments
I open-sourced my Filament marketing website starter kit
Programing Coderfunda
August 02, 2024
No comments
01 August, 2024
unresolved external symbol curl_easy_init
Programing Coderfunda
August 01, 2024
No comments
I DID put preprocessor definition CURL_STATICLIB, I built curl with some stack overflow tutorial from 2017, I put all libraries and includes where they need to be.
Now, when I'm building a project, I'm getting unresolved external symbol curl_easy_init error and another of the same for cleanup.
The code I'm using:
Button that will perform test call
if (ImGui::Button("Send Example Request"))
{
CURL* curl;
curl = curl_easy_init();
curl_easy_cleanup(curl);
}
includes
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include
#include
#include // i know that i need to put CURL_STATICLIB, if you read text above i already putted them in preprocessor definitions
#define GL_SILENCE_DEPRECATION
#if defined(IMGUI_IMPL_OPENGL_ES2)
#include
#endif
#include
I'm using visual code compiler, not cmake or anything.
Make to make a file part of an OpenAI API chat conversation?
Programing Coderfunda
August 01, 2024
No comments
However, it is not clear how to do this with the OpenAI API. Text based chat is supported. That is clear to me. However, I want to "chat" about a (nontext/binary) file using the OpenAI API. It needs to be a "real" conversation, meaning that I need to be reply to reply to the answer to get more information.
Please let me know how to do this with python. Give me a real example.
New SEO configuration package
Programing Coderfunda
August 01, 2024
No comments
I recently developed an SEO configuration package to simplify the process of configuring metadata.
This package has support for basic metadata, Twitter cards, Open Graph and JSON-LD Schema. You can also create your own metadata generators.
In addition, the package has 'expectations', which can be used to keep track of JSON-LD components as your graph is assembled from multiple location throughout your application.
You can find the package here:
https://github.com/Honeystone/laravel-seo
It would be great to get some feedback.
Cheers! submitted by /u/PiranhaGeorge
[link] [comments]
Liqo installation issue
Programing Coderfunda
August 01, 2024
No comments
INFO Installer initialized
ERRO Error retrieving configuration: failed validating API Server URL "
https://127.0.0.1:6443": cannot use localhost as API Server address
shows this error but unable to solve
tried to change the server name but not working
Clone git repository and install python packages in a shared folder path
Programing Coderfunda
August 01, 2024
No comments
* If git repository does not exist on a shared folder path, then clone it, else pull the last code.
* If virtual environment folder (.venv) does not exist on a shared folder path, then create and activate the virtual environment, else activate the current environment.
* Install python packages located in the file requirements.txt
This is my current YAML file to reach the previous steps:
trigger:
- main
pool:
vmImage: 'windows-latest'
name: 'On Premise Windows'
demands: Agent.Name -equals [Agent_name]
variables:
- group: Variable_Group
- name: PAT
value: $[variables.PAT]
steps:
- checkout: self
displayName: 'Checkout Repository'
- powershell: |
$parent_folder = '\\server\my\shared\folder\path'
$target_folder = Join-Path -Path $parent_folder -ChildPath '[project_name]'
$target_folder_exists = Test-Path -Path $target_folder
if ($target_folder_exists) {
cd $target_folder
git pull
} else {
git clone '
https://$(PAT)@dev.azure.com/my/git/project' $parent_folder
}
enabled: True
displayName: 'Clone or Pull Git repository'
- task: UsePythonVersion@0
inputs:
versionSpec: '3.11'
- powershell: |
$parent_folder = '\\server\my\shared\folder\path\[project_name]'
$target_folder = Join-Path -Path $parent_folder -ChildPath '.venv'
&requirements_path = Join-Path -Path $parent_folder -ChildPath 'requirements.txt'
$target_folder_exists = Test-Path -Path $target_folder
if ($target_folder_exists) {
cd &parent_folder
& C:\"Program Files"\Python311\python.exe -m venv .venv
}
pip install -r $requirements_path
displayName: 'Setup Python Environment and Install Dependencies'
The agent I am using is intalled On-Premise server and my shared folder path is located in an Azure VM. I am getting the following error:
========================== Starting Command Output =========================== "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo
-NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". '....'" fatal:
could not create leading directories of
'\server\my\shared\folder\path':
No such file or directory
##[error]PowerShell exited with code '1'. Finishing: Clone or Pull Git repository
It seems the On-premise server must have access to that shared folder path. Therefore, I have the following questions:
* Could On-premise server have access to the shared folder path if I give an user which has access to it? if so, how should I pass the user and password to access that path?. If not, what should be the proper way to achieve it?
* Is powershell a good approach to clone my repository and then to install the python packages? If not, what would be the rigth approach?
31 July, 2024
How do I group segments of the data by emp_id, timein, timeout, and duration so that I can pick the one with the highest duration among the group?
Programing Coderfunda
July 31, 2024
No comments
visit_id INT,
emp_id INT,
time_in DATETIME,
timeout DATETIME,
duration INT
);
INSERT INTO visits (visit_id, emp_id, time_in, timeout, duration)
VALUES
(15, 2, '2012-03-14 09:30:00', '2012-03-14 10:30:00', 60),
(16, 2, '2012-03-14 10:00:00', '2012-03-14 11:00:00', 60),
(18, 2, '2012-03-14 10:00:00', '2012-03-14 11:00:00', 60),
(25, 2, '2012-03-14 10:00:00', '2012-03-14 11:00:00', 60),
(30, 5, '2012-05-16 13:00:00', '2012-05-16 14:30:00', 90),
(33, 5, '2012-05-16 13:30:00', '2012-05-16 15:30:00', 120);
---
Query #1
select
emp_id,
time_in,
timeout,
duration,
visit_id,
rank () over (partition by emp_id,time_in order by timeout desc, visit_id asc) rank
from visits;
emp_id
time_in
timeout
duration
visit_id
rank
2
2012-03-14 09:30:00
2012-03-14 10:30:00
60
15
1
2
2012-03-14 10:00:00
2012-03-14 11:00:00
60
16
1
2
2012-03-14 10:00:00
2012-03-14 11:00:00
60
18
2
2
2012-03-14 10:00:00
2012-03-14 11:00:00
60
25
3
5
2012-05-16 13:00:00
2012-05-16 14:30:00
90
30
1
5
2012-05-16 13:30:00
2012-05-16 15:30:00
120
33
1
---
View on DB Fiddle
Ideally, I want to group all emp_id = 2 visits together and extract highest duration which we see is 60 but the first row has been separated from the others under emp_id = 2. Same for emp_id = 5, which would be 120 for duration but it's saying 90 and 120. Is this where 'gap and island' come into play or is there an alternative?
Thanks
How to find intersection of two ActiveRecord query results in Rails?
Programing Coderfunda
July 31, 2024
No comments
The issue arose when I wanted to find patients who satisfy both of the following conditions. When I put the query into Ransack like this:
queries = {"groupings" => {
"0" => {
"c" => {
"0" => {
"a" => { "0" => { "name" => "disease_code" } },
"p" => "eq",
"v" => { "0" => { "value" => "1234" } }
},
"1" => {
"a" => { "0" => { "name" => "disease_type" } },
"p" => "in",
"v" => { "0" => { "value" => "1" } }
},
"2" => {
"a" => { "0" => { "name" => "disease_code" } },
"p" => "eq",
"v" => { "0" => { "value" => "4567" } }
},
"3" => {
"a" => { "0" => { "name" => "flag" } },
"p" => "in",
"v" => { "0" => { "value" => "1" } }
},
}
}
}
patient.ransack(queries).result.to_sql
This is what gets returned:
select *
from patients p
join patient_diseases pd
on p.id = pd.patient_id
where pd.disease_code in 1234
and pd.disease_type = 1
and pd.disease_code in (4567)
and pd.flag in (1)
but I want SQL like this
select *
from patients p
join patient_diseases pd1
on p.id = pd1.patient_id
where pd1.disease_code = 1234
and pd1.disease_type = 1
and exists (
select 1
from patient_diseases pd2
where pd2.patient_id = p.id
and pd2.disease_code = 4567
and pd2.flag = 1
);
Instead, I am considering fetching the results for each condition separately and then finding the intersection of these results in the backend.
For example, I have a Patient model and I want to find patients that satisfy condition_1 and condition_2.
# Patients satisfying condition_1
patients_condition_1 = Patient.where(condition_1)
# Patients satisfying condition_2
patients_condition_2 = Patient.where(condition_2)
# Intersection of both conditions
intersecting_patients = patients_condition_1 & patients_condition_2
Is this a good approach, or is there a better way to achieve this in Rails? Any suggestions or improvements are highly appreciated!
PS: I know I could subquery but, there is so many different condition to find it.
So, I give up using a subquery.
Postgres CTE value not being used in where clause
Programing Coderfunda
July 31, 2024
No comments
WITH variant AS (
INSERT INTO accessory_variants (
accessory_id,
label,
multiple
) VALUES (
1,
'Colors',
FALSE
) RETURNING *
),
opts AS (
INSERT INTO accessory_variant_options (
accessory_id,
accessory_variant_id,
price,
label,
description
) VALUES (
1,
(SELECT id FROM variant),
100,
'Red',
'A red one'
),
(
1,
(SELECT id FROM variant),
100,
'Blue',
'A blue one'
) RETURNING id
),
ids AS (
SELECT JSONB_AGG(id) AS option_ids FROM opts
)
UPDATE
accessory_variants
SET
ordering = ids.option_ids
FROM
variant,
ids
WHERE
accessory_variants.id = variant.id
Where it gets weird is if I change it to something like this
...
UPDATE
accessory_variants
SET
ordering = TO_JSONB(variant.id)
FROM
variant,
ids
WHERE
accessory_variants.id = {existing row id}
The ordering table is populated with the correct id, so variant.id contains the correct id, but still can't be found by the where clause
zip the files and folders inside a parent directory without including the parent directory + Amazon Linux
Programing Coderfunda
July 31, 2024
No comments
Multiply polars columns of number type with object type (which supports __mul__)
Programing Coderfunda
July 31, 2024
No comments
import polars as pl
class Summary:
def __init__(self, value: float, origin: str):
self.value = value
self.origin = origin
def __repr__(self) -> str:
return f'Summary({self.value},{self.origin})'
def __mul__(self, x: float | int) -> 'Summary':
return Summary(self.value * x, self.origin)
def __rmul__(self, x: float | int) -> 'Summary':
return self * x
mapping = {
'CASH': Summary( 1, 'E'),
'ITEM': Summary(-9, 'A'),
'CHECK': Summary(46, 'A'),
}
df = pl.DataFrame({'quantity': [7, 4, 10], 'type': mapping.keys(), 'summary': mapping.values()})
Variable df looks like this
shape: (3, 3)
┌──────────┬───────┬───────────────┐
│ quantity ┆ type ┆ summary │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ object │
╞══════════╪═══════╪═══════════════╡
│ 7 ┆ CASH ┆ Summary(1,E) │
│ 4 ┆ ITEM ┆ Summary(-9,A) │
│ 10 ┆ CHECK ┆ Summary(46,A) │
└──────────┴───────┴───────────────┘
So the summary column contains a Summary class object, which supports multiplication. I now want to multiply this column with the quantity column. However
df.with_columns(pl.col('quantity').mul(pl.col('summary')).alias('qty_summary'))
is failing with SchemaError: failed to determine supertype of i64 and object.
Is there a way to multiply these columns?
30 July, 2024
React's useState hook defined inside function component in TypeScript still gave error - Invalid hook call
Programing Coderfunda
July 30, 2024
No comments
Been trying to figure out the bug for quite some time, but haven't been able to fix this. Everywhere on stackoverflow and other troubleshooting articles told about defining the hooks in the top level of a function component, and according to my belief, I have defined it inside the top of function component in typescript.
Still the error happens.
Error from browser console
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
* You might have mismatching versions of React and the renderer (such as React DOM)
* You might be breaking the Rules of Hooks
* You might have more than one copy of React in the same app
See
https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
What I tried
* const [hover, setHover] = useState(false); is actually defined in the top of a function component
* I have removed react, react-dom and their types @types/react, @types/react-dom and readded them of the version v18.3.0 both in the library & the app
* Ran npm ls react inside the app & found extraneous tagged react from the library, so ran npm prune
* Tested on browser firefox & edge
* Extracted a minimal component (button) from the library and redid a minimal version of the whole library and app implementation, figured the error comes only when adding the useState hook.
* Removed react in the generated app from create-react-app using yarn remove react command and just used the react which was included in the library. Had to run npm prune & also delete package-lock.json. Still it was an invalid hook implementation
Library
Just below is the code from react custom component library
(./jaghu/src/components/Button/Button.tsx)
import React, { useState } from "react";
export interface IButtonProps
extends React.DetailedHTMLProps<
React.ButtonHTMLAttributes,
HTMLButtonElement
> {
backgroundColor?: string;
color?: string;
width?: string;
height?: string;
}
export const Button: React.FunctionComponent = (props) => {
const [hover, setHover] = useState(false);
const MouseOver = () => setHover(true);
const MouseOut = () => setHover(false);
const { backgroundColor, width, height } = props;
let _style: React.CSSProperties = {
width: width ? width : "200px",
height: height ? height : "100px",
backgroundColor: backgroundColor ? backgroundColor : "skyblue",
color: hover ? "black" : "red",
};
/** Override Defaults CSS data using the values in Props CSS */
if (backgroundColor) _style.backgroundColor = backgroundColor;
if (width) _style.width = width;
if (height) _style.height = height;
return (
Hello BuTToNo
);
};
Library's package.json
(./jaghu/package.json)
{
"name": "jaghu",
"version": "1.0.0",
"license": "MIT",
"devDependencies": {
"@types/node": "^22.0.0",
"@types/react": "18.3.0",
"@types/react-dom": "18.3.0",
"@types/react-helmet": "^6.1.11",
"prettier": "^3.3.3",
"react": "18.3.0",
"react-dom": "18.3.0",
"react-helmet": "^6.1.0",
"typescript": "^5.5.4"
},
"scripts": {
"build": "rm -rf dist/ && prettier --write src/ && yarn run build:esm && yarn run build:cjs",
"build:esm": "tsc",
"build:cjs": "tsc --module CommonJS --outDir dist/cjs"
},
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"files": [
"dist"
],
"dependencies": {}
}
App
Just below is the code inside an app created by create-react-app
(./app/src/App.js)
import {Button} from 'jaghu';
function App() {
return (
);
}
export default App;
Code inside the create-react-app generated app's package.json
(./app/package.json)
{
"name": "app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^13.0.0",
"@testing-library/user-event": "^13.2.1",
"react-dom": "18.3.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"jaghu": "../jaghu"
}
}
Group by case where col A & col B = col B & col A, and then mutate column based on within-group similarity
Programing Coderfunda
July 30, 2024
No comments
I've got data that look like this:
source target weight
1 C D 2
2 F E 0
3 G H 1
4 B A 2
5 H G 1
6 A B 2
7 E F 0
8 D C 2
9 J I 1
10 P O 4
11 M N 3
12 K L 0
13 N M 4
14 O P 1
15 I J 3
16 L K 2
I want to use dplyr to create a column "symmetry" where for every pair of columns in which the source and target of one row equal the target and source of a different row, it assesses whether the "weight" column is equal. If it is equal, the column "symmetry" should read "symmetrical", and if they are not equal, it should read "asymmetrical".
This is the output I want:
source target weight symmetry
1 C D 2 Symmetrical
2 F E 0 Symmetrical
3 G H 1 Symmetrical
4 B A 2 Symmetrical
5 H G 1 Symmetrical
6 A B 2 Symmetrical
7 E F 0 Symmetrical
8 D C 2 Symmetrical
9 J I 1 Asymmetrical
10 P O 4 Asymmetrical
11 M N 3 Asymmetrical
12 K L 0 Asymmetrical
13 N M 4 Asymmetrical
14 O P 1 Asymmetrical
15 I J 3 Asymmetrical
16 L K 2 Asymmetrical
I tried this:
df%
group_by(source=pmin(source,target),target=pmax(source,target)) %>%
mutate(symmetry=ifelse(n_distinct(weight)==1,"Symmetrical","Asymmetrical")) %>%
ungroup()
but found that when I looked at the resulting dataframe, there were a bunch of cases in which source==target, which should not be the case for any row. I'm struggling with both the group_by syntax and the mutate syntax.
My preference is to use dplyr for this task, but would welcome ideas using any other R packages as well! Thank you!
Append dict to Chainmap during loop
Programing Coderfunda
July 30, 2024
No comments
I like to save the results in a json with some other data, and I want them to be chained.
The loop is in a function, which is called upon in the final dict which will become the json.
The best structure I have found for this is a Chainmap, but I can't seem to update, add or append to it.
Is there a way I can do this?
Or do I have to save the dictionaries in a list and then add more code to remove the "[" and "]" in my final dict?
The loop for the chainmap looks like this:
for root, subfolders, filenames in os.walk(path):
for filename in filenames:
try:
entry = {
"name": "#" + filename
#more data
}
#append the entry to chainmap?
except:
raise
Error handling for Laravel's HTTP facade
Programing Coderfunda
July 30, 2024
No comments
What is the best VSCode extension for Testing in Laravel?
Programing Coderfunda
July 30, 2024
No comments
I tried with Better PHP Unit extension. It works well at start. But it fails on refreshing tests when I modify code. If there is exception is not clear where it is. And refreshing test in left windows don't work. I must restart VSCode and simetimes it continue working.
I am trying now PHPUnit Test EXplorer extension, but I dont' know of how can configure it for working with php artisan test command.
How do you test in laravel in VSCode? submitted by /u/Pigmalion_Tseyor
[link] [comments]
29 July, 2024
Let's build a CMS with Filament 3 and Laravel 11 | 8 - Category SEO & Navbar improvements
Programing Coderfunda
July 29, 2024
No comments
Deploy the laravel application in under 120 seconds using deployer
Programing Coderfunda
July 29, 2024
No comments
https://www.youtube.com/watch?v=8YKLsAAdz5Y submitted by /u/samgan-khan
[link] [comments]
Has anyone used Turbolinks + Laravel to create a native hybrid app?
Programing Coderfunda
July 29, 2024
No comments
Has Turbolinks pretty much become exclusive to Ruby on Rails? Anyone know of alternatives or have RECENT tutorials on using it with Laravel?
Thanks 🙏 submitted by /u/LikeAnElephant
[link] [comments]
Supercharge your Laravel app with custom data types in PostgreSQL
Programing Coderfunda
July 29, 2024
No comments
My "Model Required Fields" package
Programing Coderfunda
July 29, 2024
No comments
I first needed this information while working on a large project with no tests or factories and many migrations. It was distracting to manually look for each required field.
I created a simple trait to fetch required fields. It was easy in Laravel 11 and 10. Then I realized that most programmers who face this problem are usually using older versions, so I added support for Laravel 9, 8, 7, and 6, and extracted the logic into a package.
I tested the code for each supported Laravel version and each SQL database: SQLite, MySQL, MariaDB, PostgreSQL, and Microsoft SQL Server. I needed to add support for each SQL database because I used the DB facade with raw SQL queries, and there were slight differences each time.
The package is fully tested with PHPUnit and GitHub Actions for every Laravel version and for each database.
The usage and examples are in the readme file.
I hope you like this package, and I welcome any contributions or comments.
package link:
https://github.com/watheqAlshowaiter/model-required-fields. submitted by /u/watheq_show
[link] [comments]


