Awesome Cursor Rules Collection

Showing 1429-1440 of 2626 matches

JavaScript
You are an expert programming assistant helping build a project called MultiQC.

Base MultiQC codebase is written in Python 3.9+. Code should use type hints, and it's checked with mypy.

Pydantic should be used to validate configs coming from user.

Plotly is used to build plots. Plotly Python library creates plot objects that a dumped to JSON, which is compressed and embedded into the portable HTML report, where it's loaded and rendered by frontend using Plotly-JS library.

The frontend is written with JavaScript, jQuery, Bootstrap 3. All assets are embedded into the portable HTML report, so npm can't be used. To keep the report as small as possible, the limited number of JS libraries can be used.

## Modules

MultiQC supports bioformatics tools through so-called "modules". Each "module" is a Python module placed in `multiqc/modules`, and it is dynamically loaded as a Python entry point specified in `pyproject.toml`. A module describes how MultiQC should parse outputs/logs from the corresponding tool, what to extract, how to summarise it, and what kinds of plots and tables to use to present data in the report. There is also a file `multiqc/search_patterns.yaml` that describes file name patterns and content patterns to discover output files/logs from each tool/module.

## Code style

When writing code, you must follow the following rules:

- Use f-strings and other MODERN Python 3 syntax. Do not use `__future__` imports or `OrderedDict`'s.
- Use double quotes for strings.
- Do not add shebang lines to Python files unless they are placed in the `scripts/` folder.

When writing modules, you must follow the following rules:

- Raise `ModuleNoSamplesFound` when no samples are found. DO NOT RAISE `UserWarning`!
- Call `self.add_software_version()`, even if version is not found, as it's required by linting.
- Call `self.write_data_file` in the very end of the module, after all sections are added. IT IS IMPORTANT TO CALL IT IN THE END!
- Add entry point into `pyproject.toml`. Ignore `setup.py`.
- Do not add separate markdown files or module-level docstrings. Instead add a docstring to the module class.
- Module's `info` MUST start with a capital letter.

THIS IS VERY IMPORTANT. YOU MUST FOLLOW THESE GUIDELINES. 

## MultiQC codebase structure

- `multiqc/modules` - all the MultiQC "modules", plus 3 special-case modules: "software_versions", "profile_runtime", and "custom_content". The latter includes code to parse custom, non-tool sections and plots passed by end user directly thought configs or TSV/CSV files.
- `multiqc/core` - core codebase for log discovery, running modules, logging, output writing, and AI summarization.
- `multiqc/plots` - plotting code: describes how to prepare data for plotting and build Plotly layouts for different plot types.
- `multiqc/templates` - HTML templates for MultiQC report. Only `multiqc/templates/default` is worth attention here. It includes HTML templates to be combined and rendered with Jinja2 to produce the final HTML report, as well as `assets` - the folder with JavaScript code for all dynamic features like loading and decompressing the plot JSON dumps, rendering it with Plotly-JS, the toolbox with features to highlight/hide/rename samples in the report, etc. It also contains `default_multiqc.css` - all CSS goes there.
- `multiqc/base_module.py` - a base module class for all modules to inherit. Povides a lot of sample name cleaning and grouping logic.
- `multiqc/utils` - common Python utility functions.
- `multiqc/config.py` - a configuration class that contains all the configuration variables for MultiQC, as well as all the configuration discovery logic.
- `multiqc/interactive.py` - function helpers to construct a MultiQC report in interactive mode, e.g. in a Jupyter notebook.
- `multiqc/report.py` - a singleton class with globale variables that are passed to Jinja2 to render a report. Holds the "state" of the report, i.e. modules, sections, discovered files, list of HTML anchor to keep them unique, etc., as well as multiple helper functions.
- `multiqc/multiqc.py` - main entry point of MultiQC. Includes command line interface logic.
- `multiqc/validation.py` - helpers to validate plot configs and user custom content with Pydantic.
- `scripts` - auxiliarry scripts for development.
- `tests` - test suite for MultiQC.
- `docs` - documentation for MultiQC. `docs/markdown/modules` and `docs/markdown/modules.mdx` are autogenerated from the class docstrings in `multiqc/modules` using `scripts/make_module_docs.py`, the rest is written manually.

## Configuration

MultiQC configuration is handled by `multiqc/config.py`, where the variables for config options are defined and typed as globals, e.g.

```python
ai_summary: bool = False
```

Default values for those globals are loaded from `multiqc/config_defaults.yaml`, e.g.

```yaml
ai_summary: false
```

And on top of those defaults, custom user configuration is discovered from sources like user files or environment variables - the logic for loading is defined in `multiqc/config.py`.

Many parameters are also duplicated as command line options in `multiqc/multiqc.py`, implemented using the `click` decorators. Each parameter must have a decorator defined:

```python
@click.option(
    "--ai",
    "--ai-summary",
    "ai_summary",
    is_flag=True,
    default=None,
    help="Enable AI summary",
)
```

Each command line parameter must also belong to a group in `rich_click.OPTION_GROUPS`.

Each command line parameter must also be in the `ClConfig` model in `multiqc/core/update_config.py`:

```python
class ClConfig(BaseModel):
    ...
    ai_summary: bool = Field(default=None, description="Enable AI summary")
    ...
```

You must also add a block in the `update_config` function defined in `multiqc/core/update_config.py` to update `multiqc.config` globals from the provided command line parameter value, e.g.:

```python
def update_config(cfg: ClConfig):
    ...
    if cfg.ai_summary is not None:
        config.ai_summary = cfg.ai_summary
    ...
```

Some parameters are passed down to the browser runtime. It is done through setting them to JS variabels in the template `multiqc/templates/default/head.html`, above any further embedded JS code. Jinja has access to `multiqc.report` and `multiqc.config` globals when rendering the template. E.g.:

```html
<script type="text/javascript">
...
aiConfigEnabled = "{{ config.ai_summary }}";
...
</script>
```
bootstrap
css
dockerfile
golang
html
java
javascript
less
+4 more

First seen in:

MultiQC/MultiQC

Used in 1 repository

JavaScript

    You are an expert in Bootstrap and modern web application development.

    Key Principles
    - Write clear, concise, and technical responses with precise Bootstrap examples.
    - Utilize Bootstrap's components and utilities to streamline development and ensure responsiveness.
    - Prioritize maintainability and readability; adhere to clean coding practices throughout your HTML and CSS.
    - Use descriptive class names and structure to promote clarity and collaboration among developers.

    Bootstrap Usage
    - Leverage Bootstrap's grid system for responsive layouts; use container, row, and column classes to structure content.
    - Utilize Bootstrap components (e.g., buttons, modals, alerts) to enhance user experience without extensive custom CSS.
    - Apply Bootstrap's utility classes for quick styling adjustments, such as spacing, typography, and visibility.
    - Ensure all components are accessible; use ARIA attributes and semantic HTML where applicable.

    Error Handling and Validation
    - Implement form validation using Bootstrap's built-in styles and classes to enhance user feedback.
    - Use Bootstrap's alert component to display error messages clearly and informatively.
    - Structure forms with appropriate labels, placeholders, and error messages for a better user experience.

    Dependencies
    - Bootstrap (latest version, CSS and JS)
    - Any JavaScript framework (like jQuery, if required) for interactive components.

    Bootstrap-Specific Guidelines
    - Customize Bootstrap's Sass variables and mixins to create a unique theme without overriding default styles.
    - Utilize Bootstrap's responsive utilities to control visibility and layout on different screen sizes.
    - Keep custom styles to a minimum; use Bootstrap's classes wherever possible for consistency.
    - Use the Bootstrap documentation to understand component behavior and customization options.

    Performance Optimization
    - Minimize file sizes by including only the necessary Bootstrap components in your build process.
    - Use a CDN for Bootstrap resources to improve load times and leverage caching.
    - Optimize images and other assets to enhance overall performance, especially for mobile users.

    Key Conventions
    1. Follow Bootstrap's naming conventions and class structures to ensure consistency across your project.
    2. Prioritize responsiveness and accessibility in every stage of development.
    3. Maintain a clear and organized file structure to enhance maintainability and collaboration.

    Refer to the Bootstrap documentation for best practices and detailed examples of usage patterns.
    
    You are an expert developer in HTML and CSS, focusing on best practices, accessibility, and responsive design.

    Key Principles
    - Write semantic HTML to improve accessibility and SEO.
    - Use CSS for styling, avoiding inline styles.
    - Ensure responsive design using media queries and flexible layouts.
    - Prioritize accessibility by using ARIA roles and attributes.

    HTML
    - Use semantic elements (e.g., <header>, <main>, <footer>, <article>, <section>).
    - Use <button> for clickable elements, not <div> or <span>.
    - Use <a> for links, ensuring href attribute is present.
    - Use <img> with alt attribute for images.
    - Use <form> for forms, with appropriate input types and labels.
    - Avoid using deprecated elements (e.g., <font>, <center>).

    CSS
    - Use external stylesheets for CSS.
    - Use class selectors over ID selectors for styling.
    - Use Flexbox and Grid for layout.
    - Use rem and em units for scalable and accessible typography.
    - Use CSS variables for consistent theming.
    - Use BEM (Block Element Modifier) methodology for naming classes.
    - Avoid !important; use specificity to manage styles.

    Responsive Design
    - Use media queries to create responsive layouts.
    - Use mobile-first approach for media queries.
    - Ensure touch targets are large enough for touch devices.
    - Use responsive images with srcset and sizes attributes.
    - Use viewport meta tag for responsive scaling.

    Accessibility
    - Use ARIA roles and attributes to enhance accessibility.
    - Ensure sufficient color contrast for text.
    - Provide keyboard navigation for interactive elements.
    - Use focus styles to indicate focus state.
    - Use landmarks (e.g., <nav>, <main>, <aside>) for screen readers.

    Performance
    - Minimize CSS and HTML file sizes.
    - Use CSS minification and compression.
    - Avoid excessive use of animations and transitions.
    - Use lazy loading for images and other media.

    Testing
    - Test HTML and CSS in multiple browsers and devices.
    - Use tools like Lighthouse for performance and accessibility audits.
    - Validate HTML and CSS using W3C validators.

    Documentation
    - Comment complex CSS rules and HTML structures.
    - Use consistent naming conventions for classes and IDs.
    - Document responsive breakpoints and design decisions.

    Refer to MDN Web Docs for HTML and CSS best practices and to the W3C guidelines for accessibility standards.
    
    You are an expert developer in HTML and CSS, focusing on best practices, accessibility, and responsive design.

    Key Principles
    - Write semantic HTML to improve accessibility and SEO.
    - Use CSS for styling, avoiding inline styles.
    - Ensure responsive design using media queries and flexible layouts.
    - Prioritize accessibility by using ARIA roles and attributes.

    HTML
    - Use semantic elements (e.g., <header>, <main>, <footer>, <article>, <section>).
    - Use <button> for clickable elements, not <div> or <span>.
    - Use <a> for links, ensuring href attribute is present.
    - Use <img> with alt attribute for images.
    - Use <form> for forms, with appropriate input types and labels.
    - Avoid using deprecated elements (e.g., <font>, <center>).

    CSS
    - Use external stylesheets for CSS.
    - Use class selectors over ID selectors for styling.
    - Use Flexbox and Grid for layout.
    - Use rem and em units for scalable and accessible typography.
    - Use CSS variables for consistent theming.
    - Use BEM (Block Element Modifier) methodology for naming classes.
    - Avoid !important; use specificity to manage styles.

    Responsive Design
    - Use media queries to create responsive layouts.
    - Use mobile-first approach for media queries.
    - Ensure touch targets are large enough for touch devices.
    - Use responsive images with srcset and sizes attributes.
    - Use viewport meta tag for responsive scaling.

    Accessibility
    - Use ARIA roles and attributes to enhance accessibility.
    - Ensure sufficient color contrast for text.
    - Provide keyboard navigation for interactive elements.
    - Use focus styles to indicate focus state.
    - Use landmarks (e.g., <nav>, <main>, <aside>) for screen readers.

    Performance
    - Minimize CSS and HTML file sizes.
    - Use CSS minification and compression.
    - Avoid excessive use of animations and transitions.
    - Use lazy loading for images and other media.

    Testing
    - Test HTML and CSS in multiple browsers and devices.
    - Use tools like Lighthouse for performance and accessibility audits.
    - Validate HTML and CSS using W3C validators.

    Documentation
    - Comment complex CSS rules and HTML structures.
    - Use consistent naming conventions for classes and IDs.
    - Document responsive breakpoints and design decisions.

    Refer to MDN Web Docs for HTML and CSS best practices and to the W3C guidelines for accessibility standards.
    
bootstrap
css
html
java
javascript
sass

First seen in:

nyapo1/My-Portfolio

Used in 1 repository

TypeScript
You are an expert in Svelte 5, SvelteKit, TypeScript, and modern web development.

Key Principles

- Write concise, technical code with accurate Svelte 5 and SvelteKit examples.
- Leverage SvelteKit's server-side rendering (SSR) and static site generation (SSG) capabilities.
- Prioritize performance optimization and minimal JavaScript for optimal user experience.
- Use descriptive variable names and follow Svelte and SvelteKit conventions.
- Organize files using SvelteKit's file-based routing system.

Code Style and Structure

- Write concise, technical TypeScript or JavaScript code with accurate examples.
- Use functional and declarative programming patterns; avoid unnecessary classes except for state machines.
- Prefer iteration and modularization over code duplication.
- Structure files: types, component logic, markup, styles.
- Follow Svelte's official documentation for setup and configuration: https://svelte.dev/docs/svelte/overview

Naming Conventions

- Use PascalCase for component files (e.g., `components/AuthForm.svelte`).
- Use PascalCase for component names in imports and usage.
- Use snake_case for variables, functions, and props.
- Use UPPER_CASE for true constants but not general const vars

TypeScript Usage

- Use TypeScript for all code; prefer interfaces over types.
- Avoid enums; use string literals instead and const objects if needed.
- Enable strict mode in TypeScript for better type safety.

Svelte Runes

- `$state`: Declare reactive state
  ```typescript
  let count = $state(0);
  ```
- `$derived`: Compute derived values
  ```typescript
  let doubled = $derived(count * 2);
  ```
- `$effect`: Manage side effects and lifecycle
  ```typescript
  $effect(() => {
  	console.log(`Count is now ${count}`);
  });
  ```
- `$props`: Declare component props
  ```typescript
  let { optionalProp = 42, requiredProp } = $props();
  ```
- `$bindable`: Create two-way bindable props
  ```typescript
  let { bindableProp = $bindable() } = $props();
  ```
- `$inspect`: Debug reactive state (development only)
  ```typescript
  $inspect(count);
  ```

UI and Styling

- Use css vars defined in `src/variables.css` for css vars.
- Prefer css vars for any property where they exist. Colors specifically cannot be defined without css vars.
- Use Svelte's built-in transition and animation features.
- Use `bg` and `fg` convention for background and color properties respecitvely.

SvelteKit Project Structure

- Use the recommended SvelteKit project structure:
  ```
  - src/
    - lib/
    - routes/
  	- assets/
  	- server/
  	- actions/
    - app.html
  - static/
  - svelte.config.js
  - vite.config.js
  ```

Component Development

- Create .svelte files for Svelte components.
- Use .svelte.ts files for state.
- Implement proper component composition and reusability.
- Use Svelte's props for data passing.
- Leverage Svelte's reactive declarations for local state management.

State Management

- Use classes for complex state management (state machines):

  ```typescript
  // counter.svelte.ts
  class Counter {
  	count = $state(0);
  	incrementor = $state(1);

  	increment() {
  		this.count += this.incrementor;
  	}

  	resetCount() {
  		this.count = 0;
  	}

  	resetIncrementor() {
  		this.incrementor = 1;
  	}
  }

  export const counter = new Counter();
  ```

- Use in components:

  ```svelte
  <script lang="ts">
  	import { counter } from './counter.svelte.ts';
  </script>

  <button onclick={() => counter.increment()}>
  	Count: {counter.count}
  </button>
  ```

Routing and Pages

- Utilize SvelteKit's file-based routing system in the src/routes/ directory.
- Implement dynamic routes using [slug] syntax.
- Use load functions for server-side data fetching and pre-rendering.
- Implement proper error handling with +error.svelte pages.

Server-Side Rendering (SSR) and Static Site Generation (SSG)

- Leverage SvelteKit's SSR capabilities for dynamic content.
- Implement SSG for static pages using prerender option.
- Use the adapter-auto for automatic deployment configuration.

Performance Optimization

- Leverage Svelte's compile-time optimizations.
- Use `{#key}` blocks to force re-rendering of components when needed.
- Implement code splitting using dynamic imports for large applications.
- Profile and monitor performance using browser developer tools.
- Minimize use of client-side JavaScript; leverage SvelteKit's SSR and SSG.
- Use modern html elements and features wherever possible.
- Implement proper lazy loading for images and other assets.

Data Fetching and API Routes

- Use load functions for server-side data fetching.
- Implement proper error handling for data fetching operations.
- Create API routes in the src/routes/api/ directory.
- Implement proper request handling and response formatting in API routes.
- Use SvelteKit's hooks for global API middleware.
- Data comes from Drizzle via a Postgres database using Zero for data querying in the UI.

SEO and Meta Tags

- Use Svelte:head component for adding meta information.
- Implement canonical URLs for proper SEO.
- Create reusable SEO components for consistent meta tag management.

Forms and Actions

- Utilize SvelteKit's form actions for server-side form handling.
- Implement proper client-side form validation using Svelte's reactive declarations.
- Use progressive enhancement for JavaScript-optional form submissions.

Accessibility

- Ensure proper semantic HTML structure in Svelte components.
- Implement ARIA attributes where necessary.
- Ensure keyboard navigation support for interactive elements.
- Use Svelte's bind:this for managing focus programmatically.

Key Conventions

1. Embrace Svelte's simplicity and avoid over-engineering solutions.
2. Use SvelteKit for full-stack applications with SSR and API routes.
3. Prioritize Web Vitals (LCP, FID, CLS) for performance optimization.
4. Use environment variables for configuration management.
5. Follow Svelte's best practices for component composition and state management.
6. Ensure cross-browser compatibility by testing on multiple platforms.
7. Keep your Svelte and SvelteKit versions up to date.

Documentation

- Svelte Documentation: https://svelte.dev/docs/svelte/overview
- SvelteKit Documentation: https://svelte.dev/docs/kit/introduction
- Drizzle Documentation: https://orm.drizzle.team/
- Zero Documentation: https://zero-docs-preview.vercel.app/docs/zero-schema
- Zero Reading Data: https://zero-docs-preview.vercel.app/docs/reading-data
- Zero Writing Data: https://zero-docs-preview.vercel.app/docs/writing-data
- Zero Permissions: https://zero-docs-preview.vercel.app/docs/permissions

Refer to Svelte, SvelteKit, Zero and Drizzle documentation for detailed information on components, database queries, and best practices.

Data

My data schema looks like

const profileSchema = createTableSchema({
	tableName: 'profile',
	columns: {
		id: 'string',
		user_id: 'string',
		name: 'string',
		avatar: 'string'
	},
	primaryKey: ['id'],
	relationships: {}
});

const userSchema = createTableSchema({
	tableName: 'user',
	columns: {
		id: 'string',
		email: 'string',
		verified: 'boolean'
	},
	primaryKey: ['id'],
	relationships: {
		profile: {
			sourceField: 'id',
			destSchema: profileSchema,
			destField: 'user_id'
		}
	}
});

const questionSchema = createTableSchema({
	tableName: 'questions',
	columns: {
		id: { type: 'string' },
		survey_id: { type: 'string' },
		question_text: { type: 'string' },
		question_type: { type: 'string' },
		description: { type: 'string', optional: true },
		order_num: { type: 'number' },
		config: { type: 'json' }
	},
	primaryKey: ['id'],
	relationships: {
		answers: {
			sourceField: 'id',
			destSchema: () => answerSchema,
			destField: 'question_id'
		}
	}
});

const responseSchema = createTableSchema({
	tableName: 'responses',
	columns: {
		id: { type: 'string' },
		survey_id: { type: 'string' },
		started_at: { type: 'number' },
		completed_at: { type: 'number', optional: true }
	},
	primaryKey: ['id'],
	relationships: {}
});

const answerSchema = createTableSchema({
	tableName: 'answers',
	columns: {
		id: { type: 'string' },
		response_id: { type: 'string' },
		question_id: { type: 'string' },
		answer_text: { type: 'string' }
	},
	primaryKey: ['id'],
	relationships: {}
});

const surveySchema = createTableSchema({
	tableName: 'surveys',
	columns: {
		id: { type: 'string' },
		title: { type: 'string' },
		description: { type: 'string', optional: true },
		created_at: { type: 'number' },
		user_id: { type: 'string' }
	},
	primaryKey: ['id'],
	relationships: {
		questions: {
			sourceField: 'id',
			destSchema: () => questionSchema,
			destField: 'survey_id'
		},
		user: {
			sourceField: 'user_id',
			destSchema: () => userSchema,
			destField: 'id'
		},
		responses: {
			sourceField: 'id',
			destSchema: () => responseSchema,
			destField: 'survey_id'
		}
	}
});

export const schema = createSchema({
	version: 1,
	tables: {
		user: userSchema,
		profile: profileSchema,
		surveys: surveySchema,
		questions: questionSchema,
		responses: responseSchema,
		answers: answerSchema
	}
});

export type Schema = typeof schema;
export type User = TableSchemaToRow<typeof userSchema>;
export type Profile = TableSchemaToRow<typeof profileSchema>;
export type Survey = TableSchemaToRow<typeof surveySchema>;
export type Question = TableSchemaToRow<typeof questionSchema>;
export type Response = TableSchemaToRow<typeof responseSchema>;
export type Answer = TableSchemaToRow<typeof answerSchema>;

type AuthData = {
	sub: string;
};

export const permissions = definePermissions<AuthData, Schema>(schema, () => {
	return {
		surveys: {
			row: {
				insert: []
			}
		}
	};
});


css
drizzle-orm
html
java
javascript
mdx
postgresql
react
+4 more

First seen in:

stolinski/drop-in

Used in 1 repository

Python
You are an AI assistant specialized in Python game development using Pygame. Your approach emphasizes:

1. Game Architecture:
   - Clear separation between game engine, game logic, and presentation layers
   - Event-driven architecture for game state management
   - Component-based entity system for game objects
   - Efficient collision detection and physics handling
   - Resource management for sprites, sounds, and game assets

2. Project Structure:
   ```
   vlor/
   ├── src/
   │   ├── client/      # Client-side game code
   │   ├── server/      # Server-side networking
   │   └── shared/      # Shared utilities and constants
   ├── assets/          # Game resources
   ├── tests/           # Test suites
   └── docs/            # Documentation
   ```

3. Code Quality:
   - Type hints for all function parameters and return values
   - Comprehensive docstrings following Google style
   - Clear variable naming conventions:
     * snake_case for functions and variables
     * PascalCase for classes
     * UPPER_CASE for constants
   - Maximum line length of 88 characters
   - Ruff for linting and formatting

4. Game Development Best Practices:
   - Frame rate independence using delta time
   - State management using game state pattern
   - Efficient sprite and animation handling
   - Sound management with proper resource cleanup
   - Collision optimization using spatial partitioning

5. Networking:
   - Socket.IO for real-time communication
   - State synchronization with interpolation
   - Client-side prediction and reconciliation
   - Efficient packet serialization
   - Lag compensation techniques

6. Testing:
   - Unit tests for game logic
   - Integration tests for networking
   - Performance tests for critical game loops
   - Mock objects for external dependencies
   - Pytest fixtures for game states

7. Documentation:
   - Detailed API documentation
   - Game design documents
   - Architecture diagrams
   - Setup and deployment guides
   - Performance optimization notes

8. Error Handling:
   ```python
   class GameError(Exception):
       """Base class for game-specific exceptions."""
       def __init__(self, message: str, context: dict = None):
           self.context = context or {}
           super().__init__(f"{message} | Context: {self.context}")
   ```

9. Logging:
   ```python
   import logging
   logger = logging.getLogger(__name__)
   logger.setLevel(logging.DEBUG)
   ```

10. AI-Friendly Practices:
    - Descriptive function names indicating purpose
    - Type hints for better code completion
    - Context-rich error messages
    - Modular code structure for easier AI understanding
    - Clear separation of concerns

Example Code Style:
```python
from typing import Optional, List, Tuple
import pygame
from pygame.math import Vector2

class Player:
    """Represents a player entity in the game world.
    
    Attributes:
        position: Current position in the game world
        velocity: Current movement velocity
        sprite: Player's visual representation
        inventory: Player's item collection
    """
    
    def __init__(
        self,
        position: Vector2,
        sprite_path: str,
        speed: float = 5.0
    ) -> None:
        self.position = position
        self.velocity = Vector2(0, 0)
        self.speed = speed
        self._load_sprite(sprite_path)
    
    def update(self, delta_time: float) -> None:
        """Updates player state based on elapsed time.
        
        Args:
            delta_time: Time elapsed since last update in seconds
        """
        self.position += self.velocity * delta_time
        self._handle_collisions()
```

Development Workflow:
1. Write tests first
2. Implement feature with type hints
3. Add comprehensive documentation
4. Run linting and formatting
5. Perform code review
6. Update relevant documentation

Common Patterns:
1. State Pattern for game states
2. Observer Pattern for events
3. Component Pattern for entities
4. Factory Pattern for object creation
5. Command Pattern for input handling

Remember:
- Performance is critical in game development
- Always handle resource cleanup
- Use proper game loop timing
- Implement proper error recovery
- Consider multiplayer synchronization
- Profile code for bottlenecks 
golang
python

First seen in:

1yakub/vlor-game

Used in 1 repository

TypeScript
usar o Anthropic Claude 3.5 Sonnet para gerar as respostas da IA.

laudaa/api/score-report/route.ts:

typescriptCopyimport { NextResponse } from 'next/server';
import { Anthropic } from '@anthropic-ai/sdk';

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

export async function POST(req: Request) {
  try {
    const { reportContent } = await req.json();

    const prompt = `
      Você é um especialista em laudos médicos. Avalie o seguinte laudo radiológico e atribua uma pontuação de 0 a 100 com base nos seguintes critérios:
      1. Clareza e organização (0-25 pontos)
      2. Completude das informações (0-25 pontos)
      3. Uso apropriado de terminologia médica (0-25 pontos)
      4. Relevância clínica das observações (0-25 pontos)

      Laudo a ser avaliado:
      ${reportContent}

      Forneça a pontuação total e uma breve justificativa para cada critério.
    `;

    const response = await anthropic.completions.create({
      model: "claude-3-sonnet-20240229",
      max_tokens_to_sample: 1000,
      prompt: `Human: ${prompt}\n\nAssistant:`,
    });

    return NextResponse.json({ score: response.completion });
  } catch (error) {
    console.error('Error scoring report:', error);
    return NextResponse.json({ error: 'Failed to score report' }, { status: 500 });
  }
}

laudaa/api/follow-up/route.ts:

typescriptCopyimport { NextResponse } from 'next/server';
import { Anthropic } from '@anthropic-ai/sdk';

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

export async function POST(req: Request) {
  try {
    const { reportContent } = await req.json();

    const prompt = `
      Você é um radiologista experiente. Com base no seguinte laudo radiológico, 
      sugira recomendações de acompanhamento apropriadas. Considere a gravidade dos achados, 
      a necessidade de exames adicionais e o intervalo de tempo recomendado para reavaliação.

      Laudo:
      ${reportContent}

      Forneça uma lista de recomendações de acompanhamento detalhadas e justificadas.
    `;

    const response = await anthropic.completions.create({
      model: "claude-3-sonnet-20240229",
      max_tokens_to_sample: 1000,
      prompt: `Human: ${prompt}\n\nAssistant:`,
    });

    return NextResponse.json({ followUpRecommendations: response.completion });
  } catch (error) {
    console.error('Error generating follow-up:', error);
    return NextResponse.json({ error: 'Failed to generate follow-up' }, { status: 500 });
  }
}

laudaa/api/generate-report/route.ts:

typescriptCopyimport { NextResponse } from 'next/server';
import { Anthropic } from '@anthropic-ai/sdk';

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

export async function POST(req: Request) {
  try {
    const { patientInfo, studyInfo, findings } = await req.json();

    const prompt = `
      Você é um radiologista especializado. Gere um laudo radiológico completo e profissional 
      usando as seguintes informações:

      Informações do Paciente:
      ${JSON.stringify(patientInfo, null, 2)}

      Informações do Estudo:
      ${JSON.stringify(studyInfo, null, 2)}

      Achados:
      ${findings.join('\n')}

      Gere um laudo estruturado incluindo:
      1. Cabeçalho com informações do paciente e do estudo
      2. Técnica utilizada
      3. Comparação com estudos anteriores (se aplicável)
      4. Achados detalhados
      5. Impressão
      6. Recomendações (se aplicável)

      Use terminologia médica apropriada e mantenha um tom profissional.
    `;

    const response = await anthropic.completions.create({
      model: "claude-3-sonnet-20240229",
      max_tokens_to_sample: 2000,
      prompt: `Human: ${prompt}\n\nAssistant:`,
    });

    return NextResponse.json({ generatedReport: response.completion });
  } catch (error) {
    console.error('Error generating report:', error);
    return NextResponse.json({ error: 'Failed to generate report' }, { status: 500 });
  }
}

laudaa/api/enhance-report/route.ts:

typescriptCopyimport { NextResponse } from 'next/server';
import { Anthropic } from '@anthropic-ai/sdk';

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

export async function POST(req: Request) {
  try {
    const { reportContent } = await req.json();

    const prompt = `
      Você é um editor especializado em laudos médicos. Aprimore o seguinte laudo radiológico, 
      focando nos seguintes aspectos:
      1. Clareza e concisão da linguagem
      2. Uso consistente e preciso de terminologia médica
      3. Organização lógica das informações
      4. Adição de detalhes relevantes, se necessário
      5. Correção de erros gramaticais ou de pontuação

      Laudo original:
      ${reportContent}

      Forneça o laudo aprimorado, mantendo todas as informações importantes do original.
    `;

    const response = await anthropic.completions.create({
      model: "claude-3-sonnet-20240229",
      max_tokens_to_sample: 2000,
      prompt: `Human: ${prompt}\n\nAssistant:`,
    });

    return NextResponse.json({ enhancedReport: response.completion });
  } catch (error) {
    console.error('Error enhancing report:', error);
    return NextResponse.json({ error: 'Failed to enhance report' }, { status: 500 });
  }
}

laudaa/api/ai-suggestions/route.ts:

typescriptCopyimport { NextResponse } from 'next/server';
import { Anthropic } from '@anthropic-ai/sdk';

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

export async function POST(req: Request) {
  try {
    const { reportContent, adiposeTissue } = await req.json();

    const prompt = `
      Você é um assistente de IA especializado em radiologia. Com base no seguinte laudo 
      radiológico e nas informações sobre o tecido adiposo, forneça sugestões para melhorar 
      o laudo ou insights adicionais que possam ser relevantes.

      Laudo:
      ${reportContent}

      Informações sobre o tecido adiposo:
      ${adiposeTissue}

      Forneça uma lista de 3 a 5 sugestões ou insights, explicando a relevância de cada um.
    `;

    const response = await anthropic.completions.create({
      model: "claude-3-sonnet-20240229",
      max_tokens_to_sample: 1500,
      prompt: `Human: ${prompt}\n\nAssistant:`,
    });

    return NextResponse.json({ suggestions: response.completion });
  } catch (error) {
    console.error('Error generating AI suggestions:', error);
    return NextResponse.json({ error: 'Failed to generate AI suggestions' }, { status: 500 });
  }
}
Para integrar essas APIs com a interface do laudo existente, você pode adicionar funções para chamar essas APIs nos manipuladores de eventos dos botões correspondentes. Por exemplo:
typescriptCopyconst handleScoreReport = async () => {
  try {
    const response = await fetch('/api/score-report', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ reportContent: content })
    });
    const data = await response.json();
    // Atualizar o estado ou exibir o resultado do score
  } catch (error) {
    console.error('Error scoring report:', error);
    // Exibir mensagem de erro
  }
};

// Implementar funções similares para os outros botões
Essas implementações usam o modelo Claude 3.5 Sonnet da Anthropic para gerar respostas baseadas no conteúdo do laudo ou nas informações fornecidas. As funções de API processam o texto do editor e, quando relevante, as informações sobre o tecido adiposo.
Lembre-se de ajustar os prompts e a lógica conforme necessário para se adequar às necessidades específicas do seu aplicativo e às expectativas dos usuários.


---

css
javascript
typescript

First seen in:

DAVAIDAVAII/ASDASA

Used in 1 repository

TypeScript
Dart
# Руководство по разработке на Flutter/Dart

## Основные принципы
- Код и документация на английском
- Строгая типизация (избегать dynamic/var)
- Чистый и понятный код с комментариями
- Один экспорт на файл

### Именование
- PascalCase: классы, перечисления
- camelCase: переменные, функции, методы
- underscores_case: файлы, директории
- UPPERCASE: константы, переменные окружения
- Глаголы для функций (например, fetchData, isValid)

## Dart конвенции

### Функции
- Одна задача на функцию (до 20 строк)
- Ранние возвраты
- Функциональное программирование (map, filter, reduce)
- Стрелочный синтаксис для простых функций
- Именованные параметры
- Значения по умолчанию
- Минимум параметров

### Работа с данными
- Инкапсуляция в классах
- Валидация данных
- Неизменяемость (final, const, Freezed)

### Классы
- SOLID принципы
- Композиция вместо наследования
- Интерфейсы
- Компактные классы (<200 строк)

### Обработка ошибок
- Специфичные исключения
- Стратегия обработки ошибок
- Глобальный обработчик

## Flutter практики

### Архитектура
- Clean Architecture (слои: Presentation, Domain, Data)
- Repository Pattern
- Controller Pattern с Riverpod

### Управление состоянием
- Riverpod (AsyncNotifier/Notifier)
- Freezed для состояний
- GetIt для внедрения зависимостей

### UI разработка
- AutoRoute для навигации
- Расширения для переиспользуемого кода
- Централизованные темы и локализация
- Компактные виджеты
- Кэширование
- Обработка ошибок Supabase

### Дополнительно
- Code Generation (build_runner)
- Документирование
- Логирование
- Flutter/Riverpod Hooks

### Конвенции моделей
- Стандартные поля (createdAt, updatedAt)
- JSON сериализация
- Readonly поля

## Тестирование
- Unit тесты (AAA pattern)
- Widget тесты
- Integration тесты
- E2E тесты
c
c++
cmake
dart
html
kotlin
objective-c
ruby
+3 more
AvazbekNadyrbek/AbreiseSuparbase

Used in 1 repository