1685371792
dynamic_fonts
The dynamic_fonts
package for Flutter allows you to (relatively) easily add dynamically loaded web-hosted fonts to your appーjust like the google_fonts package, but for any arbitrary fonts hosted anywhere.
dynamic_fonts
is a fork of google_fonts
with more of the API exposed so that you can specify your own fonts.
If there is a font that you know you're going to use in your app, just bundle it normally. Don't bother with this package.
But if your app e.g. offers users multiple choices of fonts, and
then this package gives you a convenient way to load your fonts dynamically and keep your initial download slim.
With the dynamic_fonts
package, .ttf
or .otf
files do not need to be stored in your assets folder and mapped in the pubspec. Instead, they can be fetched once via http at runtime, and cached in the app's file system. This is ideal for development, and can be the preferred behavior for production apps that are looking to reduce the app bundle size. Still, you may at any time choose to include the font file in the assets, and the Dynamic Fonts package will prioritize pre-bundled files over http fetching. Because of this, the Dynamic Fonts package allows developers to choose between pre-bundling the fonts and loading them over http, while using the same API.
For example, say you want to use the FiraGO font (not in Google Fonts) in your Flutter app.
First, add the dynamic_fonts
package to your pubspec dependencies.
To import DynamicFonts
:
import 'package:dynamic_fonts/custom_dynamic_fonts.dart';
To register your font with DynamicFonts
, you will need to supply the family name and a map of DynamicFontsVariant
to DynamicFontsFile
.
DynamicFontsVariant
merely indicates font weight and font style (normal vs italic)DynamicFontsFile
stores checksum info and provides the URL for the fileIf we want to download FiraGO from the repo hosted on GitHub (don't do this in a production app!), the URL depends on the variant, so we need to do something like this:
class FiraGoFile extends DynamicFontsFile {
FiraGoFile(this.variant, String expectedFileHash, int expectedLength)
: super(expectedFileHash, expectedLength);
final DynamicFontsVariant variant;
String get _dir {
switch (variant.fontStyle) {
case FontStyle.normal:
return 'Roman';
case FontStyle.italic:
return 'Italic';
}
throw Exception('Unknown style: ${variant.fontStyle}');
}
@override
String get url =>
'https://raw.githubusercontent.com/bBoxType/FiraGO/9882ba0851f88ab904dc237f250db1d45641f45d/Fonts/FiraGO_TTF_1001/$_dir/FiraGO-${variant.toApiFilenamePart()}.ttf';
}
Now we can register the font like so, supplying the SHA256 and file sizes for security. (Actual SHA256 values not shown!)
DynamicFonts.register(
'FiraGO',
[
FiraGoFile(
const DynamicFontsVariant(
fontWeight: FontWeight.w400,
fontStyle: FontStyle.normal,
),
'0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
804888,
),
FiraGoFile(
const DynamicFontsVariant(
fontWeight: FontWeight.w700,
fontStyle: FontStyle.normal,
),
'0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
807140,
),
FiraGoFile(
const DynamicFontsVariant(
fontWeight: FontWeight.w400,
fontStyle: FontStyle.italic,
),
'0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
813116,
),
].fold<Map<DynamicFontsVariant, DynamicFontsFile>>(
{},
(acc, file) => acc..[file.variant] = file,
),
);
To use DynamicFonts
with the default TextStyle:
Text(
'This is Dynamic Fonts',
style: DynamicFonts.getFont('FiraGO'),
),
To use DynamicFonts
with an existing TextStyle
:
Text(
'This is Dynamic Fonts',
style: DynamicFonts.getFont(
'FiraGO', textStyle: TextStyle(color: Colors.blue, letterSpacing: .5),
),
),
or
Text(
'This is Dynamic Fonts',
style: DynamicFonts.getFont('FiraGO', textStyle: Theme.of(context).textTheme.headline4),
),
To override the fontSize
, fontWeight
, or fontStyle
:
Text(
'This is Dynamic Fonts',
style: DynamicFonts.getFont(
'FiraGO',
textStyle: Theme.of(context).textTheme.headline4,
fontSize: 48,
fontWeight: FontWeight.w700,
fontStyle: FontStyle.italic,
),
),
You can also use DynamicFonts.getTextTheme()
to make or modify an entire text theme to use the "FiraGO" font.
MaterialApp(
theme: ThemeData(
textTheme: DynamicFonts.getTextTheme(
'FiraGO',
Theme.of(context).textTheme,
),
),
);
Or, if you want a TextTheme
where a couple of styles should use a different font:
final textTheme = Theme.of(context).textTheme;
MaterialApp(
theme: ThemeData(
textTheme: DynamicFonts.getTextTheme('FiraGO', textTheme).copyWith(
body1: DynamicFonts.getFont('OtherFont', textStyle: textTheme.body1),
),
),
);
The dynamic_fonts
package will automatically use matching font files in your pubspec.yaml
's assets
(rather than fetching them at runtime via HTTP). Once you've settled on the fonts you want to use:
Italic
in the filename. Font weights map to file names as follows:{
FontWeight.w100: 'Thin',
FontWeight.w200: 'ExtraLight',
FontWeight.w300: 'Light',
FontWeight.w400: 'Regular',
FontWeight.w500: 'Medium',
FontWeight.w600: 'SemiBold',
FontWeight.w700: 'Bold',
FontWeight.w800: 'ExtraBold',
FontWeight.w900: 'Black',
}
Move those fonts to a top-level app directory (e.g. dynamic_fonts
).
Ensure that you have listed the folder (e.g. dynamic_fonts/
) in your pubspec.yaml
under assets
.
Note: If your fonts' names do not match up with the Google Font naming conventions, you will either have to register them in the fonts
section of pubspec.yaml
, or rename them.
Be sure to check the licenses of your fonts. For instance FiraGO comes with an OFL.txt
file.
Once you've decided on the fonts you want in your published app, you should add the appropriate licenses to your flutter app's LicenseRegistry.
For example:
void main() {
LicenseRegistry.addLicense(() async* {
final license = await rootBundle.loadString('dynamic_fonts/OFL.txt');
yield LicenseEntryWithLineBreaks(['dynamic_fonts'], license);
});
runApp(...);
}
Run this command:
With Flutter:
$ flutter pub add custom_dynamic_fonts
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
custom_dynamic_fonts: ^2.0.0
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:custom_dynamic_fonts/custom_dynamic_fonts.dart';
import 'package:dynamic_fonts/custom_dynamic_fonts.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
@override
void initState() {
_initCustomFonts();
super.initState();
}
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
final TextStyle headline4 = Theme.of(context).textTheme.headline4!;
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
style: DynamicFonts.getFont('FiraGO', textStyle: headline4),
),
Text(
'$_counter',
style:
DynamicFonts.getFont('FiraGO', fontStyle: FontStyle.italic),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
void _initCustomFonts() {
DynamicFonts.register(
'FiraGO',
[
_FiraGoFile(
const DynamicFontsVariant(
fontWeight: FontWeight.w400,
fontStyle: FontStyle.normal,
),
'495901c0c608ea265f4c31aa2a4c7a313e5cc2a3dd610da78a447fe8e07454a2',
804888,
),
_FiraGoFile(
const DynamicFontsVariant(
fontWeight: FontWeight.w400,
fontStyle: FontStyle.italic,
),
'36713ecac376845daa58738d2c2ba797cf6f6477b8c5bb4fa79721dc970e8081',
813116,
),
].fold<Map<DynamicFontsVariant, DynamicFontsFile>>(
{},
(acc, file) => acc..[file.variant] = file,
),
);
}
class _FiraGoFile extends DynamicFontsFile {
_FiraGoFile(this.variant, String expectedFileHash, int expectedLength)
: super(expectedFileHash, expectedLength);
final DynamicFontsVariant variant;
String get _dir {
switch (variant.fontStyle) {
case FontStyle.normal:
return 'Roman';
case FontStyle.italic:
return 'Italic';
}
}
@override
String get url =>
'https://raw.githubusercontent.com/bBoxType/FiraGO/9882ba0851f88ab904dc237f250db1d45641f45d/Fonts/FiraGO_TTF_1001/$_dir/FiraGO-${variant.toApiFilenamePart()}.ttf';
}
Download Details:
Author: amake
Source Code: https://github.com/amake/dynamic-fonts-flutter/
1683626788
A Python package used for simulating spiking neural networks (SNNs) on CPUs or GPUs using PyTorch Tensor
functionality.
BindsNET is a spiking neural network simulation library geared towards the development of biologically inspired algorithms for machine learning.
This package is used as part of ongoing research on applying SNNs to machine learning (ML) and reinforcement learning (RL) problems in the Biologically Inspired Neural & Dynamical Systems (BINDS) lab.
Check out the BindsNET examples for a collection of experiments, functions for the analysis of results, plots of experiment outcomes, and more. Documentation for the package can be found here.
To install the most recent stable release from the GitHub repository
pip install git+https://github.com/BindsNET/bindsnet.git
Or, to build the bindsnet
package from source, clone the GitHub repository, change directory to the top level of this project, and issue
pip install .
Or, to install in editable mode (allows modification of package without re-installing):
pip install -e .
To install the packages necessary to interface with the OpenAI gym RL environments library, follow their instructions for installing the packages needed to run the RL environments simulator (on Linux / MacOS).
Link to Docker repository.
We also provide a Dockerfile in which BindsNET and all of its dependencies come installed in. Issue
docker build .
at the top level directory of this project to create a docker image.
To change the name of the newly built image, issue
docker tag <IMAGE_ID> <NEW_IMAGE_ID>
To run a container and get a bash terminal inside it, issue
docker run -it <NEW_IMAGE_ID> bash
To run a near-replication of the SNN from this paper, issue
cd examples/mnist
python eth_mnist.py
There are a number of optional command-line arguments which can be passed in, including --plot
(displays useful monitoring figures), --n_neurons [int]
(number of excitatory, inhibitory neurons simulated), --mode ['train' | 'test']
(sets network operation to the training or testing phase), and more. Run the script with the --help
or -h
flag for more information.
A number of other examples are available in the examples
directory that are meant to showcase BindsNET's functionality. Take a look, and let us know what you think!
Issue the following to run the tests:
python -m pytest test/
Some tests will fail if Open AI gym
is not installed on your machine.
The simulation of biologically plausible spiking neuron dynamics can be challenging. It is typically done by solving ordinary differential equations (ODEs) which describe said dynamics. PyTorch does not explicitly support the solution of differential equations (as opposed to brian2
, for example), but we can convert the ODEs defining the dynamics into difference equations and solve them at regular, short intervals (a dt
on the order of 1 millisecond) as an approximation. Of course, under the hood, packages like brian2
are doing the same thing. Doing this in PyTorch
is exciting for a few reasons:
We can use the powerful and flexible torch.Tensor
object, a wrapper around the numpy.ndarray
which can be transferred to and from GPU devices.
We can avoid "reinventing the wheel" by repurposing functions from the torch.nn.functional
PyTorch submodule in our SNN architectures; e.g., convolution or pooling functions.
The concept that the neuron spike ordering and their relative timing encode information is a central theme in neuroscience. Markram et al. (1997) proposed that synapses between neurons should strengthen or degrade based on this relative timing, and prior to that, Donald Hebb proposed the theory of Hebbian learning, often simply stated as "Neurons that fire together, wire together." Markram et al.'s extension of the Hebbian theory is known as spike-timing-dependent plasticity (STDP).
We are interested in applying SNNs to ML and RL problems. We use STDP to modify weights of synapses connecting pairs or populations of neurons in SNNs. In the context of ML, we want to learn a setting of synapse weights which will generate data-dependent spiking activity in SNNs. This activity will allow us to subsequently perform some ML task of interest; e.g., discriminating or clustering input data. In the context of RL, we may think of the spiking neural network as an RL agent, whose spiking activity may be converted into actions in an environment's action space.
We have provided some simple starter scripts for doing unsupervised learning (learning a fully-connected or convolutional representation via STDP), supervised learning (clamping output neurons to desired spiking behavior depending on data labels), and reinforcement learning (converting observations from the Atari game Space Invaders to input to an SNN, and converting network activity back to actions in the game).
We simulated a network with a population of n Poisson input neurons with firing rates (in Hertz) drawn randomly from U(0, 100), connected all-to-all with a equally-sized population of leaky integrate-and-fire (LIF) neurons, with connection weights sampled from N(0,1). We varied n systematically from 250 to 10,000 in steps of 250, and ran each simulation with every library for 1,000ms with a time resolution dt = 1.0. We tested BindsNET (with CPU and GPU computation), BRIAN2, PyNEST (the Python interface to the NEST SLI interface that runs the C++NEST core simulator), ANNarchy (with CPU and GPU computation), and BRIAN2genn (the BRIAN2 front-end to the GeNN simulator).
Several packages, including BRIAN and PyNEST, allow the setting of certain global preferences; e.g., the number of CPU threads, the number of OpenMP processes, etc. We chose these settings for our benchmark study in an attempt to maximize each library's speed, but note that BindsNET requires no setting of such options. Our approach, inheriting the computational model of PyTorch, appears to make the best use of the available hardware, and therefore makes it simple for practicioners to get the best performance from their system with the least effort.
All simulations run on Ubuntu 16.04 LTS with Intel(R) Xeon(R) CPU E5-2687W v3 @ 3.10GHz, 128Gb RAM @ 2133MHz, and two GeForce GTX TITAN X (GM200) GPUs. Python 3.6 is used in all cases. Clock time was recorded for each simulation run.
If you use BindsNET in your research, please cite the following article:
@ARTICLE{10.3389/fninf.2018.00089,
AUTHOR={Hazan, Hananel and Saunders, Daniel J. and Khan, Hassaan and Patel, Devdhar and Sanghavi, Darpan T. and Siegelmann, Hava T. and Kozma, Robert},
TITLE={BindsNET: A Machine Learning-Oriented Spiking Neural Networks Library in Python},
JOURNAL={Frontiers in Neuroinformatics},
VOLUME={12},
PAGES={89},
YEAR={2018},
URL={https://www.frontiersin.org/article/10.3389/fninf.2018.00089},
DOI={10.3389/fninf.2018.00089},
ISSN={1662-5196},
}
Author: BindsNET
Source Code: https://github.com/BindsNET/bindsnet
License: AGPL-3.0 license
1683241620
В этой статье вы узнаете, как создать динамический слайдер изображений с помощью PHP. Ранее я разработал множество слайдеров изображений, используя html, css, javascript, jquery и т. д. Это первый раз, когда я поделюсь с вами тем, как сделать слайдер изображений с помощью PHP.
Чтобы создать слайдер изображений с помощью PHP, вы можете использовать следующие шаги:
Создайте папку на своем сервере для хранения изображений, которые вы хотите использовать в слайдере.
Используйте функцию PHP scandir()для чтения содержимого папки и сохранения имен файлов изображений в массиве.
Используйте foreachцикл для перебора массива имен файлов и вывода HTML для каждого изображения.
Используйте CSS для стилизации изображений и создания эффекта скольжения, например, используя свойства transitionи transformдля скольжения изображений по горизонтали или вертикали.
Используйте JavaScript или jQuery, чтобы создать кнопки навигации для ползунка.
Вот пример базового PHP-скрипта, который будет считывать все изображения в папке с именем «слайдер» и выводить их в виде слайдера изображений:
<div class="slider">
<?php
$folder = 'slider/';
$files = scandir($folder);
foreach($files as $file) {
$file_parts = pathinfo($file);
if($file_parts['extension'] == 'jpg') {
echo '<div class="slide">';
echo '<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" data-lazy-src="'.$folder.$file.'" /><noscript><img decoding="async" src="'.$folder.$file.'" /></noscript>';
echo '</div>';
}
}
?>
</div>
.slider {
width: 600px;
height: 400px;
overflow: hidden;
position: relative;
}
.slide {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
transition: left 1s ease-in-out;
}
.slide img {
width: 100%;
height: 100%;
}
<script type="rocketlazyloadscript">
var current = 0,
slides = document.getElementsByClassName("slide");
function nextSlide(){
goToSlide(current+1);
}
function previousSlide(){
goToSlide(current-1);
}
function goToSlide(n){
slides[current].className = 'slide';
current = (n+slides.length)%slides.length;
slides[current].className = 'slide showing';
}
var next = document.getElementById('next');
var previous = document.getElementById('previous');
next.onclick = function(){
nextSlide();
};
previous.onclick = function(){
previousSlide();
};
</script>
<button id="previous">Previous</button>
<button id="next">Next</button>
Этот скрипт создаст базовый слайдер изображений, который позволит пользователю перемещаться по изображениям с помощью кнопок «Назад» и «Далее». Вы можете настроить стиль и функциональность в соответствии с вашими требованиями.
Чтобы создать динамический автоматический слайдер изображений с помощью PHP, вы можете использовать следующие шаги:
Создайте папку на своем сервере для хранения изображений, которые вы хотите использовать в слайдере.
Используйте функцию PHP scandir()для чтения содержимого папки и сохранения имен файлов изображений в массиве.
Используйте foreachцикл для перебора массива имен файлов и вывода HTML для каждого изображения.
Используйте JavaScript или jQuery для создания эффекта ползунка, например, сдвига изображений по горизонтали или их появления и исчезновения.
Используйте функцию JavaScript setInterval(), чтобы установить временной интервал для автоматического поворота изображений.
Вот пример базового PHP-скрипта, который будет считывать все изображения в папке с именем «слайдер» и выводить их как автоматический слайдер изображений:
<div class="slider">
<?php
$folder = 'slider/';
$files = scandir($folder);
foreach($files as $file) {
$file_parts = pathinfo($file);
if($file_parts['extension'] == 'jpg') {
echo '<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" data-lazy-src="'.$folder.$file.'" /><noscript><img decoding="async" src="'.$folder.$file.'" /></noscript>';
}
}
?>
</div>
Этот код JavaScript создает автоматический слайдер изображения, используя setTimeout()функцию для изменения изображения каждые 3 секунды (3000 миллисекунд), как указано в timeпеременной.
Вот как это работает:
<script type="rocketlazyloadscript">
var index = 0;
var images = [];
var time = 3000;
// Image List
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
// Change Image
function changeImg(){
document.slide.src = images[index];
if(index < images.length - 1){
index++;
} else {
index = 0;
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
</script>
<img name="slide" width="600" height="400">
Этот скрипт будет автоматически менять изображение каждые 3 секунды (3000 миллисекунд). Вы можете настроить временной интервал в соответствии с вашими требованиями.
Примечание. Это базовый пример, вы можете добавить некоторые дополнительные функции, такие как кнопки навигации, подписи и т. д. Надеюсь, что приведенная выше статья помогла вам узнать, как создать слайдер изображений и автоматический слайдер изображений с помощью PHP .
Оригинальный источник статьи: https://foolishdeveloper.com/
1683237900
在本文中,您将了解如何使用 PHP 创建动态图像滑块。之前我用html, css, javascript, jquery等设计过很多图片滑块,这是我第一次和大家分享如何用PHP制作图片滑块。
要使用 PHP 创建图像滑块,您可以使用以下步骤:
在您的服务器上创建一个文件夹来存储您要在滑块中使用的图像。
使用 PHPscandir()函数读取文件夹的内容并将图像的文件名存储在数组中。
使用foreach循环遍历文件名数组并输出每个图像的 HTML。
使用 CSS 为图像设置样式并创建滑动效果,例如使用transition和transform属性使图像水平或垂直滑动。
使用 JavaScript 或 jQuery 为滑块创建导航按钮。
这是一个基本的 PHP 脚本示例,它将读取名为“slider”的文件夹中的所有图像并将它们输出为图像滑块:
<div class="slider">
<?php
$folder = 'slider/';
$files = scandir($folder);
foreach($files as $file) {
$file_parts = pathinfo($file);
if($file_parts['extension'] == 'jpg') {
echo '<div class="slide">';
echo '<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" data-lazy-src="'.$folder.$file.'" /><noscript><img decoding="async" src="'.$folder.$file.'" /></noscript>';
echo '</div>';
}
}
?>
</div>
.slider {
width: 600px;
height: 400px;
overflow: hidden;
position: relative;
}
.slide {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
transition: left 1s ease-in-out;
}
.slide img {
width: 100%;
height: 100%;
}
<script type="rocketlazyloadscript">
var current = 0,
slides = document.getElementsByClassName("slide");
function nextSlide(){
goToSlide(current+1);
}
function previousSlide(){
goToSlide(current-1);
}
function goToSlide(n){
slides[current].className = 'slide';
current = (n+slides.length)%slides.length;
slides[current].className = 'slide showing';
}
var next = document.getElementById('next');
var previous = document.getElementById('previous');
next.onclick = function(){
nextSlide();
};
previous.onclick = function(){
previousSlide();
};
</script>
<button id="previous">Previous</button>
<button id="next">Next</button>
该脚本将创建一个基本的图像滑块,允许用户使用“上一个”和“下一个”按钮浏览图像。您可以根据需要调整样式和功能。
要使用 PHP 创建动态自动图像滑块,您可以使用以下步骤:
在您的服务器上创建一个文件夹来存储您要在滑块中使用的图像。
使用 PHPscandir()函数读取文件夹的内容并将图像的文件名存储在数组中。
使用foreach循环遍历文件名数组并输出每个图像的 HTML。
使用 JavaScript 或 jQuery 创建滑块效果,例如水平滑动图像或淡入淡出。
使用 JavaScriptsetInterval()函数设置图像自动旋转的时间间隔。
下面是一个基本的 PHP 脚本示例,它将读取名为“slider”的文件夹中的所有图像并将它们输出为自动图像滑块:
<div class="slider">
<?php
$folder = 'slider/';
$files = scandir($folder);
foreach($files as $file) {
$file_parts = pathinfo($file);
if($file_parts['extension'] == 'jpg') {
echo '<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" data-lazy-src="'.$folder.$file.'" /><noscript><img decoding="async" src="'.$folder.$file.'" /></noscript>';
}
}
?>
</div>
此 JavaScript 代码创建一个自动图像滑块,setTimeout()方法是使用变量中指定的每 3 秒(3000 毫秒)更改一次图像的函数time。
它是这样工作的:
<script type="rocketlazyloadscript">
var index = 0;
var images = [];
var time = 3000;
// Image List
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
// Change Image
function changeImg(){
document.slide.src = images[index];
if(index < images.length - 1){
index++;
} else {
index = 0;
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
</script>
<img name="slide" width="600" height="400">
此脚本将每 3 秒(3000 毫秒)自动更改图像。您可以根据需要调整时间间隔。
注意:这是一个基本示例,您可能想要添加更多功能,如导航按钮、标题等。希望以上文章能帮助您了解如何使用 PHP 创建图像滑块和自动图像滑块。
文章原文出处:https: //foolishdeveloper.com/
1683198120
In this article you will know how to create Dynamic Image Slider using PHP. Earlier I have designed many image sliders using html, css, javascript, jquery etc. This is the first time I will share with you how to make image slider using PHP.
To create an image slider using PHP, you can use the following steps:
Create a folder on your server to store the images you want to use in the slider.
Use the PHP scandir()
function to read the contents of the folder and store the filenames of the images in an array.
Use a foreach
loop to iterate through the array of filenames and output the HTML for each image.
Use CSS to style the images and create a slide effect, such as using the transition
and transform
properties to slide the images horizontally or vertically.
Use JavaScript or jQuery to create the navigation buttons for the slider.
Here is an example of a basic PHP script that will read all the images in a folder called “slider” and output them as an image slider:
<div class="slider">
<?php
$folder = 'slider/';
$files = scandir($folder);
foreach($files as $file) {
$file_parts = pathinfo($file);
if($file_parts['extension'] == 'jpg') {
echo '<div class="slide">';
echo '<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" data-lazy-src="'.$folder.$file.'" /><noscript><img decoding="async" src="'.$folder.$file.'" /></noscript>';
echo '</div>';
}
}
?>
</div>
.slider {
width: 600px;
height: 400px;
overflow: hidden;
position: relative;
}
.slide {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
transition: left 1s ease-in-out;
}
.slide img {
width: 100%;
height: 100%;
}
<script type="rocketlazyloadscript">
var current = 0,
slides = document.getElementsByClassName("slide");
function nextSlide(){
goToSlide(current+1);
}
function previousSlide(){
goToSlide(current-1);
}
function goToSlide(n){
slides[current].className = 'slide';
current = (n+slides.length)%slides.length;
slides[current].className = 'slide showing';
}
var next = document.getElementById('next');
var previous = document.getElementById('previous');
next.onclick = function(){
nextSlide();
};
previous.onclick = function(){
previousSlide();
};
</script>
<button id="previous">Previous</button>
<button id="next">Next</button>
This script will create a basic image slider that allows the user to navigate through the images using the “Previous” and “Next” buttons. You can adjust the styling and functionality as per your requirement.
To create a dynamic automatic image slider using PHP, you can use the following steps:
Create a folder on your server to store the images you want to use in the slider.
Use the PHP scandir()
function to read the contents of the folder and store the filenames of the images in an array.
Use a foreach
loop to iterate through the array of filenames and output the HTML for each image.
Use JavaScript or jQuery to create the slider effect, such as sliding the images horizontally or fading them in and out.
Use the JavaScript setInterval()
function to set a timed interval for the automatic rotation of the images.
Here is an example of a basic PHP script that will read all the images in a folder called “slider” and output them as an automatic image slider:
<div class="slider">
<?php
$folder = 'slider/';
$files = scandir($folder);
foreach($files as $file) {
$file_parts = pathinfo($file);
if($file_parts['extension'] == 'jpg') {
echo '<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" data-lazy-src="'.$folder.$file.'" /><noscript><img decoding="async" src="'.$folder.$file.'" /></noscript>';
}
}
?>
</div>
This JavaScript code creates an automatic image slider by using the setTimeout()
function to change the image every 3 seconds (3000 milliseconds) as specified in the time
variable.
Here’s how it works:
index
variable keeps track of which image is currently being displayed.images
array holds the file paths for the images to be displayed in the slider.changeImg()
function is called when the page loads, and it sets the src
attribute of an img
element with the id “slide” to the current image in the images
array.if
statement increments the index
variable so that the next image in the array is displayed on the next call of the changeImg()
function, and the else
statement resets the index
variable to 0 when the last image is displayed, so the slider loops back to the first image.setTimeout()
function is used to call the changeImg()
function every 3 seconds, so the images are automatically changed every 3 seconds.<script type="rocketlazyloadscript">
var index = 0;
var images = [];
var time = 3000;
// Image List
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
// Change Image
function changeImg(){
document.slide.src = images[index];
if(index < images.length - 1){
index++;
} else {
index = 0;
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
</script>
<img name="slide" width="600" height="400">
This script will automatically change the image every 3 seconds (3000 milliseconds). You can adjust the time interval as per your requirement.
Note: This is a basic example, you may want to add some more functionality like, navigation buttons, captions, etc. Hope the above article helped you to know how to create image slider and automatic image slider with PHP.
Original article source at: https://foolishdeveloper.com/
1682423487
A Flutter package to create Material color schemes based on a platform's implementation of dynamic color. Currently supported platforms are:
@theme_selected_bg_color
This package also supports color and color scheme harmonization.
flutter pub add dynamic_color
import 'package:dynamic_color/dynamic_color.dart';
DynamicColorBuilder
is a stateful widget that provides the device's dynamic colors in a light and dark ColorScheme
.
DynamicColorBuilder(
builder: (ColorScheme? lightDynamic, ColorScheme? darkDynamic) {
return ...;
}
),
Under the hood, DynamicColorBuilder
uses a plugin to talk to the OS.
Harmonization makes adding and introducing new colors to your app more seamless by automatically shifting hue and chroma slightly so that a product's colors feel more cohesive with user colors.
This package provides two extension methods to accomplish this:
Color color = Colors.red;
// Shift's [color]'s hue towards the (dynamic) color scheme's primary color. This leaves the color recognizable while harmonizing it with a user's dynamic color.
harmonizedColor = color.harmonizeWith(colorScheme.primary);
// Does the same thing, for ColorScheme built-in semantic colors
harmonizedColorScheme = colorScheme.harmonized();
See harmonization.dart for details. Learn more about custom colors and harmonization on the Material 3 site.
See example/lib/complete_example.dart for obtaining dynamic colors, creating harmonized color schemes, and harmonizing custom colors.
See example/lib/accent_color.dart for obtaining the accent color on desktop.
All examples are part of this example app (source). To run the example app:
cd example
flutter run
import 'package:dynamic_color/test_utils.dart';
import 'package:dynamic_color/samples.dart';
void main() {
// Reset for every test
setUp(() => DynamicColorTestingUtils.setMockDynamicColors());
testWidgets('Verify dynamic core palette is used ',
(WidgetTester tester) async {
DynamicColorTestingUtils.setMockDynamicColors(
corePalette: SampleCorePalettes.green,
);
// ...
});
See example/test/widget_test.dart for an example.
The example app is hosted via GitHub pages. To update it:
cd example
flutter build web
Run this command:
With Flutter:
$ flutter pub add dynamic_color
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
dynamic_color: ^1.6.3
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:dynamic_color/dynamic_color.dart';
import 'package:flutter/material.dart';
import 'accent_color.dart';
import 'common.dart';
import 'complete_example.dart';
import 'core_palette_visualization.dart';
import 'dynamic_color_builder_example.dart';
import 'get_core_palette_example.dart';
import 'harmonization_example.dart';
void main() {
runApp(const ExampleApp());
}
class ExampleApp extends StatelessWidget {
const ExampleApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Examples')),
body: Center(
child: Container(
constraints: contentMaxWidth,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const _ExampleAppButton(
title: CompleteExample.title,
widget: CompleteExample(),
),
const Divider(),
Padding(
padding: const EdgeInsets.all(20),
child: Text(
'Advanced examples',
style: textTheme.titleMedium,
),
),
const _ExampleAppButton(
title: CorePaletteVisualization.title,
widget: CorePaletteVisualization(),
),
const _ExampleAppButton(
title: AccentColorExample.title,
widget: AccentColorExample(),
),
const _ExampleAppButton(
title: HarmonizationExample.title,
widget: HarmonizationExample(),
),
const _ExampleAppButton(
title: AdvancedExample1.title,
widget: AdvancedExample1(),
),
const _ExampleAppButton(
title: AdvancedExample2.title,
widget: AdvancedExample2(),
),
],
),
),
),
),
);
}
}
class _ExampleAppButton extends StatelessWidget {
const _ExampleAppButton({
Key? key,
required this.title,
required this.widget,
}) : super(key: key);
final String title;
final Widget widget;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(10),
child: ElevatedButton(
child: Text(title),
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Scaffold(
appBar: AppBar(
title: Text(title, style: const TextStyle(fontSize: 14)),
),
body: Padding(
padding: (title == CompleteExample.title)
? EdgeInsets.zero
: contentPadding,
child: widget),
),
),
),
),
);
}
}
Download Details:
Author: material.io
Source Code: https://github.com/material-foundation/flutter-packages/tree/main/packages/dynamic_color
1682075820
Чтобы создать объект с динамическими ключами в JavaScript, вы можете использовать функцию вычисляемых имен свойств ES6 .
Функция вычисляемых имен свойств позволяет нам назначать выражение в качестве имени свойства для объекта в литеральной нотации объекта.
Вот пример:
const key = 'title';
const value = 'JavaScript';
const course = {
[key]: value,
price: '$99'
};
console.log(course.title); // JavaScript
console.log(course.price); // $99
Значением ключа может быть любое выражение, если оно заключено в скобки [] :
const key = 'title';
const value = 'JavaScript';
const course = {
[key + '2']: value,
price: '$99'
};
console.log(course.title2); // JavaScript
console.log(course.price); // $99
Оригинальный источник статьи: https://attacomsian.com/
1682072057
要在 JavaScript 中创建具有动态键的对象,您可以使用 ES6 的计算属性名称功能。
计算属性名称功能允许我们将表达式作为属性名称分配给对象字面量表示法中的对象。
这是一个例子:
const key = 'title';
const value = 'JavaScript';
const course = {
[key]: value,
price: '$99'
};
console.log(course.title); // JavaScript
console.log(course.price); // $99
key的值可以是任何表达式,只要它被括在方括号[]中:
const key = 'title';
const value = 'JavaScript';
const course = {
[key + '2']: value,
price: '$99'
};
console.log(course.title2); // JavaScript
console.log(course.price); // $99
文章原文出处:https: //attacomsian.com/
1682050264
To create an object with dynamic keys in JavaScript, you can use ES6's computed property names feature.
The computed property names feature allows us to assign an expression as the property name to an object within object literal notation.
Here is an example:
const key = 'title';
const value = 'JavaScript';
const course = {
[key]: value,
price: '$99'
};
console.log(course.title); // JavaScript
console.log(course.price); // $99
The value of the key can be any expression as long as it is wrapped in brackets []:
const key = 'title';
const value = 'JavaScript';
const course = {
[key + '2']: value,
price: '$99'
};
console.log(course.title2); // JavaScript
console.log(course.price); // $99
Original article source at: https://attacomsian.com/
1681115123
В этом посте я покажу, как создать динамическую привязку InputRadio к Enum с помощью Blazor и с использованием языка C#, Blazor и Visual Studio Code.
В этом примере я создаю простое перечисление с двумя записями.
public enum MapInfo {
Department = 2,
City = 4
}
На этом этапе я создаю свой класс и объявляю свойство типа MapInfo.
public class MyForm {
public MapInfo mapInfo {
get;
set;
}
}
В @code я создаю экземпляр класса MyForm и объявляю массив, в котором хранятся значения перечисления.
@code {
private MyForm form = new MyForm();
private Array enumValue = Enum.GetValues(typeof(MapInfo));
}
Чтобы создать форму, управляемую Razor, я буду использовать раздел EditForm. Модели EditForm нацелены на объект «form» в моем разделе @code. Я также установлю параметр OnSubmit (обратный вызов, вызываемый при отправке формы), чтобы проверить результат.
Если вам нужна информация о Razor EditForm, я приглашаю вас посетить раздел Улучшение работы форм и проверки в веб-приложениях Blazor — Обучение | Обучение Майкрософт .
<EditForm Model="@form" OnSubmit="ValidateRequest">
<InputRadioGroup @bind-Value="form.mapInfo">
@foreach (var option in enumValue)
{
MapInfo enumInfo = (MapInfo)Enum.Parse(typeof(MapInfo), option.ToString());
<InputRadio Value="@enumInfo" /> @option
}
</InputRadioGroup>
</EditForm>
Запускайте и отлаживайте с помощью VS Code и получайте результат.
Я добавляю кнопку в HTML-раздел моей страницы бритвы, чтобы проверить свою группу InputRadio и убедиться, что моя привязка работает нормально.
<input type="submit" class="btn btn-primary" value="Request" />
Когда я нажимаю кнопку отправки, элемент управления EditForm вызывает обратный вызов метода ValidateRequest (параметра OnSubmit EditForm) в моем разделе @code.
private async Task ValidateRequest()
{
Console.WriteLine(form.mapInfo.ToString());
await JSRuntime.InvokeVoidAsync("MyJSFunction", new[] {});
}
В моей консоли отладки VSCode я вижу выбранное значение перечисления, когда нажимаю кнопку «Отправить». Мое свойство form.mapInfo хорошо обновлено. Привязка работает нормально.
Увидимся в моем следующем посте.
Оригинальный источник статьи: https://www.c-sharpcorner.com/
1681111320
在本文中,我将演示如何使用 Blazor 以及使用 C# 语言、Blazor 和 Visual Studio Code 在 Enum 上创建动态 InputRadio 绑定。
在此示例中,我创建了一个包含两个条目的简单枚举。
public enum MapInfo {
Department = 2,
City = 4
}
在这个阶段,我创建了我的类并声明了一个 MapInfo 类型的属性。
public class MyForm {
public MapInfo mapInfo {
get;
set;
}
}
在@code 中,我实例化了 MyForm 类并声明了一个数组,其中存储了我的枚举值。
@code {
private MyForm form = new MyForm();
private Array enumValue = Enum.GetValues(typeof(MapInfo));
}
要创建由 Razor 管理的表单,我将使用 EditForm 部分。EditForm 模型以我的@code 部分中的对象« form » 为目标。我还将设置 OnSubmit 参数(提交表单时调用的回调)来测试结果。
如果您想了解有关 Razor EditForm 的信息,我邀请您访问 - 改进表单和验证在 Blazor Web 应用程序中的工作方式 - 培训 | 微软学习。
<EditForm Model="@form" OnSubmit="ValidateRequest">
<InputRadioGroup @bind-Value="form.mapInfo">
@foreach (var option in enumValue)
{
MapInfo enumInfo = (MapInfo)Enum.Parse(typeof(MapInfo), option.ToString());
<InputRadio Value="@enumInfo" /> @option
}
</InputRadioGroup>
</EditForm>
使用 VS Code 和 Tada 运行并调试结果。
我在 razor 页面的 HTML 部分添加按钮来测试我的 InputRadio 组并查看我的绑定是否正常工作。
<input type="submit" class="btn btn-primary" value="Request" />
当我单击我的提交按钮时,EditForm 控件回调我的@code 部分中的 ValidateRequest 方法(EditForm 的 OnSubmit 参数)。
private async Task ValidateRequest()
{
Console.WriteLine(form.mapInfo.ToString());
await JSRuntime.InvokeVoidAsync("MyJSFunction", new[] {});
}
在我的 VSCode 调试控制台中,当我单击“提交”按钮时,我可以看到所选的枚举值。我的财产 form.mapInfo 是一个很好的更新。绑定工作正常。
在我的下一篇文章中见。
文章原文出处:https: //www.c-sharpcorner.com/
1681100594
Здесь мы увидим, как создать динамическую карту сайта в laravel. Как мы знаем, карта сайта — очень важная часть SEO, карта сайта — это список страниц веб-сайта в пределах одного домена.
Здесь мы создадим динамическую карту сайта XML в laravel. Карта сайта — это план вашего веб-сайта, который может помочь поисковым системам находить, сканировать и индексировать весь контент вашего сайта. Итак, давайте посмотрим, как создать динамическую карту сайта XML в laravel и как добавить карту сайта в ларавель,
Здесь мы используем пакет карты сайта для создания динамической карты сайта в команде laravel.run ниже в вашем терминале, чтобы установить пакет в laravel.
composer require watson/sitemap
Чтобы опубликовать файл конфигурации для пакета карты сайта, выполните приведенную ниже команду Artisan.
php artisan config:publish watson/sitemap
php artisan vendor:publish --provider="Watson\Sitemap\SitemapServiceProvider"
Здесь вам нужно добавить теги для каждого элемента в вашу карту сайта, используя Sitemap::addTag($location, $lastModified, $changeFrequency, $priority). И мы можем вернуть карту сайта с расширением Sitemap::renderSitemap(). $lastModified переменная будет проанализирована и преобразована в правильный формат для карты сайта.
Если вы хотите получить необработанный XML, просто позвоните Sitemap::xml()
Пример :
namespace App\Http\Controllers;
use Post;
use Sitemap;
class SitemapsController extends Controller
{
public function posts()
{
$posts = Post::all();
foreach ($posts as $post) {
Sitemap::addTag(route('posts.show', $post), $post->updated_at, 'daily', '0.6');
}
return Sitemap::render();
}
}
Карта сайта изображения:
Parameters : $tag->addImage($location, $caption, $geoLocation, $title, $licenceUrl);
namespace App\Http\Controllers;
use Page;
use Sitemap;
class SitemapsController extends Controller
{
public function pages()
{
$pages = Page::all();
foreach ($pages as $page) {
$tag = Sitemap::addTag(route('pages.show', $page), $page->updated_at, 'daily', '0.8');
foreach ($page->images as $image) {
$tag->addImage($image->url, $image->caption);
}
}
return Sitemap::render();
}
}
Оригинальный источник статьи: https://websolutionstuff.com/
1681096800
在这里,我们将看到如何在 Laravel 中生成动态站点地图。众所周知,站点地图是 seo 中非常重要的一部分,站点地图是单个域内网站页面的列表。
这里我们将在 laravel 中创建动态 xml 站点地图。站点地图是您网站的蓝图,可以帮助搜索引擎查找、抓取和索引您网站的所有内容所以让我们看看如何在 laravel 中创建动态 xml 站点地图以及如何在 laravel 中添加站点地图拉维尔,
在这里,我们使用站点地图包在 laravel.run 中生成动态站点地图,在终端中运行以下命令以在 laravel 中安装包。
composer require watson/sitemap
要发布站点地图包的配置文件,请运行以下 Artisan 命令。
php artisan config:publish watson/sitemap
php artisan vendor:publish --provider="Watson\Sitemap\SitemapServiceProvider"
在这里,您需要使用 为站点地图中的每个项目添加标签 Sitemap::addTag($location, $lastModified, $changeFrequency, $priority)。我们可以返回站点地图 Sitemap::renderSitemap()。$lastModified 变量将被解析并转换为站点地图的正确格式。
如果您想获取原始 XML,则只需调用 Sitemap::xml()
例子 :
namespace App\Http\Controllers;
use Post;
use Sitemap;
class SitemapsController extends Controller
{
public function posts()
{
$posts = Post::all();
foreach ($posts as $post) {
Sitemap::addTag(route('posts.show', $post), $post->updated_at, 'daily', '0.6');
}
return Sitemap::render();
}
}
图片站点地图:
Parameters : $tag->addImage($location, $caption, $geoLocation, $title, $licenceUrl);
namespace App\Http\Controllers;
use Page;
use Sitemap;
class SitemapsController extends Controller
{
public function pages()
{
$pages = Page::all();
foreach ($pages as $page) {
$tag = Sitemap::addTag(route('pages.show', $page), $page->updated_at, 'daily', '0.8');
foreach ($page->images as $image) {
$tag->addImage($image->url, $image->caption);
}
}
return Sitemap::render();
}
}
原文出处:https: //websolutionstuff.com/
1681096526
Here we will see how to generate dynamic sitemap in laravel. As we know sitemap is very important part of seo, sitemap is list of pages of a website within a single domain.
Here we will create dynamic XML sitemap in laravel.sitemap is a blueprint of your website that can help to search engines find, crawl and index all of your website's content So let's see how to create dynamic xml sitemap in laravel and how to add sitemap in laravel,
Here, we are using sitemap package for generate dynamic sitemap in laravel.run below command in your terminal to install package in laravel.
composer require watson/sitemap
To publish the configuration file for the sitemap package, run below Artisan command.
php artisan config:publish watson/sitemap
php artisan vendor:publish --provider="Watson\Sitemap\SitemapServiceProvider"
Here, you need to add tags for each item in your sitemap using Sitemap::addTag($location, $lastModified, $changeFrequency, $priority)
. And we can return the sitemap with Sitemap::renderSitemap()
. $lastModified
variable will be parsed and convered to the right format for the sitemap.
If you want to get raw XML then simply call Sitemap::xml()
Example :
namespace App\Http\Controllers;
use Post;
use Sitemap;
class SitemapsController extends Controller
{
public function posts()
{
$posts = Post::all();
foreach ($posts as $post) {
Sitemap::addTag(route('posts.show', $post), $post->updated_at, 'daily', '0.6');
}
return Sitemap::render();
}
}
Image Sitemap :
Parameters : $tag->addImage($location, $caption, $geoLocation, $title, $licenceUrl);
namespace App\Http\Controllers;
use Page;
use Sitemap;
class SitemapsController extends Controller
{
public function pages()
{
$pages = Page::all();
foreach ($pages as $page) {
$tag = Sitemap::addTag(route('pages.show', $page), $page->updated_at, 'daily', '0.8');
foreach ($page->images as $image) {
$tag->addImage($image->url, $image->caption);
}
}
return Sitemap::render();
}
}
Original article source at: https://websolutionstuff.com/
1681096511
In this post, I will demonstrate how to create dynamic InputRadio binding on Enum with Blazor and using C# language, Blazor, and Visual Studio Code.
In this sample, I create a simple enum with two entries.
public enum MapInfo {
Department = 2,
City = 4
}
In this stage, I create my class and declare a property of MapInfo type.
public class MyForm {
public MapInfo mapInfo {
get;
set;
}
}
In @code, I instantiate MyForm class and declare an array where I stock my enum values.
@code {
private MyForm form = new MyForm();
private Array enumValue = Enum.GetValues(typeof(MapInfo));
}
To create a form managed by Razor, I will use an EditForm section. The EditForm models target the object « form » in my @code section. I will also set the OnSubmit parameter (a callback invoked when the form is submitted) to test the result.
If you want information about Razor EditForm, I invite you to visit- Improve how forms and validation work in Blazor web apps - Training | Microsoft Learn.
<EditForm Model="@form" OnSubmit="ValidateRequest">
<InputRadioGroup @bind-Value="form.mapInfo">
@foreach (var option in enumValue)
{
MapInfo enumInfo = (MapInfo)Enum.Parse(typeof(MapInfo), option.ToString());
<InputRadio Value="@enumInfo" /> @option
}
</InputRadioGroup>
</EditForm>
Run and debug with VS Code and Tada the result.
I add the button in my razor page's HTML section to test my InputRadio group and to see if my binding works fine.
<input type="submit" class="btn btn-primary" value="Request" />
When I click on my submit button, the EditForm control callback the ValidateRequest method (of EditForm's OnSubmit parameter) in my @code section.
private async Task ValidateRequest()
{
Console.WriteLine(form.mapInfo.ToString());
await JSRuntime.InvokeVoidAsync("MyJSFunction", new[] {});
}
In my VSCode Debug Console, I can see the enum value selected when I click the Submit button. My property form.mapInfo is a well update. The binding works fine.
See you in my next post.
Original article source at: https://www.c-sharpcorner.com/