29 March, 2024
Suppress default message of assert_eq! when custom message provided?
Programing Coderfunda
March 29, 2024
No comments
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.
Bidimensional splines, strictly increasing in one argument
Programing Coderfunda
March 29, 2024
No comments
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?
firebase_storage/object-not-found. No object exists at the desired reference
Programing Coderfunda
March 29, 2024
No comments
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,
);
},
),
);
}
}
Use Font Awesome icon as CSS content
Programing Coderfunda
March 29, 2024
No comments
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
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
Spring Security not working after API migration to Spring Boot 3
Programing Coderfunda
March 09, 2024
No comments
* 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.
Implementing an equation involving integrals as a filter
Programing Coderfunda
March 09, 2024
No comments
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
TypeScript Type on constructor to reference itself in extended class
Programing Coderfunda
March 09, 2024
No comments
class BaseEntity {
constructor(data: ) {
Object.assign(this, data);
}
}
class UserEntity extends BaseEntity {
name: string;
}
user = new UserEntity({name: 'Bar'});
The ultimate guide to creating a course platform with Vue 3 & Filament 3
Programing Coderfunda
March 09, 2024
No comments
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]
08 March, 2024
How to I add the sum of 2 dice throw continuously in JS?
Programing Coderfunda
March 08, 2024
No comments
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.
PHP compare two arrays and output all with zero at different record
Programing Coderfunda
March 08, 2024
No comments
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.
Using UPDATE ... SET arr[idx] = ... to aggregate rows into arrays
Programing Coderfunda
March 08, 2024
No comments
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?
Integrating TypeScript with Inertia.js and Vue.js
Programing Coderfunda
March 08, 2024
No comments
Laravel Request Forwarder
Programing Coderfunda
March 08, 2024
No comments
07 March, 2024
How to Create a New Table from JSONB_ARRAY_ELEMENTS and JSONB_OBJECT_KEYS in Postgresql?
Programing Coderfunda
March 07, 2024
No comments
It seems like there should be an easy way to create a new table from the keys and values.
Here is the request:
WITH sport_markets_api AS (
SELECT ((CONTENT::jsonb ->> 'data')::jsonb ->> 'sportMarkets')::jsonb AS details
FROM http_post(
'
https://api.thegraph.com/subgraphs/name/',
/> '{"query": "{sportMarkets(first:2,skip:0,orderBy:timestamp,orderDirection:desc){id,timestamp,address,gameId,maturityDate,tags,isOpen,isResolved,isCanceled,finalResult,homeTeam,awayTeam }}"}'::text,
'application/json'))
I tried:
SELECT
jsonb_array_elements(details) ->> jsonb_object_keys(jsonb_array_elements(details))
FROM sport_markets_api
and was expecting a table with columns based on the keys.
Is there a way to set Horizon's timeout on a job class ?
Programing Coderfunda
March 07, 2024
No comments
The way it used to work was the job was sent on a regular redis queue, and timeout would be set on the symfony process, effectively making the job run for the time it needed.
Now we want to send the job on a Horizon queue. The timeout is still set on the process, but Horizon's config has its own timeout value in the config. The problem is that the length of the recording will vary from case to case, with an average being 60 minutes, but we do have cases doing for multiple hours.
I could set it up to a very (very) long timeout, but I find it counterintuitive. Isn't there a way that I could specify the value for timeout on a job ? Otherwise, is setting a humongously long timeout the only logical way to do this ? submitted by /u/CouldHaveBeenAPun
[link] [comments]
Group the ones that are the same and right next to each other in sql
Programing Coderfunda
March 07, 2024
No comments
websit_id
updated_at
display_id
1222
03-06 06:00
apple
1222
03-06 08:00
apple
1222
03-06 10:00
carrot
1222
03-06 12:00
apple
1222
03-06 14:00
fig
1234
03-06 06:00
apple
1234
03-06 08:00
peach
I wanted to label the rows so that it groups the same display ID that are right next to each other but would not group them if there's something else in btw.
The desired outcome should be the following:
websit_id
updated_at
display_id
group_label
1222
03-06 06:00
apple
1
1222
03-06 08:00
apple
1
1222
03-06 10:00
carrot
2
1222
03-06 12:00
apple
3
1222
03-06 14:00
fig
4
1234
03-06 06:00
apple
1
1234
03-06 08:00
peach
2
I am using snowflake for this.
Async Initializers Swift MVVM not working
Programing Coderfunda
March 07, 2024
No comments
import Foundation
import FirebaseFirestore
class ChatViewModel: ObservableObject {
@Published var chat: ChatModel
@Published var opposingUser: User
init(oppUser: User) {
self.opposingUser = oppUser
Task {
if let fetchedChat = try? await fetchChat(oppUser: oppUser) {
self.chat = fetchedChat
}
}
}
init(chat: ChatModel) {
self.chat = chat
Task {
if let fetchedUser = try? await getOpposingUser(chat: chat) {
self.opposingUser = fetchedUser
}
}
}
@MainActor
func fetchChat(oppUser: User) async throws -> ChatModel? {
do {
let documents = try await Firestore.firestore()
.collection("conversations")
.whereField("users", arrayContains: UserService.shared.currentUser?.id ?? "error")
.whereField("users", arrayContains: oppUser.id)
.getDocuments()
for document in documents.documents {
guard let chatData = try? document.data(as: ChatModel.self) else {
print("[DEBUG fetchChat(oppUser: User)]: Error while converting Firebase Document to ChatModel ")
return nil
}
return chatData
}
} catch {
print("[DEBUG fetchChat(oppUser: User)]: \(error)")
throw error // Re-throw the error so it can be handled by the caller if needed
}
return nil
}
@MainActor
func getOpposingUser(chat: ChatModel) async throws -> User? {
do {
let opposingUid: String
if chat.users[0] == UserService.shared.currentUser?.id {
opposingUid = chat.users[1]
} else {
opposingUid = chat.users[0]
}
let document = try await Firestore
.firestore()
.collection("users")
.document(opposingUid)
.getDocument()
guard let opposingUserDoc = try? document.data(as: User.self) else {
// Handle the case where conversion to User fails
print("[DEBUG (getOpposingUser(chat: chatModel)]: Error while converting Firebase-Document to User ")
return nil
}
return opposingUserDoc
} catch {
print("[DEBUG (getOpposingUser(chat: chatModel)]: \(error) ")
throw error
}
return nil
}
}
I tried to "pre initilize" the variables with something like self.chat = ChatModel() but due to the nature of my Cahtmodel I can't init it without properties.
Herd for Windows
Programing Coderfunda
March 07, 2024
No comments
https://preview.redd.it/4t22y3gulvmc1.png?width=627&format=png&auto=webp&s=806bbe46479290857bc29f17e853d68667e03639
https://herd.laravel.com/ submitted by /u/VaguelyOnline
[link] [comments]
06 March, 2024
How to type two variables that are correlated in TypeScript?
Programing Coderfunda
March 06, 2024
No comments
If I define it in this way, it works
function process1() {
const yAxisType = 'primary';
const otherYAxisType = 'secondary';
return {
[yAxisType]: foo,
[otherYAxisType]: bar
}
}
function process2() {
const yAxisType = 'secondary';
const otherYAxisType = 'primary';
return {
[yAxisType]: foo,
[otherYAxisType]: bar
}
}
I want to merge these two functions. But I kept getting TS errors. How can I resolve it? Thanks!
function process(yAxisType: 'primary' | 'secondary') {
const otherYAxisType = yAxisType === 'primary' ? 'secondary' : 'primary';
return {
[yAxisType]: foo,
[otherYAxisType]: bar
}
}
Type '{ [x: string]: { fields: never[]; } | { type: "quantitative"; }; scale: { type: "quantitative"; }; }' is not assignable to type 'ComboChartAxisEncoding'.
Type '{ [x: string]: { fields: never[]; } | { type: "quantitative"; }; scale: { type: "quantitative"; }; }' is not assignable to type 'ComboChartSingleAxisEncoding'.
Type '{ [x: string]: { fields: never[]; } | { type: "quantitative"; }; scale: { type: "quantitative"; }; }' is missing the following properties from type '{ primary: ComboChartSingleAxisSectionEncoding; secondary: ComboChartSingleAxisSectionEncoding; scale: QuantitativeScale; }': primary, secondaryts(2322)
index.ts(85, 3): The expected type comes from property 'y' which is declared here on type 'ComboChartEncodingMap'
See Minimal repro on TS playground 👈
export type ComboChartAxisEncoding = ComboChartSingleAxisEncoding | ComboChartDualAxisEncoding;
export type ComboChartSingleAxisEncoding = {
primary: ComboChartSingleAxisSectionEncoding;
secondary: ComboChartSingleAxisSectionEncoding;
scale: 'quantitative';
};
export type ComboChartSingleAxisSectionEncoding = {
fields: number[];
};
export type ComboChartDualAxisEncoding = {
primary: ComboChartDualAxisSectionEncoding;
secondary: ComboChartDualAxisSectionEncoding;
};
export type ComboChartDualAxisSectionEncoding = {
fields: number[];
scale: 'quantitative';
};
function process1(): ComboChartAxisEncoding {
const yAxisType: 'primary' | 'secondary' = 'primary';
const otherYAxisType: 'primary' | 'secondary' = 'secondary';
return { // this works
[yAxisType]: { fields: [] },
[otherYAxisType]: { fields: [] },
scale: 'quantitative',
};
}
function process2(yAxisType: T): ComboChartAxisEncoding {
const otherYAxisType = (yAxisType === 'primary' ? 'secondary' : 'secondary') as (T extends 'primary' ? 'secondary' : 'primary');
// this doesn't work. Note that in my case this function wraps lots of test cases and each of them has this structure.
// So, if I don't have to change the structure of the JS objects, and just need to change the types, it would be better.
return {
[yAxisType]: { fields: [] },
[otherYAxisType]: { fields: [] },
scale: 'quantitative',
};
}
Receiving Incoming SMS post Android 8
Programing Coderfunda
March 06, 2024
No comments
* Background Service Limitations
* Broadcast Limitations
TL;DR: Starting Android 8 the OS will stop your Services and Broadcast Receivers except in some situations mentioned in above documents.
What is then a proper way to detect incoming sms? We can use WorkManager to manually query the SMS to check for new entries every 15 minutes. But what would be a way to get it instantly?
Also the official docs list the SMS_RECEIVE intent in the list of broadcasts that are exceptions to the above rules, but many have found that the receivers and services still get terminated and I have confirmed that by testing it myself.
There are some spend tracking apps out there that still do track the incoming sms regardless of the situation.
Would appreciate any inputs on the situation.
Thanks.
Logo puzzle I made for Laracon
Programing Coderfunda
March 06, 2024
No comments
https://preview.redd.it/mdeyzgg68smc1.jpg?width=1201&format=pjpg&auto=webp&s=6cb85cacca07a36125d7ee6b8db1f588f651bb01 submitted by /u/jeffjohnvol
[link] [comments]
Query Builder whereAll() and whereAny() Methods Added to Laravel 10.47
Programing Coderfunda
March 06, 2024
No comments
The Laravel team released v10.47 this week, which added the whereAll and whereAny methods to the query builder, the ability to use sorting flags with the Collection sortByMany method, and more.
This week will likely be the last release to the 10.x branch before Laravel 11’s release on Tuesday, March 12th, 2024. Laravel 10 will continue to receive bug fixes until August 6th, 2024, and security fixes until February 4th, 2025.
New whereAll and whereAny query builder methods
@musiermoore contributed a new whereAll and whereAny methods to the query builder, along with orWhereAll and orWhereAny methods. These new methods can search against multiple columns using or or and logic
// Before using `orWhere`
User::query()
->where(function ($query) use ($search) {
$query
->where('first_name', 'LIKE', $search)
->orWhere('last_name', 'LIKE', $search)
->orWhere('email', 'LIKE', $search)
->orWhere('phone', 'LIKE', $search);
});
// Using `whereAny`
User::whereAny(
[
'first_name',
'last_name',
'email',
'phone'
],
'LIKE',
"%$search%"
);
Here’s an example of using whereAll, in which all columns would need to match using AND:
$search = 'test';
User::whereAll([
'first_name',
'last_name',
'email',
], 'LIKE', "%$search%");
/*
SELECT * FROM "users" WHERE (
"first_name" LIKE "%test%"
AND "last_name" LIKE "%test%"
AND "email" LIKE "%test%"
)
*/
You can combine multiple like this using orWhereAll and orWhereAny methods.
Support Sort Option Flags on sortByMany Collections
Tim Withers contributed the ability to pass multiple sorting options to the Collection sortBy method. Before this update, you could accomplish this using multiple callables, but using PHP’s sorting flags:
// Pull Request before example
$this->campaigns = $campaigns
->with('folder', 'campaignCategory')
->get()
->sortBy([
fn ($a, $b) => str($a->folder?->name)->lower() str($b->folder?->name)->lower(),
fn ($a, $b) => str($a->campaignCategory->name)->lower() str($b->campaignCategory->name)->lower(),
fn ($a, $b) => str($a->name)->lower() str($b->name)->lower(),
])
// Using sorting flags
$this->campaigns = $campaigns
->with('folder', 'campaignCategory')
->get()
->sortBy(['folder.name', 'campaignCategory.name', 'name'], SORT_NATURAL | SORT_FLAG_CASE)
You can learn more about sorting flags from the sort function in the PHP manual.
Set $failOnTimeout on Queue Listeners
Saeed Hosseini contributed the ability to set the $failOnTimeout property on the queue job that indicates if the job should fail if the timeout is exceeded:
class UpdateSearchIndex implements ShouldQueue
{
public $failOnTimeout = false;
}
Release notes
You can see the complete list of new features and updates below and the diff between 10.46.0 and 10.47.0 on GitHub. The following release notes are directly from the changelog:
v10.47.0
* [10.x] Allow for relation key to be an enum by @AJenbo in
https://github.com/laravel/framework/pull/50311
/>
* Fix for "empty" strings passed to Str::apa() by @tiagof in
https://github.com/laravel/framework/pull/50335
/>
* [10.x] Fixed header mail text component to not use markdown by @dmyers in
https://github.com/laravel/framework/pull/50332
/>
* [10.x] Add test for the "empty strings in Str::apa()" fix by @osbre in
https://github.com/laravel/framework/pull/50340
/>
* [10.x] Fix the cache cannot expire cache with 0 TTL by @kayw-geek in
https://github.com/laravel/framework/pull/50359
/>
* [10.x] Add fail on timeout to queue listener by @saeedhosseiinii in
https://github.com/laravel/framework/pull/50352
/>
* [10.x] Support sort option flags on sortByMany Collections by @TWithers in
https://github.com/laravel/framework/pull/50269
/>
* [10.x] Add whereAll and whereAny methods to the query builder by @musiermoore in
https://github.com/laravel/framework/pull/50344
/>
* [10.x] Adds Reverb broadcasting driver by @joedixon in
https://github.com/laravel/framework/pull/50088
/>
The post Query Builder whereAll() and whereAny() Methods Added to Laravel 10.47 appeared first on Laravel News.
Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.
compare file's date bash
Programing Coderfunda
March 06, 2024
No comments
05 March, 2024
Cannot get TRUE when assigning report URL Param to a field
Programing Coderfunda
March 05, 2024
No comments
Running Python code in Docker gives: "/usr/bin/python3: can't find '__main__' module in 'test.py'"
Programing Coderfunda
March 05, 2024
No comments
FROM ubuntu:latest
RUN apt update
RUN apt install software-properties-common -y
RUN add-apt-repository ppa:deadsnakes/ppa
RUN apt install python3-pip -y
RUN apt-get remove swig
RUN apt-get install swig3.0
RUN ln -s /usr/bin/swig3.0 /usr/bin/swig
RUN pip3 install auto-sklearn
# During debugging, this entry point will be overridden. For more information, please refer to
https://aka.ms/vscode-docker-python-debug
/> ADD . /test.py
WORKDIR /
CMD ["python3", "test.py"]
and I get the error "/usr/bin/python3: can't find 'main' module in 'test.py'" from Docker Desktop. There are other posts similar to this on Stack Overflow, but I made the appropriate changes and it still doesn't seem to work. My Python code is quite simple
import pandas as pd
import autosklearn.classification as classification
import sklearn.model_selection as model_selection
if __name__ == "__main__":
def split_train_val(self, X: pd.DataFrame, y: pd.DataFrame):
X_train, X_val, y_train, y_val = model_selection.train_test_split(
X, y, test_size=0.25)
return X_train, X_val, y_train.to_frame(), y_val.to_frame()
model = classification.AutoSklearnClassifier(
time_left_for_this_task=3600,
ensemble_size=1,
ensemble_nbest=1,
)
dataset = pd.read_csv('data.csv')
dataset = dataset.iloc[:100]
X, y = dataset.drop(columns=[target_col]), dataset[target_col]
self.model.fit(X, y)
print(self.model.cv_results_)
Laravel Validation Provider Package
Programing Coderfunda
March 05, 2024
No comments
The Evolution of the Laravel Welcome Page
Programing Coderfunda
March 05, 2024
No comments
The release of Laravel 11 and Laravel Reverb will happen on Tuesday, March 12, 2024. Along with major updates to Laravel, we'll get a new welcome page when creating a new Laravel application with laravel new or composer.
I thought it would be fun to see how the welcome page has evolved over previous versions of Laravel. Whether you are new to the framework or have been around a while, there's something special about creating a new Laravel project and seeing that welcome screen!
Laravel 11
Laravel 11 will feature a light and dark theme, which looks gorgeous and inviting. It has a vibrant background, clean icons, and a welcoming feel that inspires creativity:
Laravel 11 welcome page (dark mode)
Laravel 11 welcome page (light mode)
Comparing Laravel 11 (top) to Laravel 10 (bottom)
Laravel 10
It's hard to believe that Laravel 10 was released a year ago on February 14, 2023. Over the last year, we've received countless amazing new features and quality-of-life updates. Here's what the welcome page looks like with a fresh Laravel 10 installation:
Laravel 10 welcome (dark mode)
Laravel 10 welcome (light mode)
Notably, the Laravel logo is centered and is only the logo mark. Laravel 9 and 8 had a left-aligned logo + Laravel text mark:
Logo mark changes between Laravel 8 and Laravel 10
Laravel 8
The welcome page featured in Laravel 8 was the first time we saw a significant change since Laravel 5.x. Laravel 8 was released on September 8, 2020, during the period of time Laravel released a major version every six months:
Laravel 8 dark mode featuring updated Laravel branding
Laravel 8 light mode featuring updated Laravel branding
Laravel's branding was technically updated around the Laravel 6 release. However, Laravel 8 was the first time the new logo was introduced on the welcome page. It featured four main areas/links: documentation, Laravel News, Laracasts, and prominent ecosystem links.
Laravel 5.5
Between Laravel 6 and 7, we didn't see any significant changes to the welcome page, but at some point in the 5.x releases, the welcome page included links to documentation, Laracasts, Laravel News, Forge, and GitHub:
Laravel 5.5 welcome page
Laravel 5.0
Laravel 5.0's landing page had the words "Laravel 5" and rendered a random inspiring quote using the Inspiring facade:
Laravel 5
{{ Inspiring::quote() }}
Laravel 5.0 welcome page
Bonus: Laravel 4.2
Laravel 4.2 had a minimal welcome page featuring a nostalgic logo (base64 image) and folder structure, which included this hello.php file, with the text, "You have arrived."
Laravel 4.2 hello page
The post The Evolution of the Laravel Welcome Page appeared first on Laravel News.
Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.
Laravel 11 + Laravel Reverb will be released on Tuesday, March 12th.
Programing Coderfunda
March 05, 2024
No comments





