CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

01 April, 2024

possible to delete a mongodb catch block

 Programing Coderfunda     April 01, 2024     No comments   

I have updated my mongodb driver which forces me to use two completion blocks: .then() .catch() instead of a single callback. The consequence of this is that any error in my stack down the line will jump back up to the mongodb .catch() and potentially cascade processes all over again. Any 'done' block should only be called once. Code that was once easily traceable and was called only once has lost it's simplicity and coherence when migrating from a single callback to two blocks: then() and catch().
DB.insertOne(something).then( (r) =>
{
done({success:true});
}).catch( (e) =>
{
done({success:false, message:e.code});
});



My question - is it possible to delete the catch block, once the insert command has successfully completed? I want to do this because I do not want the mongodb .catch() block executing when irrelevant and unrelated events crash occur down the line. I am looking for something like this.
DB.insertOne(something).then( (r) =>
{
delete this.catch;//does not work
done({success:true});
}).catch( (e) =>
{
done({success:false, message:e.code});
});



note also that I do need the catch block in general. I need the catch block to execute once - for example if the insert command were to return an error for attempting to insert the same document with the same ._id (for example).
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Predicting on new data using locally weighted regression (LOESS/LOWESS)

 Programing Coderfunda     April 01, 2024     No comments   

How to fit a locally weighted regression in python so that it can be used to predict on new data?



There is statsmodels.nonparametric.smoothers_lowess.lowess, but it returns the estimates only for the original data set; so it seems to only do fit and predict together, rather than separately as I expected.



scikit-learn always has a fit method that allows the object to be used later on new data with predict; but it doesn't implement lowess.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Audit services?

 Programing Coderfunda     April 01, 2024     No comments   

I’ve built a medium sized Laravel app and was wondering if there are any companies/people I can hire to audit my code and give feedback and help me to improve my code architecture. Thanks. submitted by /u/jamlog
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

A little April Fools' fun from a shifty Shift

 Programing Coderfunda     April 01, 2024     No comments   

submitted by /u/mccreaja
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Creating Your Own PHP Helpers in a Laravel Project

 Programing Coderfunda     April 01, 2024     No comments   

---



Laravel provides many excellent helper functions that are convenient for doing things like working with arrays, file paths, strings, and routes, among other things like the beloved dd() function.


You can also define your own set of helper functions for your Laravel applications and PHP packages, by using Composer to import them automatically.


If you are new to Laravel or PHP, let’s walk through how you might go about creating your own helper functions that automatically get loaded by Laravel.


Creating a Helpers file in a Laravel App




The first scenario you might want to include your helper functions is within the context of a Laravel application. Depending on your preference, you can organize the location of your helper file(s) however you want, however, here are a few suggested locations:




*
app/helpers.php


*
app/Http/helpers.php






I prefer to keep mine in app/helpers.php in the root of the application namespace.


Autoloading




To use your PHP helper functions, you need to load them into your program at runtime. In the early days of my career, it wasn’t uncommon to see this kind of code at the top of a file:
require_once ROOT . '/helpers.php';




PHP functions cannot be autoloaded. However, we have a much better solution through Composer than using require or require_once.


If you create a new Laravel project, you will see an autoload and autoload-dev keys in the composer.json file:
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},




If you want to add a helpers file, composer has a files key (which is an array of file paths) that you can define inside of autoload:
"autoload": {
"files": [
"app/helpers.php"
],
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},




Once you add a new path to the files array, you need to dump the autoloader:
composer dump-autoload



Now on every request the helpers.php file will be loaded automatically because Laravel requires Composer’s autoloader in public/index.php:
require __DIR__.'/../vendor/autoload.php';



Defining Functions




Defining functions in your helpers class is the easy part, although, there are a few caveats. All of the Laravel helper files are wrapped in a check to avoid function definition collisions:
if (! function_exists('env')) {
function env($key, $default = null) {
// ...
}
}




This can get tricky, because you can run into situations where you are using a function definition that you did not expect based on which one was defined first.


I prefer to use function_exists checks in my application helpers, but if you are defining helpers within the context of your application, you could forgo the function_exists check.


By skipping the check, you’d see collisions any time your helpers are redefining functions, which could be useful.


In practice, collisions don’t tend to happen as often as you’d think, and you should make sure you’re defining function names that aren’t overly generic. You can also prefix your function names to make them less likely to collide with other dependencies.


Helper Example




I like the Rails path and URL helpers that you get for free when defining a resourceful route. For example, a photos resource route would expose route helpers like new_photo_path, edit_photo_path`, etc.


When I use resource routing in Laravel, I like to add a few helper functions that make defining routes in my templates easier. In my implementation, I like to have a URL helper function that I can pass an Eloquent model and get a resource route back using conventions that I define, such as:
create_route($model);
edit_route($model);
show_route($model);
destroy_route($model);



Here’s how you might define a show_route in your app/helpers.php file (the others would look similar):
if (! function_exists('show_route')) {
function show_route($model, $resource = null)
{
$resource = $resource ?? plural_from_model($model);

return route("{$resource}.show", $model);
}
}

if (! function_exists('plural_from_model')) {
function plural_from_model($model)
{
$plural = Str::plural(class_basename($model));

return Str::kebab($plural);
}
}




The plural_from_model() function is just some reusable code that the helper route functions use to predict the route resource name based on a naming convention that I prefer, which is a kebab-case plural of a model.


For example, here’s an example of the resource name derived from the model:
$model = new App\LineItem;
plural_from_model($model);
// => line-items

plural_from_model(new App\User);
// => users




Using this convention you’d define the resource route like so in routes/web.php:
Route::resource('line-items', 'LineItemsController');
Route::resource('users', 'UsersController');



And then in your blade templates, you could do the following:

{{ $lineItem->name }}




Which would produce something like the following HTML:

Line Item #1




Packages




Your Composer packages can also use a helpers file for any helper functions you want to make available to projects consuming your package.


You will take the same approach in the package’s composer.json file, defining a files key with an array of your helper files.


It’s imperative that you add function_exists() checks around your helper functions so that projects using your code don’t break due to naming collisions.


You should choose proper function names that are unique to your package, and consider using a short prefix if you are afraid your function name is too generic.


Learn More




Check out Composer’s autoloading documentation to learn more about including files, and general information about autoloading classes.



The post Creating Your Own PHP Helpers in a Laravel Project appeared first on Laravel News.


Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

31 March, 2024

There are two solutions for one board, using different chips. But one of their i2c address is the same. How to resolve conflict in one dts?

 Programing Coderfunda     March 31, 2024     No comments   

Two chips A and B conflict with 0x62 on i2c bus 10. If A@62 and B@62 are configured on dts, Linux loads the driver of A. If B@62 is in front, it will load the driver of B. Whoever is in front will Which driver will be loaded, and is there any way to make the two chips compatible in one DTS.


i2cdetect -r -y 10
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- UU -- UU -- UU -- UU --
60: UU -- UU -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --


i2cdetect -r -y 9
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- 0c -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- 28 -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- 37 -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- UU 62 UU -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- UU -- UU UU -- --


Hardware can't modify the address. If two dts are used, there will be two firmwares, which is inconvenient.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to properly integrate against 3rd party services

 Programing Coderfunda     March 31, 2024     No comments   

submitted by /u/lyotox
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Weekly /r/Laravel Help Thread

 Programing Coderfunda     March 31, 2024     No comments   

Ask your Laravel help questions here. To improve your chances of getting an answer from the community, here are some tips:

* What steps have you taken so far?
* What have you tried from the documentation?
* Did you provide any error messages you are getting?
* Are you able to provide instructions to replicate the issue?

* Did you provide a code example?

* Please don't post a screenshot of your code. Use the code block in the Reddit text editor and ensure it's formatted correctly.






For more immediate support, you can ask in the official Laravel Discord.

Thanks and welcome to the /r/Laravel community! submitted by /u/AutoModerator
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Positioning agent randomly within GIS space

 Programing Coderfunda     March 31, 2024     No comments   

I am looking to randomly position a fixed number of 'People' agents into my GIS space with regions. I currently have a table with a column for region and have identically named GIS regions in my GIS map.
Each 'Person' has a parameter 'region' which into which I map the value of the 'region' column in my table to. I then need to find some way to set the position of the agent to a random point inside the assigned region.


I have tried:
GISRegion myRegion = main.map.searchFirstRegion(region);
Point pt = myRegion.randomPointInside();
setXYZ( pt.x, pt.y, pt.z );



in the "On startup" field for my Person Agent but it seems that main.map.searchFirstRegion(region); does not do a good job of getting the correct region, as agents are distributed in places where there is no region (i.e in the sea):
Image


Ideally, I would like to use void setLocation(region) but setLocation takes in a Point or INode variable whereas the 'region' parameter is a string. Is there a way to search the list of regions by name for the matching region and return that region?
Thanks!
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Laravel Google Api

 Programing Coderfunda     March 31, 2024     No comments   

Hey Reddit community! 👋

I’m excited to share my latest project with you all: the Laravel Google Services Client! 🎉

🔗 GitHub Repository:
https://github.com/tomshaw/google-api submitted by /u/bigspacecraft
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

30 March, 2024

python valueerror : too many values to unpack

 Programing Coderfunda     March 30, 2024     No comments   

I am a python beginner . I was trying to run this code :

def main():
print ( " This program computes the average of two exam scores . ")
score1,score2 = input ("Enter two scores separated by a comma:")
average = (score1 + score2)/2.0
print ("The average of the score is : " , average )




when I summon the main() I got this ValueError :

ValueError: too many values to unpack (expected 2)




what is wrong with this code ?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

storing std::reference_wrapper into std::set

 Programing Coderfunda     March 30, 2024     No comments   

I was hoping infer std::reference_wrapper to MyType& automagically on bool operator
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Dijkstra’s Algorithm negative edges

 Programing Coderfunda     March 30, 2024     No comments   

How can I formally prove that Dijkstra’s algorithm doesn’t work with negative-weighted edges?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

expo DocumentPicker is not selecting any document

 Programing Coderfunda     March 30, 2024     No comments   

I am new to React native i have a problem withe the expo DocumentPicker for some reason the DocumentPicker does not select any file, and it always shows that Selected Document: None

import React, { useState } from "react";
import { Button, StyleSheet, Text, View } from "react-native";
import * as DocumentPicker from "expo-document-picker";

export default function App() {
const [document, setDocument] = useState(null);

const pickDocument = async () => {
const result = await DocumentPicker.getDocumentAsync({ type: 'application/pdf' });
if (result.type === "success") {
setDocument(result);
}
};

return (


Selected Document: {document ? document.name : "None"}



);
}

const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
padding: 20,
},
paragraph: {
marginTop: 24,
fontSize: 18,
fontWeight: "bold",
textAlign: "center",
},
});
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to get the json object with Typescript?

 Programing Coderfunda     March 30, 2024     No comments   

I am trying to get job by job_id via firebase rest api. I am getting this JSON result below. How i can rid of the 0 and get the object?


And Is there better way to get the job via firebase rest api?
This is my code:
{
"0": {
"category_id": 0,
"created_on": "Mar 29, 2024",
"description": "Dolor justo tempor duo ipsum accusam rebum gubergren erat. Elitr stet dolor vero clita labore gubergren. Kasd sed ipsum elitr clita rebum ut sea diam tempor. Sadipscing nonumy vero labore invidunt dolor sed, eirmod dolore amet aliquyam consetetur lorem, amet elitr clita et sed consetetur dolore accusam.",
"job_id": "TEL5UAVd5b3Q4jLY2aFfWs4QneMO",
"job_nature": "Full-time",
"location": "Gabrovo, Bulgaria",
"qualifications": [
"Rebum vero dolores dolores elitr",
"Elitr stet dolor vero clita labore gubergren",
"Dolor justo tempor duo ipsum accusam"
],
"salary": "$1500-$1900",
"title": "Marketing manager",
"user_id": "qDDuvTWL00N2sNXPhMy2rE0ZB8w2"
}
}

export class JobDetailComponent implements OnInit {
job = {} as Job;

constructor(
private apiService: ApiService,
private activeRoute: ActivatedRoute
) { }

ngOnInit(): void {
this.activeRoute.params.subscribe((data) => {
const id = data['jobId'];

this.apiService.getJob(id).subscribe((job) => {
this.job = job;
console.log(job)
});
});
}
}

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment.development';
import { Category } from './types/category';
import { Job } from './types/job';

@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }

getCategories() {
const { apiUrl } = environment;
return this.http.get(`${apiUrl}/categories.json`);
}
getJobs() {
const { apiUrl } = environment;
return this.http.get(`${apiUrl}/jobs.json`);
}
getJob(id: string) {
const { apiUrl } = environment;
return this.http.get(`${apiUrl}/jobs.json?orderBy="job_id"&equalTo="${id}"`);
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

29 March, 2024

Boost Your Laravel Forge Productivity 🚀

 Programing Coderfunda     March 29, 2024     No comments   

submitted by /u/christophrumpel
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Suppress default message of assert_eq! when custom message provided?

 Programing Coderfunda     March 29, 2024     No comments   

To my surprise, when I supply a custom message, it seems that assert_eq!'s default message is also printed out regardless.


Here I'm comparing some very long strs. So it is preferable not to clutter up the console but instead take a limited slice of each.
let left = tds.get_bulk_post_str();
let error_msg = format!("Bulk text is not what is expected: get_bulk_post_str() starts\n{}...\n\nExpected text starts\n{}...\n",
&left[0..20], &expected_bulk_text[0..20]);
// assert_eq! not used because assert_eq! apparently does not suppress its default message even when you supply a custom message!
// ... and in this case the default message is far too long.
// assert_eq!(left, expected_bulk_text, "{}", error_msg);

// instead, I think I'm forced to do something like this:
if left != expected_bulk_text {
panic!("{}", error_msg)
}



... is there any way of suppressing the default message?


If not, this seems a strange design choice, unlike any other language I know. Is it deliberate?


PS I'm aware the first 20 chars of each string might be identical. Obviously if I really wanted to go to town on this I'd have to examine both strings to find out the first case of difference, and just print corresponding slices from the middle.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Bidimensional splines, strictly increasing in one argument

 Programing Coderfunda     March 29, 2024     No comments   

I am working in R. I want to specify flexibly a function q(X,Y) where q is strictly increasing with respect to X (but not necessarily with respect to Y).
I want to use bidimensional splines but I don't know how to do (how to impose the monotonicity constraint in 2D).
So far, my method is to select several values of Y, and for each values of Y, I compute a monotone splines with respect to X. And then I interpolate to create the whole function q. But I wonder if it was possible to do all this in 1 step?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

firebase_storage/object-not-found. No object exists at the desired reference

 Programing Coderfunda     March 29, 2024     No comments   

I am trying to fetch images from firebase storage and display it in my flutter app but i am getting the error "No object exists at the desired reference". All the images are stored in the root directory. I have also changed the firebase rules to allow read and write without authentication.
This is my code.
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:firebase_storage/firebase_storage.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Wallpaper App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: WallpaperScreen(),
);
}
}

class WallpaperScreen extends StatefulWidget {
@override
_WallpaperScreenState createState() => _WallpaperScreenState();
}

class _WallpaperScreenState extends State {
List imageUrls = []; // Store fetched image URLs

@override
void initState() {
super.initState();
fetchImages();
}

Future fetchImages() async {
try {
final storageRef = FirebaseStorage.instance.ref();
final result = await storageRef.listAll();

for (var item in result.items) {
try {
final url = await item.getDownloadURL();
setState(() {
imageUrls.add(url);
});
} catch (error) {
print("Error fetching URL");
}
}
} catch (e) {
print("Error fetching images: $e");
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Wallpapers'),
),
body: GridView.builder(
itemCount: imageUrls.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 4.0,
mainAxisSpacing: 4.0,
),
itemBuilder: (BuildContext context, int index) {
return Image.network(
imageUrls[index], // Load image from URL
fit: BoxFit.cover,
);
},
),
);
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Use Font Awesome icon as CSS content

 Programing Coderfunda     March 29, 2024     No comments   

I want to use a Font Awesome icon as CSS content, i.e.,

a:before {
content: "...";
}




I know I cannot use HTML code in content, so is it only images left?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

09 March, 2024

SNMP OID not supported in HP GEN11 but same supported in old HP GEN machines

 Programing Coderfunda     March 09, 2024     No comments   

In DL325 GEN11 DA most of the SNMP OID below returns no such oid available for GEN11 but same works and returns the value in GEN10/GEN10 Plus. What to do get those values ?




cpqSeCpuStatus :
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.1.2.2.1.1.6
SNMPv2-SMI::enterprises.232.1.2.2.1.1.6 = No Such Instance currently exists at this OID
cpqDaCntlrCondition :
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.2.1.1.6
SNMPv2-SMI::enterprises.232.3.2.2.1.1.6 = No Such Instance currently exists at this OID
cpqDaAccelCondition :
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.2.2.1.9
SNMPv2-SMI::enterprises.232.3.2.2.2.1.9 = No Such Instance currently exists at this OID
cpqDaLogDrvStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.3.1.1.4
SNMPv2-SMI::enterprises.232.3.2.3.1.1.4 = No Such Instance currently exists at this OID
cpqDaLogDrvCondition :
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.3.1.1.11
SNMPv2-SMI::enterprises.232.3.2.3.1.1.11 = No Such Instance currently exists at this OID
cpqDaPhyDrvStatus :
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.5.1.1.6
SNMPv2-SMI::enterprises.232.3.2.5.1.1.6 = No Such Instance currently exists at this OID
cpqDaPhyDrvCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.5.1.1.37
SNMPv2-SMI::enterprises.232.3.2.5.1.1.37 = No Such Instance currently exists at this OID
cpqDaPhyDrvSmartStatus :
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.5.1.1.57
SNMPv2-SMI::enterprises.232.3.2.5.1.1.57 = No Such Instance currently exists at this OID
cpqDaTapeDrvStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.3.2.9.1.1.8
SNMPv2-SMI::enterprises.232.3.2.9.1.1.8 = No Such Instance currently exists at this OID
cpqHeEventLogCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.11.2.0
SNMPv2-SMI::enterprises.232.6.2.11.2.0 = No Such Instance currently exists at this OID
cpqHeThermalSystemFanStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.6.4
SNMPv2-SMI::enterprises.232.6.2.6.4 = No Such Instance currently exists at this OID
cpqHeThermalCpuFanStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.6.5
SNMPv2-SMI::enterprises.232.6.2.6.5 = No Such Instance currently exists at this OID
cpqHeFltTolFanCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.6.7.1.9
SNMPv2-SMI::enterprises.232.6.2.6.7.1.9 = No Such Instance currently exists at this OID
cpqHeTemperatureCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.6.8.1.6
SNMPv2-SMI::enterprises.232.6.2.6.8.1.6 = No Such Instance currently exists at this OID
cpqHeFltTolPwrSupplyCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.9.1
SNMPv2-SMI::enterprises.232.6.2.9.1 = No Such Instance currently exists at this OID
cpqHeFltTolPowerSupplyCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.9.3.1.4
SNMPv2-SMI::enterprises.232.6.2.9.3.1.4 = No Such Instance currently exists at this OID
cpqRackCommonEnclosureFanCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.22.2.3.1.3.1.11
SNMPv2-SMI::enterprises.232.22.2.3.1.3.1.11 = No Such Instance currently exists at this OID


cpqRackPowerSupplyCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.22.2.5.1.1.1.17
SNMPv2-SMI::enterprises.232.22.2.5.1.1.1.17 = No Such Instance currently exists at this OID
cpqHeResilientMemCondition:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.6.2.14.4
SNMPv2-SMI::enterprises.232.6.2.14.4 = No Such Instance currently exists at this OID
cpqNicIfLogMapStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.18.2.2.1.1.11
SNMPv2-SMI::enterprises.232.18.2.2.1.1.11 = No Such Instance currently exists at this OID
cpqFcaHostCntlrStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.16.2.7.1.1.4
SNMPv2-SMI::enterprises.232.16.2.7.1.1.4 = No Such Instance currently exists at this OID
cpqNicIfPhysAdapterStatus:
~# snmpwalk -v2c -c 7810_ext localhost 1.3.6.1.4.1.232.18.2.3.1.1.14
SNMPv2-SMI::enterprises.232.18.2.3.1.1.14 = No Such Instance currently exists at this OID
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Spring Security not working after API migration to Spring Boot 3

 Programing Coderfunda     March 09, 2024     No comments   

Software versions



* Spring Boot and dependencies: 3.2.2

* Spring Core : 6.1.3

* Spring Security 6.2.1

* Jetty Server: 11.0.20

* Languages: Java 17, Kotlin (Jetbrains Kotlin and Kotlin test library versions) 1.8.10






Below are modified code snippets for Jetty based Http Server Configuration, API Configuration and API Security Configuration which now uses a SecurityFilterChain instead of WebSecurityConfigurerAdapter.


Http Server Configuration
@Configuration
@EnableConfigurationProperties(ApiServiceProperties::class)
@ComponentScan("com......service")
@Import(value = [ApiSecurityConfig::class, WebFluxConfig::class])
class HttpServerConfig(var apiServiceProperties: ApiServiceProperties) {

/**
* Jetty Server Bean.
*/
@Bean
@SuppressWarnings("LongMethod")
fun jettyServer(
context: ApplicationContext,
springSecurityFilterChain: Filter,
mdcSetterFilter: MdcSetterFilter,
webContextFilter: WebContextFilter
): Server {
LOG.info(
"Starting Jetty server with " + ""
)

.. code removed ..

ServletContextHandler(server, "").apply {
val servlet = JettyHttpHandlerAdapter(WebHttpHandlerBuilder.applicationContext(context).build())
addServlet(ServletHolder(servlet), "/")

addFilter(FilterHolder(mdcSetterFilter), "/*", EnumSet.of(DispatcherType.REQUEST))
addFilter(FilterHolder(webContextFilter), "/*", EnumSet.of(DispatcherType.REQUEST))

// The ping endpoint should be unsecured, therefore ignored by the security filter
addFilter(
FilterHolder { request: ServletRequest, response: ServletResponse, chain: FilterChain ->
if (request is HttpServletRequest && request.requestURI != "/v1/ping") {
springSecurityFilterChain.doFilter(request, response, chain)
} else {
chain.doFilter(request, response)
}
},
"/v1/*",
EnumSet.of(DispatcherType.REQUEST)
)
}.start()

.. code removed ..

server.start()

LOG.info("Started Jetty server.")
return server
}

.. code removed ..
}



API Configuration
@Configuration
@ComponentScan(basePackages = [
"com......security",
"com......service"
])
@EnableConfigurationProperties(ApiServiceProperties::class)
@Import(HttpServerConfig::class)
class ApiServiceConfig : AbstractSpringBasedApplicationConfig()



API Security Configuration
@Configuration
@EnableWebSecurity
@ComponentScan("com......security", "com......service")
@EnableMethodSecurity(prePostEnabled = false, jsr250Enabled = true)
class ApiSecurityConfig(
private val restAuthenticationEntryPoint: RestAuthenticationEntryPoint,
private val restAuthenticationProvider: RestAuthenticationProvider
) {
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http
.cors { }
.anonymous { it.disable() }
.httpBasic { it.disable() }
.formLogin { it.disable() }
.logout { it.disable() }
.csrf { it.disable() }
.sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
.exceptionHandling { it.authenticationEntryPoint(restAuthenticationEntryPoint) }
.authenticationManager { authentication -> restAuthenticationProvider.authenticate(authentication) }
.addFilterBefore(RestAuthenticationTokenFilter(), AnonymousAuthenticationFilter::class.java)
.authorizeHttpRequests { it.requestMatchers("/**").permitAll().anyRequest().authenticated() }
return http.build()
}

@Bean
fun corsConfigurationSource(): CorsConfigurationSource = UrlBasedCorsConfigurationSource().apply {
registerCorsConfiguration(
"/**",
CorsConfiguration().applyPermitDefaultValues().apply {
allowedMethods = listOf("POST", "GET", "PUT", "DELETE", "HEAD")
}
)
}
}



Custom authentication provider
@Component
class RestAuthenticationProvider(
private val securityServiceClient: SecurityServiceClient,
private val cryptoService: CryptoService
) : AuthenticationProvider {

/**
* Given a [token] and [verifiedTokenModel], return a new User with granted authorities.
*/
private fun createAuthenticatedUser(token: String, verifiedTokenModel: VerifiedTokenModel) = User
.withUsername(verifiedTokenModel.verifiedPrincipalModel.id)
.password(token)
.authorities(verifiedTokenModel.verifiedPrincipalModel.scopes.map { scope ->
SimpleGrantedAuthority("ROLE_${scope.toUpperCase()}")
})
.build()

/**
* Given a [verifiedTokenModel], create a JSON Web Token to represent the authorizations of the verified principal.
*/
private fun createJwt(verifiedTokenModel: VerifiedTokenModel) = cryptoService.createAuthToken(
.. code removed ..
)

override fun authenticate(authentication: Authentication): Authentication? =
(authentication as? RestAuthenticationToken)?.token?.let { token ->
try {
val verifiedTokenModel = securityServiceClient.verifyToken(token)
val user = createAuthenticatedUser(token = token, verifiedTokenModel = verifiedTokenModel)

RestAuthenticationToken(
.. code removed ..
jwt = createJwt(verifiedTokenModel = verifiedTokenModel)
)
} catch (e: ReplyException) {
.. code removed ..
}
}

.. code removed ..
}



Below is a comparison of the new and old code for security configuration (Spring Boot 2.6.2 and Spring Core 5.3.14)





Postman request always receives a 403 response





Logs (without permit all)
DEBUG c.a.e.d.api.v1.security.MdcSetterFilter : Setting MDC logging context.
DEBUG c.a.e.d.a.v1.security.WebContextFilter : Setting WebContext on message
DEBUG o.s.security.web.FilterChainProxy : Securing GET /v1/clients/*/brands
INFO c.a.e.d.api.v1.config.HttpServerConfig : Token ::
DEBUG o.s.s.w.access.AccessDeniedHandlerImpl : Responding with 403 status code



I also tried passing it.requestMatchers("/**").permitAll().anyRequest().authenticated() in the call to authorizeHttpRequests() however that results in a different failure behavior


Logs (with permit all)
DEBUG c.a.e.d.api.v1.security.MdcSetterFilter : Setting MDC logging context.
DEBUG c.a.e.d.a.v1.security.WebContextFilter : Setting WebContext on message
DEBUG o.s.security.web.FilterChainProxy : Securing GET /v1/clients/*/brands
INFO c.a.e.d.api.v1.config.HttpServerConfig : Token ::
...
...
DEBUG o.s.w.s.adapter.HttpWebHandlerAdapter : [49377233] HTTP GET "/v1/clients/*/brands"
...
DEBUG s.w.r.r.m.a.RequestMappingHandlerMapping: [49377233] Mapped to com......service.ClientsApiController#listBrands(String, ServerHttpRequest)
DEBUG AuthorizationManagerBeforeMethodInterceptor: Authorizing method invocation ReflectiveMethodInvocation: public org.springframework.http.ResponseEntity com......service.ClientsApiController.listBrands(..); target is of class [com......service.ClientsApiController]

DEBUG AuthorizationManagerBeforeMethodInterceptor: Failed to authorize ReflectiveMethodInvocation: public org.springframework.http.ResponseEntity com......service.ClientsApiController.listBrands(...); target is of class [com......service.ClientsApiController] with authorization manager org.springframework.security.config.annotation.method.configuration.DeferringObservationAuthorizationManager@2323fe6a and decision AuthorityAuthorizationDecision [granted=false, authorities=[ROLE_READ_BRANDS]]
DEBUG s.w.r.r.m.a.RequestMappingHandlerAdapter: [49377233] Using @ExceptionHandler com......service.DefaultExceptionHandler#onThrowable(Throwable, ServerWebExchange)
DEBUG o.s.w.s.adapter.HttpWebHandlerAdapter : [49377233] Completed 403 FORBIDDEN




* Have tried multiple combinations of the security chain as suggested on several similar threads

* Added a few more log statements in security configuration code to capture these events and help understand how the new flow works

* DEBUG level log statements added inside the RestAuthenticationProvider.authenticate() are not showing up in the logs, indicating it is not getting invoked, and the flow is breaking before reaching that point.






However I suspect that the configured AuthenticationProvider (tried using authenticationProvider(..) earlier, but that did not work either) and AuthenticationManager are not getting plugged in the chain for some reason. Need help from the community in guiding me to set this up correctly. Thank you.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Implementing an equation involving integrals as a filter

 Programing Coderfunda     March 09, 2024     No comments   

This is a question that possibly borders on the intersection of the general usage of MATLAB and/or signal processing. Thought I would first ask the question in a MATLAB forum before trying signal processing.



So our lecturer read out his notes/paper and said the equation







could be implemented as a filter.



At first, it seemed difficult to follow the idea but when realizing that integration is same as finding areas under the curve which seems similar to applying a low pass filter so that only the portion of the signal under the threshold is allowed to pass through, it made a bit of sense. But how - meaning to say which function - can I use to implement the above equation? Do I need three filters or can I use just one? How do I use the terms preceding the integrals in the filter?



Thanks in advance
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

TypeScript Type on constructor to reference itself in extended class

 Programing Coderfunda     March 09, 2024     No comments   

This works but I was wondering if there is a better way of getting the constructor to know we want a UserEntity aka typeof this
class BaseEntity {
constructor(data: ) {
Object.assign(this, data);
}
}

class UserEntity extends BaseEntity {
name: string;
}

user = new UserEntity({name: 'Bar'});
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

The ultimate guide to creating a course platform with Vue 3 & Filament 3

 Programing Coderfunda     March 09, 2024     No comments   

Want to learn how to create a course platform, with filament 3, Vue 3 and Laravel 10? Tune into my series as we explore how to build a course platform.

This is an ongoing course with lessons published each day, I aim for 2-3 lessons a day to be published. submitted by /u/Tilly-w-e
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

08 March, 2024

How to I add the sum of 2 dice throw continuously in JS?

 Programing Coderfunda     March 08, 2024     No comments   

I'm doing a school project of a dice game, the player select a number between 6-9 and afterwards throw two dices. If the dices show the chosen number, its game over. But i cant get the sum to add upp after each throw, it just shows each specific throws sum.


Also, how do i get the program to understand that it's game over when the dices shows the "knockout" number?


let knockoutSiffra = 0;

const dices = document.querySelectorAll('.dice');
console.log(dices);

dices.forEach(bt =>{
bt.addEventListener('click', (e) =>{
knockoutSiffra = e.target.innerHTML;
console.log(knockoutSiffra)
})
})

document.getElementById('go')
.addEventListener('click', () => {

if(knockoutSiffra != 0){
choose.style.display = 'none'
play.style.display = 'block'
console.log('kör')
}

else{
console.log('välj ett nummer')

}

const showNumber = document.getElementById('showNumber');
showNumber.innerText = 'Ditt valda nummer är:' + " " + knockoutSiffra

})

// Slide 3

let lost = document.querySelector('.lost')
lost.style.display = 'none';

const dice1 = document.querySelector('.dice1');
const dice2 = document.querySelector('.dice2');
const result = document.querySelector('.dice-result');
const game = document.querySelector('.game');

let score = 0;

game.addEventListener('click', () => {
let d1 = GetRandomDice ();
let d2 = GetRandomDice ();

dice1.src = `Dice img/Dice-${d1}.png`;
dice2.src = `Dice img/Dice-${d2}.png`;

let sum = d1 + d2;
result.innerText = 'Antal poäng:' + " " + sum;

function GetRandomDice(){
return Math.ceil(Math.random() * 6);

}

})

This is just the last part of the HTML



Ditt valda nummer är:




Antal poäng:



Kasta tärningarna









Du förlorade!


Spela igen




Tried very much of different stuff but i can't get the code to work properly.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

PHP compare two arrays and output all with zero at different record

 Programing Coderfunda     March 08, 2024     No comments   

I have two arrays:



Array1:

ID: 1
ID: 2
ID: 3
ID: 4
ID: 5




Array2, with num value:

ID: 2, NUM: 200
ID: 4, NUM: 400




I want the output like: (adding zero if no record in array2)

ID: 1, NUM: 0
ID: 2, NUM: 200
ID: 3, NUM: 0
ID: 4, NUM: 400
ID: 5, NUM: 0




I am new to PHP, tried array_diff and array_intersect but not find the clue, could you please let me know how can I do that?



Thanks.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Using UPDATE ... SET arr[idx] = ... to aggregate rows into arrays

 Programing Coderfunda     March 08, 2024     No comments   

I currently have a database schema like the following table:
CREATE TABLE Measures(
expId SERIAL,
iteration INT NOT NULL,
value float4 NOT NULL,
PRIMARY KEY(expId, iteration)
);




So, a table of various measurements, repeated for n iterations.
Though, because we have more data than originally expected, I want to move to a new table layout that instead uses an array column, which overall gives better performance (already tested and benchmarked):
CREATE TABLE TmpMeasures(
expId SERIAL PRIMARY KEY,
values float4[] NOT NULL
);



My problem now is how to get the old data into the new format.
In the simplest case, the data may look something like this:
INSERT INTO Measures (expId, iteration, value)
VALUES
(1, 1, 1.1),
(1, 2, 2.1),
(1, 3, 3.1),
(2, 1, 1.2),
(3, 1, 1.3);



And conversion could be done with a two step process, roughly like this, to first create the array for an experiment, and then populate the iteration values:
INSERT INTO TmpMeasures(expId, values)
SELECT expId, '{}'::float4[]
FROM Measures
ON CONFLICT DO NOTHING;

UPDATE TmpMeasures tm
SET values[iteration] = m.value
FROM Measures m WHERE tm.expId = m.expId;



Though, my problem now is that the UPDATE actually only ever seems to take the first iteration, i.e., iteration = 1.
I am not quite understanding why that is the case.


I suspect, alternative approaches to values[iteration] would try to group by expId, and order by iteration and aggregate that into an array.


Unfortunately, the data isn't perfect, but iterations should line up.


So, the following seems to work, but it's extremely slow, and I don't quite understand why it's needed in the first place.
DO
$do$
BEGIN
FOR i IN 1..(SELECT max(iteration) FROM Measures m) LOOP
UPDATE TmpMeasures tm
SET values[i] = m.value
FROM Measures m
WHERE
tm.expId = m.expId AND
m.iteration=i;
END LOOP;
END
$do$;



Why does the "normal" update statement not suffice?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Integrating TypeScript with Inertia.js and Vue.js

 Programing Coderfunda     March 08, 2024     No comments   

submitted by /u/octarino
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Laravel Request Forwarder

 Programing Coderfunda     March 08, 2024     No comments   

submitted by /u/tersakyan
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts Home

Meta

Popular Posts

  • Write API Integrations in Laravel and PHP Projects with Saloon
    Write API Integrations in Laravel and PHP Projects with Saloon Saloon  is a Laravel/PHP package that allows you to write your API integratio...
  • Credit card validation in laravel
      Validation rules for credit card using laravel-validation-rules/credit-card package in laravel Install package laravel-validation-rules/cr...
  • iOS 17 Force Screen Rotation not working on iPAD only
    I have followed all the links on Google and StackOverFlow, unfortunately, I could not find any reliable solution Specifically for iPad devic...
  • C++ in Hindi Introduction
    C ++ का परिचय C ++ एक ऑब्जेक्ट ओरिएंटेड प्रोग्रामिंग लैंग्वेज है। C ++ को Bjarne Stroustrup द्वारा विकसित किया गया था। C ++ में आने से पह...
  • Python AttributeError: 'str' has no attribute glob
    I am trying to look for a folder in a directory but I am getting the error.AttributeError: 'str' has no attribute glob Here's ...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • July (2)
  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

Loading...

Laravel News

Loading...

Copyright © CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda