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

11 April, 2024

Laravel Upgrading from Laravel 10 to Laravel 11

 Programing Coderfunda     April 11, 2024     No comments   

 The detailed upgrade document is available on the official Laravel document.

Also, read the Laravel 11 release notes. It will help us to upgrade our application.

1. PHP Version

Our first step is to upgrade your PHP version. Laravel 11 requires PHP 8.2.0 or greater.

2. Update Composer Dependencies

Now open our composer.json and update the following dependencies

  • php to^8.2
  • laravel/framework to ^11.0
  • Remove the guzzlehttp/guzzle package. Because it is already included in laravel/framework
  • nunomaduro/collision to ^8.1

I have updated some require-dev packages to match the Laravel 11 composer.json

diff --git a/composer.json b/composer.json
index 546a826..22a7942 100644
--- a/composer.json
+++ b/composer.json
@@ -5,25 +5,24 @@
"keywords": ["framework", "laravel", "boilerplate", "admin panel"],
"license": "MIT",
"require": {
- "php": "^8.1",
+ "php": "^8.2",
"balajidharma/laravel-admin-core": "^1.0",
- "guzzlehttp/guzzle": "^7.2",
- "laravel/framework": "^10.0",
- "laravel/sanctum": "^3.2",
- "laravel/tinker": "^2.8",
+ "laravel/framework": "^11.0",
+ "laravel/tinker": "^2.9",
"spatie/laravel-permission": "^5.5"
},
"require-dev": {
"barryvdh/laravel-debugbar": "^3.7",
- "fakerphp/faker": "^1.9.1",
+ "fakerphp/faker": "^1.23",
"laravel/breeze": "^1.7",
"laravel/dusk": "^7.1",
- "laravel/pint": "^1.0",
- "laravel/sail": "^1.18",
- "mockery/mockery": "^1.4.4",
- "nunomaduro/collision": "^7.0",
- "phpunit/phpunit": "^10.0",
- "spatie/laravel-ignition": "^2.0"
+ "laravel/pint": "^1.13",
+ "laravel/sail": "^1.26",
+ "mockery/mockery": "^1.6",
+ "nunomaduro/collision": "^8.1",
+ "phpunit/phpunit": "^10.5",
+ "spatie/laravel-ignition": "^2.4"
},
"autoload": {
"psr-4": {

Also, update the below package if you have installed

  • laravel/cashier-stripe to ^15.0
  • laravel/passport to ^12.0
  • laravel/sanctum to ^4.0
  • laravel/spark-stripe to ^5.0
  • laravel/telescope to ^5.0

3. Run composer update

We have updated all the dependencies on composer.json. Now is the time to run the composer update

./vendor/bin/sail composer update

I am getting the below error due to the laravel/breeze not supporting Laravel 11.

So, we need to find the latest version of laravel/breeze and add it to the composer.json file

  • laravel/breeze to ^2.0

Now getting the same error forlaravel/dusk

so update Dusk to the latest version

  • laravel/dusk to ^8.0

Again we getting errors, this time on our admin panel supporting packages

So, I am going to include Laravel 11 on both Laravel Menu and Laravel Category packages.

"illuminate/support": "^8.71|^9.0|^10.0|^11.0"

Again, this error is due to the spatie/laravel-permission. I am included spatie/laravel-permission in the application and admin code package.

So, going to remove spatie/laravel-permission and update the latest version of the admin code package.

finally, the composer update worked.

4. Check Laravel Version

To check the Laravel version, run the below command

./vendor/bin/sail artisan -v

//or

./vendor/bin/sail artisan --version

//If you not using sail
php artisan --version

Now our Admin Panel is using the Laravel 11.

5. Updating Sanctum

Now open the application in the browser. It throws the Fatal Error.

We are currently not using the Laravel Sanctum on the Admin Panel. So, I am going to remove the HasApiTokens from the user model.

Laravel 11 no longer supports Laravel Sanctum 3.x. Therefore, you should update your application’s Laravel Sanctum dependency to ^4.0 in your composer.json file.

If you're using Sanctum follow the steps mentioned in the upgrade document.

Now the admin panel is loading without errors

6. Remove Config Files

Taylor has introduced a slimmer config version. So, in Laravel 11 below the config is missing

  • config/broadcasting.php
  • config/cors.php
  • config/hashing.php
  • config/sanctum.php
  • config/view.php

We can publish them manually, with this command

php artisan config:publish

OR

php artisan config:publish --all

So, we deleted the below config files similar to Laravel 11

        deleted:    config/broadcasting.php
deleted: config/cors.php
deleted: config/hashing.php
deleted: config/sanctum.php
deleted: config/view.php

7. Update package.json

Laravel 11 is using the Vite version 5. So, we are going to update the Vite version. Also, we going to add the type to the module on package.json.

Find below the updated package.json file.

diff --git a/package.json b/package.json
index 2effbfc..30feaba 100644
--- a/package.json
+++ b/package.json
@@ -1,20 +1,17 @@
{
"private": true,
+ "type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"devDependencies": {
"@tailwindcss/forms": "^0.5.2",
- "alpinejs": "^3.4.2",
"autoprefixer": "^10.4.2",
- "axios": "^1.1.2",
- "laravel-vite-plugin": "^0.8.0",
- "lodash": "^4.17.19",
- "postcss": "^8.4.6",
- "postcss-import": "^14.0.1",
+ "axios": "^1.6.4",
+ "laravel-vite-plugin": "^1.0",
"tailwindcss": "^3.2.4",
- "vite": "^4.0.0"
+ "vite": "^5.0"
},
"dependencies": {
"daisyui": "^3.0.0",

We have removed alpinejs, lodash as per Laravel 11 package.json. We need to remove the alpinejs, lodash includes in resources/js/app.js and resources/js/bootstrap.js. After the removal, our app.js and bootstrap.js will have below-slim code.

resources/js/app.js

import './bootstrap';

resources/js/bootstrap.js

import axios from 'axios';
window.axios = axios;

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Now run the npm update after the npm update run the npm run dev

The fix the below error we need to update the postcss.config.js Because we updated the type as a module.

Add export default on postcss.config.js

export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

Now our Laravel Admin Panel is upgraded with Laravel 11.

Thank you for reading.

Source : Balaji Dharma (Medium)

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

08 April, 2024

Upgrading an open source project to Laravel 11 with Shift

 Programing Coderfunda     April 08, 2024     No comments   

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

Releasing a Filament JSON viewer/editor plugin [feedback is welcome]

 Programing Coderfunda     April 08, 2024     No comments   

Hi everyone!

Here's the link to the repo:


https://github.com/valentin-morice/filament-json-column

I was currently working on a project using Filament, and required a column to view and edit JSON data. I've found two plugins, jsoneditor and Pretty JSON, that would let me do either but not both at the same time, so I combined them.

If you'd feel like trying it, or have a look at the code, please do so. It's only my second package so I'd love to have some feedback. There's no testing since the plugin is mostly Alpine. Would you recommend doing some front-end testing using Dusk?

The future things I'm planning to work on:
- Blocking tab switching to viewer when JSON is invalid
- Moving from CDNs to npm
- Adding support for hints and other Filament methods submitted by /u/andre_ange_marcel
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

pandas/pyarrow ArrowTypeError: Unable to merge: Field on handcrafted partitioned parquet

 Programing Coderfunda     April 08, 2024     No comments   

I read the parquet file directly
pd.read_parquet(r'C:\Datasets\cn_data\dm\qmt\wqa_mfeatures\30m\year=2020\month=11\data.parquet')



No error will be reported.


But when I read the directory:
pd.read_parquet(r'C:\Datasets\cn_data\dm\qmt\wqa_mfeatures\30m\year=2020')



An error will be reported
ArrowTypeError: Unable to merge: Field month has incompatible types: int32 vs dictionary



This is because I handcrafted this partitioned path.
It is important that I have to hand craft the partitioned path.
I have 5000 item need transform and write to df.to_parquet(path, partition_cols=['year', 'month']) , and yes it would not overwrite existing files.



* But if I only need rerun 300 item, it would preduce new files, I can't delete the data produce by last run.

* With time goes, I need rerun transform function on new dates(year,month), I need new data overwrite old data.






I just want to keep pd.read_parquet function working with handcraft paths, this can reduce many works on reimplement a similar stuff and refactor pd.read_parquet in many projects.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

07 April, 2024

autocommit when using Spring BatchSqlUpdate

 Programing Coderfunda     April 07, 2024     No comments   

We have been using spring with MSSQL jdbc driver for a while. It's an older project where we have an applicatonContext.xml file that defines a datasource transaction manager and each method uses a proxy.


If we switch to using Spring's BatchSqlUpdate do we need to somehow disable autocommit for this call to gain the full benefit? I read lots of posts about this but they all give examples with you are building your own queries and using your connection directly like this and many more: does my batch really execute as expected if autocommit is set to true?


But I can't find anyone talking about when doing it the "spring way". The connection will default to autocommit=true and that's good for all of our other methods. But now we have just a couple of batch ones and I don't see a method to set autocommit to false for a specific method/class.


I'll give more details, but does anyone know if we should disable autocommit for this (like it sounds from other posts) and if so how?


The details are we have this in the applicationContext.xml:









PROPAGATION_SUPPORTS
PROPAGATION_SUPPORTS
PROPAGATION_SUPPORTS
PROPAGATION_REQUIRED






and the datasource comes from wildfly standalone.xml. This all has been working great. Now we are working on using batch mode. Our sql update methods are like this (somewhat simplified)
protected class UpdateUserUpdate extends SqlUpdate {
public UpdateUserUpdate(DataSource ds) {
setDataSource(ds);
setSql("update whatever.. set value = ?")
declareParameter(new SqlParameter(Types.VARCHAR));
compile();
}
public int myupdate(String s) {
Object[] params = new Object[] { s };
return update(params);
}
}



And if we simply change the parent class to BatchSqlUpdate, it does work fine:
protected class UpdateUserUpdateBatch extends BatchSqlUpdate {
...copy as before but now add...
setBatchSize(1000);
}



And we do see some improvement. But would we see more if we can somehow disable the autocommit or is that even possible?


Or would it be faster to just create a method, feed it our array of entries, get a new connection from the datasource, and use PreparedStatement, like:
con = dataSource.getConnection();
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement(sql);
do my add batch/executebatch in a 1000 loop...
pstmt.executeBatch();
con.commit();
con.setAutoCommit(false);



That is not the spring way but is it faster because I turned of autocommit or can you turn it of on BatchSqlUpdate?


Thank you!
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

zsh: bad CPU type in executable: node

 Programing Coderfunda     April 07, 2024     No comments   

I have installed nvm using brew. After that, I installed node version of 16 through nvm and check the current version using node -v to see whether the node is working properly. However, when I install version 14 or any other previous versions and runs node -v, it gives this "zsh: bad CPU type in executable: node" message and I have no idea what to do about this, though, installing node v17 and running node -v works as expected. Below are the snippet of the said commands.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Weekly /r/Laravel Help Thread

 Programing Coderfunda     April 07, 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

Laravel Forum 6.0 released

 Programing Coderfunda     April 07, 2024     No comments   

Hi all!

I've spent the past few weeks working on a new major release of Laravel Forum. Highlights include:

* Laravel 11 support
* A new UI preset system (similar to Laravel's Starter Kits)
* A new Livewire-powered, Tailwind-styled UI preset supporting dark mode




You can find an up-to-date live demo here:
https://laravel-forum.teamteatime.net/

I also overhauled the site where the docs are hosted. You can find them here:
https://www.teamteatime.net/docs/laravel-forum/6.x/general/

Feel free to ask questions here, or if you encounter any bugs, please open an issue!

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

The IEDA software cannot run the Vue project, and the IDEA shows that no executable file was found in $PATH

 Programing Coderfunda     April 07, 2024     No comments   

电脑的path环境在.zshrc中,把node的bin文件路径也添加到了zshrc中,终端也可以查看到node的版本,idea还是显示在path中未找到可执行的文件


运行报127错
env: node: No such file or directory


进程已结束,退出代码为 127


enter image description here


enter image description here


问下各位大佬怎么解决


enter image description here


enter image description here
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

06 April, 2024

A website displays attachments(files) either as pdf, XMl (XRBL) . I want to see info in XRBL files the same way as i see pdf and not the actual text

 Programing Coderfunda     April 06, 2024     No comments   

A website display attachments(files) as either as pdf , XMl (XRBL) . I want to see info in XRBL files the same way as i see pdf and not the actual. Is there any chrome extension for the same. Ideally I want to click on it and when it open it in browser,some way in the browswer itself so that I can make sense from it. If not possible in browser then how best to see the contents in a visual format rather than as text.



https://nsearchives.nseindia.com/corporate/xbrl/KANDARP_05042024142508_CLOSURE_TRADING_WINDOW_1081236_05042024022507_WEB.xml
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

I am trying to make a console.log but it does not work in my app

 Programing Coderfunda     April 06, 2024     No comments   

I'm building a react app and when I add a console.log, there is not output.


Help, please.


I'm using react, vite, chrome and edge
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

The docker client must be run elevated to connect

 Programing Coderfunda     April 06, 2024     No comments   

When I am trying to built docker app, I am getting below error. Command I am running is docker build -t node_curd_exe .




error during connect: Post
http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.40/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&rm=1&session=h3q9gxeprezyco28agiqe9jp2&shmsize=0&t=node_curd_exe&target=&ulimits=null&version=1: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.



Anything else I can do ?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Detecting .NET8 with Inno Setup and InnoDependenciyInstaller

 Programing Coderfunda     April 06, 2024     No comments   

I am looking at using InnoDependencyInstaller and it has a function that it uses under the hood:


Dependency_AddDotNet80
procedure Dependency_AddDotNet80;
begin
To detect .NET 8 using Inno Setup, you can use a combination of registry checks and custom code execution. Here's a basic example of how you can achieve this:

1. **Registry Check**: Check the registry to see if .NET 8 is installed. .NET 8 would be installed under a registry key specific to its version.

2. **Custom Code Execution**: If the registry check indicates .NET 8 is not installed, you can prompt the user to install it. You can execute custom code to check for the presence of .NET 8 assemblies or use InnoDependencyInstaller to install .NET 8 automatically.

Below is a sample script demonstrating how you can accomplish this:

```pascal
[Setup]
AppName=MyApp
AppVersion=1.0
DefaultDirName={pf}\MyApp

[Code]
function IsDotNet8Installed: Boolean;
var
  regKey: string;
begin
  // Check the registry to see if .NET 8 is installed
  regKey := 'Software\Microsoft\NET Framework Setup\NDP\v8\Full';
  Result := RegKeyExists(HKLM, regKey) or RegKeyExists(HKCU, regKey);
end;

procedure InstallDotNet8;
begin
  // Custom code to install .NET 8 or use InnoDependencyInstaller
  // Example:
  // ShellExec('open', 'https://dotnet.microsoft.com/download/dotnet/8.0', '', '', SW_SHOWNORMAL, ewNoWait, ErrorCode);
end;

function InitializeSetup: Boolean;
begin
  // Check if .NET 8 is installed
  if not IsDotNet8Installed then
  begin
    // Prompt the user to install .NET 8
    if MsgBox('This application requires .NET 8. Would you like to install it now?', mbConfirmation, MB_YESNO) = IDYES then
    begin
      InstallDotNet8;
      Result := False; // Abort setup
      Exit;
    end
    else
    begin
      // .NET 8 not installed and user declined installation
      MsgBox('.NET 8 is required to install this application. Setup will now exit.', mbError, MB_OK);
      Result := False; // Abort setup
      Exit;
    end;
  end;

  // .NET 8 is installed, continue setup
  Result := True;
end;
```

In this script:

- `IsDotNet8Installed` function checks the registry to see if .NET 8 is installed.
- `InstallDotNet8` procedure executes custom code to install .NET 8 or launches a browser to download it.
- `InitializeSetup` function is called before the setup begins. It checks if .NET 8 is installed. If not, it prompts the user to install it.

You may need to adjust the registry key path based on the specific registry location where .NET 8 is installed on your system. Additionally, replace the `InstallDotNet8` procedure with the appropriate code to install .NET 8 or utilize InnoDependencyInstaller to handle the installation automatically.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

05 April, 2024

Not able to stream in Flutter, throwing Platform exception

 Programing Coderfunda     April 05, 2024     No comments   

Here i am using 'apivideo_live_stream ' package for streaming purposes,Facing one issue while streaming time


[Issue]: Encountering an Exception when streaming Time in Flutter. Error Message: 'PlatformException(failed_to_start_stream, java.lang.IllegalArgumentException: Only one audio stream is supported by FLV, null, null)'. This issue is a significant roadblock in our current project, rendering it unable to run. Seeking assistance from the community to resolve this critical issue. Any support in resolving this matter would be greatly appreciated


////creating live stream controller instance
ApiVideoLiveStreamController createLiveStreamController(
BuildContext context) {
return ApiVideoLiveStreamController(
initialAudioConfig: config.audio,
initialVideoConfig: config.video,
onConnectionSuccess: () {
log('Connection succeeded');
},
onConnectionFailed: (error) {
log('on error failed1: $error');
Utils.showCustomDialog(context, 'Connection failed',
"Something went wrong, Please try again later"
// error
);
if (isStreaming) {
manualStopButtonClicked(context);
} else {
setIsStreaming(false);
}
// if (mounted) {

// }
},
onDisconnection: () async {
log('on error failed:2 ');
// Utils.snackBar('Disconnected', context);
// if (mounted) {
if (isStreaming) {
manualStopButtonClicked(context);
} else {
setIsStreaming(false);
}
// }
},
onError: (error) {
log('on error failed:3 $error');
// Get error such as missing permission,...
Utils.showCustomDialog(
context, 'Error', 'Something went wrong, Please try again later');
// if (mounted) {
if (isStreaming) {
manualStopButtonClicked(context);
} else {
setIsStreaming(false);
}
// }
});
}

//initialize controller
await _controller.initialize().catchError((exception) {
Utils.snackBar('Something went wrong, Please try again Later', context);
});



This the code for start stream
void onStartStreamingButtonPressed(BuildContext context) async {
_isStreamingStarted = true;
await _controller.setAudioConfig(config.audio);
startStreaming().then((_) {
setIsStreaming(true);
_isStreamingStarted = false;
notifyListeners();

startTimer();
Utils.snackBar("Streaming Started..!", context);
}).catchError((error) {
_isStreamingStarted = false;
if (error is PlatformException) {
log("strat stream 1 $error");
;
Utils.showCustomDialog(context, "Error",
"Something went wrong in server side, Please try again Later");
} else {
log("strat stream 2 $error");

Utils.showCustomDialog(
context, "Error", "Something went wrong , Please try again Later");
}
});
notifyListeners();
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Enabling authentication in swagger

 Programing Coderfunda     April 05, 2024     No comments   

I created a asp.net core empty project running on .net6. I am coming across an issue when I am trying to enable authentication in swagger. Swagger UI runs as expected, the only issue is whenever I click on the Authorize green button on the swagger UI it will pop up but say Unknown Security definition type and give me two options Authorize and Close. It does not show under Available authorizations Bearer(http,Bearer) and allow me to enter a jwt value. I ran into this article that goes over bearer authentication but it isn't much help for me. Am I missing something in the .AddSwaggerGen()?



builder.Services.AddAuthorization();

builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Name = "Authorization",
Description = "Bearer Authentication with JWT Token",
Type = SecuritySchemeType.Http
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
},
new List()
}
});
});

var app = builder.Build();
app.UseAuthorization();
app.UseAuthentication();
......
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Symfony custom field type with data transformer not working properly when in an embedded collection form

 Programing Coderfunda     April 05, 2024     No comments   

I am having a problem in Symfony with a custom data transformer on a custom form field - but only when this is used in a collection/embedded form within my main form. If I use the same custom field type and transformer for field directly in the main form, then it works perfectly.
Basically I have an app that is a database of all of my music/films/etc. Each item is stored in an entity called AVItem. For each of these items I can have zero or more tracks and I do this with a CollectionType. Within this embedded form/collection I have simple text fields and also a Collection of EntityType and they all work perfectly when submitting the main form; however, only the one field that uses my custom field type and transformer does not.
My custom field is for a "duration". In the database I save any lengths of time purely as an integer of seconds; however, I display it and want it entered as a string in the form [HH:]mm:ss. When displaying, the custom field and transformer works, it reads the number of seconds from the entity and then the "transform" method correctly displays that as HH:mm:ss. However, when I submit the main form and one of those tracks has something entered into it, when the "reverseTransform" method is called, the value it receives is always null!
However, in my main entity, where I also have a filled called "totalRunningTime" which also uses the same custom field type and transformer, the transform and reverseTransform always work perfectly.
This seems to be an issue purely within the Collection/embedded form.
Does anyone have an ideas?
Here are some code snippets.


This is my custom data transformer:
class TimeDurationTransformer implements DataTransformerInterface
{
private ?string $invalidMessage = null;

public function __construct( ?string $invalidMessage = null )
{
$this->invalidMessage = $invalidMessage;
}

/**
* Transform an integer (number of seconds) into a string of the form HH:mm:ss.
*
* @param mixed $value
* @return mixed
*/
public function transform( mixed $value ) : mixed
{
if ( ( null === $value ) || ( intval( $value ) == 0 ) ):
return null;
endif;

return sprintf( '%02d:%02d:%02d', ( $value/ 3600 ), ( $value / 60 % 60 ), ( $value% 60 ) );
}

/**
* Transform a string of the form HH:mm:ss into a number of seconds as an integer.
*
* @param mixed $value
* @return mixed
*/
public function reverseTransform( mixed $value ) : mixed
{
if ( ( null === $value ) || empty( $value ) || ( strlen( $value ) < 1 ) ) :
return null;
endif;

$matchResult = preg_match( pattern: '/^((\d{1,3}):)?(\d{1,2}):(\d{1,2})$/', subject: $value, matches: $matches, flags: PREG_UNMATCHED_AS_NULL );
// If the string entered does not match the pattern, throw an exception
if ( ( false === $matchResult) || ( 0 === $matchResult ) ) :
throw new TransformationFailedException( message: $this->invalidMessage, invalidMessage: $this->invalidMessage );
else:
if ( $matchResult === 1 && ( count( $matches ) == 5 ) ) :
if ( round( $matches[4] ) != null ):
return( round( $matches[4] ) + ( $matches[3] ? ( $matches[3] * 60 ) : 0 ) + ( $matches[3] ? ( $matches[2] * 3600 ) : 0 ) );
endif;
endif;
throw new TransformationFailedException( message: $this->invalidMessage, invalidMessage: $this->invalidMessage );
endif;
}
}



This is my custom field type:
class TimeDurationType extends AbstractType
{
private $translator;

public function __construct( TranslatorInterface $translator ) {
$this->translator = $translator;
}

public function buildForm( FormBuilderInterface $builder, array $options ) : void
{
$builder->addModelTransformer( new StuggiBearTimeDurationTransformer( invalidMessage: $options[ 'invalid_message' ] ) );
}

public function configureOptions( OptionsResolver $resolver ): void
{
$resolver->setDefaults( [
'data_class' => null,
'required' => false,
'constraints' => [
new PositiveOrZero(),
],
'invalid_message' => $this->translator->trans( 'message.assert.time_duration_format' ),
'attr' => [
'placeholer' => '',
],
] );
}

public function getParent(): string
{
return TextType::class;
}
}



Within my main form for my entity AVItem, I have one field that uses this custom field type - and it works fine:
public function buildForm( FormBuilderInterface $builder, array $options ): void
{
$this->editType = $options['edit_type'];
$this->isWishlistItem = $options[ 'isWishlistItem' ];

$builder
...
->add( 'totalRunningTime', TimeDurationType::class, [
'required' => false,
'label' => $this->translator->trans( 'form.field.label.total_running_time' ),
'label_html' => true,
'attr' => [
'placeholder' => 'HH:mm:ss',
],
'empty_data' => null,
] )
...



Within this form I then have the collection of Tracks:
$builder
...

->add( 'tracks', CollectionType::class, [
'label' => $this->translator->trans( 'form.field.label.tracks' ),
'label_html' => true,
'entry_type' => TrackEmbeddedFormType::class,
'entry_options' => [
'label' => false,
],
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
'empty_data' => [],
] )
...



...and then the embedded form type for the tracks:
$builder
->add( 'seriesEpisodeNumber', null, [
'required' => false,
'label' => $this->translator->trans( 'form.field.label.atce_series_episode_number' ),
] )
->add( 'title', null, [
'required' => ( $this->editType == FormEditType::SEARCH ) ? false : true,
'label' => $this->translator->trans( 'form.field.label.atce_title' ),
'label_html' => true,
] )
->add( 'additionalArtistsActors', EntityType::class, [
'required' => false,
'label' => $this->translator->trans( 'form.field.label.atce_additional_artists_actors' ),
'mapped' => true,
'class' => PersonGroup::class,
'by_reference' => true,
'multiple' => true,
'expanded' => false,
'choices' => [],
] )
->add( 'comment', null, [
'required' => false,
'mapped' => true,
'label' => $this->translator->trans( 'form.field.label.atce_comment' ),
'label_html' => true,
] )
->add( 'trackChapterNumber', null, [
'required' => true,
'label' => $this->translator->trans( 'form.field.label.atce_number' ),
'label_html' => true,
] )
->add( 'duration', TimeDurationType::class, [
'required' => false,
'label' => $this->translator->trans( 'form.field.label.atce_duration' ),
'label_html' => true,
'attr' => [
'placeholder' => 'HH:mm:ss',
],
'empty_data' => null,
] );
...



So, as I mentioned, the field "totalRunningTime" works perfectly with the data transformer, converting between integer seconds and a HH:mm:ss string and back.
However, the "duration" field within my collection/embedded tracks form only works reading from the database (the "transform" function works), but when I go to submit the form, the "reverseTransform" function always receives null.


If I change this field to be one of the standard types such as TextType or the like, then the value from the field seems to get passed.


Any help would be greatly appreciated.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

I need help beefing up my A/B testing package

 Programing Coderfunda     April 05, 2024     No comments   

I developed a A/B testing package for laravel a while back ago and I'm bringing it back.
https://github.com/pivotalso/laravel-ab

Eventually I want to beef it up to back it with a SaaS, but I'd really like more laravel devs to test drive it so I can make sure large issues are handled.

I also plan on beefing it up into feature flagging/user flagging, but I want to make sure this package is useful before I dev it further.

There are examples on how to use it here

https://docs.pivotal.so/docs/ab/laravel/installation/

Please ignore images on the site, it's still all under development.
AND if you decide to try the reporting saas, ignore the payment stuff, I havent done payment and wont until I feel comfortable enough the project is worth something. submitted by /u/IAmRules
[link] [comments]
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Firebase realtime rules - not working on child

 Programing Coderfunda     April 05, 2024     No comments   

Building a Firebase Realtime database with auth - but I
can't even get this started - returns permission denied
{
"rules": {
"forms": {
"$formid": {
".read": "true",
".write": "true"
}
}
}
}



ultimately I'd like to apply a rule like such
{
"rules": {
"forms": {
"$formid": {
".read": "auth.uid == data.child('userId').val()",
".write": "auth.uid != 'null'"
}
}
}
}



Data is formatted
forms




* $formId (eg -Nan39eo)



* userId










Console logging when rules are changed at the root to true returns that my authid is the same as the formId.userId
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

04 April, 2024

consume COM library from C# to rust

 Programing Coderfunda     April 04, 2024     No comments   

Question




I want to rewrite my project from C# to rust.
But I stuck in Segmentation Fault situation.
I think I misunderstood something, or meet crate limitation, hope for some help.


Rust Code






* find interface UUID
regedit capture

* find CLSID
regedit capture

* other id (I'm not sure shall we need it)
regedit capture



use windows::core::{GUID, HRESULT, IUnknown, IUnknown_Vtbl, interface};
use windows::Win32::System::Com::{
COINIT_APARTMENTTHREADED,
CLSCTX_ALL,
CoInitializeEx,
CoCreateInstance};

// define interface
#[interface("288EFDEC-3CF0-4F6C-8473-4E4CD47A93C7")]
unsafe trait Inhicshisx: IUnknown {
fn VPNGetRandomX(&self) -> HRESULT;
}

fn run() -> Result {
unsafe {
// 2F5AECD5-B5CD-41E1-8265-E2F6AA4548CB
const CLSID: GUID = GUID {
data1: 0x2F5AECD5,
data2: 0xB5CD,
data3: 0x41E1,
data4: [0x82, 0x65, 0xE2, 0xF6, 0xAA, 0x45, 0x48, 0xCB],
};

// initialize runtime
CoInitializeEx(Some(ptr::null_mut() as *mut c_void), COINIT_APARTMENTTHREADED)?;

// create COM object
let hisx: Inhicshisx = CoCreateInstance(&CLSID, None, CLSCTX_ALL)?;

// call object function
let value = hisx.VPNGetRandomX();
}

Ok(())
}



C# Part






* add a reference
regedit capture
* call function




using CSHISXLib;
string MyStr0;
CSHISXLib.Inhicshisx CSHISXLibObj = new CSHISXLib.nhicshisx();
MyStr0 = CSHISXLibObj.VPNGetRandomX();
Console.WriteLine(MyStr0);




* It works.






Update information




According to @IInspectable help, I can generate interface by oleview.exe tool.



* generated interface




[
odl,
uuid(288EFDEC-3CF0-4F6C-8473-4E4CD47A93C7),
helpstring("Inhicshisx Interface"),
dual,
oleautomation
]
interface Inhicshisx : IDispatch {
[id(0x00000001), helpstring("method VPNGetRandomX")]
HRESULT VPNGetRandomX([out, retval] BSTR* strRandom);
[id(0x00000002), helpstring("method VPNH_SignX")]
HRESULT VPNH_SignX(
[in] BSTR strRandom,
[in, optional, defaultvalue("")] BSTR strCardType,
[in, optional, defaultvalue("")] BSTR strServiceType,
[out, retval] BSTR* strRet);
}




* Rust code change




use windows::core::BSTR;

#[interface("288EFDEC-3CF0-4F6C-8473-4E4CD47A93C7")]
unsafe trait Inhicshisx: IDispatch {
fn VPNGetRandomX(&self) -> BSTR;
fn VPNH_SignX(&self, *mut BSTR, *mut BSTR, *mut BSTR) -> BSTR;
}



But it still cause Segmentation Fault, hope some advice 🙏
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Check if value exists in enum in TypeScript

 Programing Coderfunda     April 04, 2024     No comments   

I receive a number type = 3 and have to check if it exists in this enum:
export const MESSAGE_TYPE = {
INFO: 1,
SUCCESS: 2,
WARNING: 3,
ERROR: 4,
};



The best way I found is by getting all Enum Values as an array and using indexOf on it. But the resulting code isn't very legible:
if( -1 < _.values( MESSAGE_TYPE ).indexOf( _.toInteger( type ) ) ) {
// do stuff ...
}



Is there a simpler way of doing this?
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Why can I not see any of my points when adding them to my scene?

 Programing Coderfunda     April 04, 2024     No comments   

I have created a program for java fx to enter points in for an array. The points are to be shown with a line drawn between the maximal points. Also if you left mouse click it adds a point and recalculates the maximal points. If you right click it removes the point from the display. The problem I am running into is I am reading in a file with the points but nothing is showing in my display. I have even tried to manually add points and still nothing shows in the display. What am I missing?


I have tried everything I can to understand why no points are showing and am at a loss. I know it is something simple, but I cannot figure it out.
The points that should be added from the text file are

This is what it should look like when initially ran

This is what it actually looks like

I have corrected the mouse event so if I click in the upper left it will add points



Point.java
package application;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public final class Point implements Comparable {
private final double x;
private final double y;

public Point(double x, double y) {
this.x = x;
this.y = y;
}

public double getX() {
return x;
}

public double getY() {
return y;
}

public boolean isBelowAndLeftOf(Point other) {
return this.x
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