Monty  Boehm

Monty Boehm

1685375160

React.dev: The React Documentation Website

React.dev

This repo contains the source code and documentation powering react.dev.

Getting started

Prerequisites

  1. Git
  2. Node: any 12.x version starting with v12.0.0 or greater
  3. Yarn: See Yarn website for installation instructions
  4. A fork of the repo (for any contributions)
  5. A clone of the react.dev repo on your local machine

Installation

  1. cd react.dev to go into the project root
  2. yarn to install the website's npm dependencies

Running locally

  1. yarn dev to start the development server (powered by Next.js)
  2. open http://localhost:3000 to open the site in your favorite browser

Contributing

Guidelines

The documentation is divided into several sections with a different tone and purpose. If you plan to write more than a few sentences, you might find it helpful to get familiar with the contributing guidelines for the appropriate sections.

Create a branch

  1. git checkout main from any folder in your local react.dev repository
  2. git pull origin main to ensure you have the latest main code
  3. git checkout -b the-name-of-my-branch (replacing the-name-of-my-branch with a suitable name) to create a branch

Make the change

  1. Follow the "Running locally" instructions
  2. Save the files and check in the browser
  3. Changes to React components in src will hot-reload
  4. Changes to markdown files in content will hot-reload
  5. If working with plugins, you may need to remove the .cache directory and restart the server

Test the change

  1. If possible, test any visual changes in all latest versions of common browsers, on both desktop and mobile.
  2. Run yarn check-all. (This will run Prettier, ESLint and validate types.)

Push it

  1. git add -A && git commit -m "My message" (replacing My message with a commit message, such as Fix header logo on Android) to stage and commit your changes
  2. git push my-fork-name the-name-of-my-branch
  3. Go to the react.dev repo and you should see recently pushed branches.
  4. Follow GitHub's instructions.
  5. If possible, include screenshots of visual changes. A preview build is triggered after your changes are pushed to GitHub.

Translation

If you are interested in translating react.dev, please see the current translation efforts here.


Download Details:

Author: Reactjs
Source Code: https://github.com/reactjs/react.dev 
License: CC-BY-4.0 license

#react #javascript #website #documentation 

React.dev: The React Documentation Website
Web Monster

Web Monster

1683823354

How To Create Website Using HTML & CSS & JS | Full Responsive Website

Learn how to create a completely responsive website using HTML, CSS, and javascript. This is a step-by-step beginner web development project tutorial on how to build a modernwebsite using html5, css3, and javascript. 

🔔 Subscribe for more! 

https://bit.ly/3UbNw7F

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

💙 Get template by PayPal 

https://ko-fi.com/s/985908ce63

🔗 Source code 

https://ko-fi.com/s/985908ce63

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

🔥 Follow me! Facebook 

https://bit.ly/3IMfk04

Instagram 

https://bit.ly/3GHoQyT

Twitter 

https://bit.ly/3IOBEqc

Linkedin 

https://bit.ly/3INnwNY

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

☕️ Support me 

buymeacoffee.com/webmonster

💙 Support me by PayPal 

https://ko-fi.com/webmonster01

 👍 Thanks for watching, I appreciate it Made with ❤ by Web Monster 

Tags: #responsivewebsite #website #htmlcssjs #webmonster #html #css #javascript #webdesign #website #react #bootstrap 

 

➤ Link of The Video :

➤https://youtu.be/Uxbh12inqKg
 

How To Create Website Using HTML & CSS & JS | Full Responsive Website
Royce  Reinger

Royce Reinger

1683130398

Traingenerator: A Web App to Generate Template Code for ML

Traingenerator

🧙  A web app to generate template code for machine learning ✨

demo.gif
 

Generate custom template code for PyTorch & sklearn, using a simple web UI built with streamlit. Traingenerator offers multiple options for preprocessing, model setup, training, and visualization (using Tensorboard or comet.ml). It exports to .py, Jupyter Notebook, or Google Colab. The perfect tool to jumpstart your next machine learning project!

For updates, follow me on Twitter.


Adding new templates

You can add your own template in 4 easy steps (see below), without changing any code in the app itself. Your new template will be automatically discovered by Traingenerator and shown in the sidebar. That's it! 🎈

Want to share your magic? 🧙 PRs are welcome! Please have a look at CONTRIBUTING.md.

Some ideas for new templates: Keras/Tensorflow, Pytorch Lightning, object detection, segmentation, text classification, ...

  1. Create a folder under ./templates. The folder name should be the task that your template solves (e.g. Image classification). Optionally, you can add a framework name (e.g. Image classification_PyTorch). Both names are automatically shown in the first two dropdowns in the sidebar (see image). ✨ Tip: Copy the example template to get started more quickly.
  2. Add a file sidebar.py to the folder (see example). It needs to contain a method show(), which displays all template-specific streamlit components in the sidebar (i.e. everything below Task) and returns a dictionary of user inputs.
  3. Add a file code-template.py.jinja to the folder (see example). This Jinja2 template is used to generate the code. You can write normal Python code in it and modify it (through Jinja) based on the user inputs in the sidebar (e.g. insert a parameter value from the sidebar or show different code parts based on the user's selection).
  4. Optional: Add a file test-inputs.yml to the folder (see example). This simple YAML file should define a few possible user inputs that can be used for testing. If you run pytest (see below), it will automatically pick up this file, render the code template with its values, and check that the generated code runs without errors. This file is optional – but it's required if you want to contribute your template to this repo.

Installation

Note: You only need to install Traingenerator if you want to contribute or run it locally. If you just want to use it, go here.

git clone https://github.com/jrieke/traingenerator.git
cd traingenerator
pip install -r requirements.txt

Optional: For the "Open in Colab" button to work you need to set up a Github repo where the notebook files can be stored (Colab can only open public files if they are on Github). After setting up the repo, create a file .env with content:

GITHUB_TOKEN=<your-github-access-token>
REPO_NAME=<user/notebooks-repo>

If you don't set this up, the app will still work but the "Open in Colab" button will only show an error message.

Running locally

streamlit run app/main.py

Make sure to run always from the traingenerator dir (not from the app dir), otherwise the app will not be able to find the templates.

Deploying to Heroku

First, install heroku and login. To create a new deployment, run inside traingenerator:

heroku create
git push heroku main
heroku open

To update the deployed app, commit your changes and run:

git push heroku main

Optional: If you set up a Github repo to enable the "Open in Colab" button (see above), you also need to run:

heroku config:set GITHUB_TOKEN=<your-github-access-token>
heroku config:set REPO_NAME=<user/notebooks-repo>

Testing

First, install pytest and required plugins via:

pip install -r requirements-dev.txt

To run all tests:

pytest ./tests

Note that this only tests the code templates (i.e. it renders them with different input values and makes sure that the code executes without error). The streamlit app itself is not tested at the moment.

You can also test an individual template by passing the name of the template dir to --template, e.g.:

pytest ./tests --template "Image classification_scikit-learn"

The mage image used in Traingenerator is from Twitter's Twemoji library and released under Creative Commons Attribution 4.0 International Public License.


Download Details:

Author: jrieke
Source Code: https://github.com/jrieke/traingenerator 
License: MIT license

#machinelearning #python #template #website #deeplearning #tensorflow 

Traingenerator: A Web App to Generate Template Code for ML
Bongani  Ngema

Bongani Ngema

1682609520

How to Test your Drupal website with Cypress

Testing makes everything better. Learn how to use Cypress for your Drupal website.

If you don't include tests in your Drupal development, chances are it's because you think it adds complexity and expense without benefit. Cypress is an open source tool with many benefits:

  • Reliably tests anything that runs in a web browser
  • Works on any web platform (it's great for testing projects using front-end technologies like React)
  • Highly extensible
  • Increasingly popular
  • Easy to learn and implement
  • Protects against regression as your projects become more complex
  • Can make your development process more efficient

This article covers three topics to help you start testing your Drupal project using Cypress:

  1. Installing Cypress
  2. Writing and running basic tests using Cypress
  3. Customizing Cypress for Drupal

Install Cypress

For the purposes of this tutorial I'm assuming that you have built a local dev environment for your Drupal project using the `drupal/recommended-project` project. Although details on creating such a project are outside of the scope of this piece, I recommend Getting Started with Lando and Drupal 9.

Your project has at least this basic structure:

vendor/
web/
.editorconfig
.gitattributes
composer.json
composer.lock

The cypress.io site has complete installation instructions for various environments. For this article, I installed Cypress using npm.

Initialize your project using the command npm init. Answer the questions that Node.js asks you, and then you will have a package.json file that looks something like this:

{
  "name": "cypress",
  "version": "1.0.0",
  "description": "Installs Cypress in a test project.",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Install Cypress in your project:

$ npm install cypress --save-dev

Run Cypress for the first time:

$ npx cypress open

Because you haven't added a config or any scaffolding files to Cypress, the Cypress app displays the welcome screen to help you configure the project. To configure your project for E2E (end-to-end) testing, click the Not Configured button for E2E Testing. Cypress adds some files to your project:

cypress/
node_modules/
vendor/ 
web/
.editorconfig
.gitattributes
composer.json
composer.lock
cypress.config.js
package-lock.json
package.json

Click Continue and choose your preferred browser for testing. Click Start E2E Testing in [your browser of choice]. I'm using a Chromium-based browser for this article.

In a separate window, a browser opens to the Create your first spec page:

Cypress in a web browser

(Jordan Graham, CC BY-SA 4.0)

Click on the Scaffold example specs button to create a couple of new folders with example specs to help you understand how to use Cypress. Read through these in your code editor, and you'll likely find the language (based on JavaScript) intuitive and easy to follow.

Click on any in the test browser. This reveals two panels. On the left, a text panel shows each step in the active spec. On the right, a simulated browser window shows the actual user experience as Cypress steps through the spec.

Open the cypress.config.js file in your project root and change it as follows:

const { defineConfig } = require("cypress");
 
module.exports = defineConfig({
  component: {
    fixturesFolder: "cypress/fixtures",
    integrationFolder: "cypress/integration",
    pluginsFile: "cypress/plugins/index.js",
    screenshotsFolder: "cypress/screenshots",
    supportFile: "cypress/support/e2e.js",
    videosFolder: "cypress/videos",
    viewportWidth: 1440,
    viewportHeight: 900,
  },

  e2e: {
    setupNodeEvents(on, config) {
      // implement node event listeners here
    },
    baseUrl: "https://[your-local-dev-url]",
    specPattern: "cypress/**/*.{js,jsx,ts,tsx}",
    supportFile: "cypress/support/e2e.js",
    fixturesFolder: "cypress/fixtures"
   },
 });

Change the baseUrl to your project's URL in your local dev environment.

These changes tell Cypress where to find its resources and how to find all of the specs in your project.

Write and run basic tests using Cypress

Create a new directory called integration in your /cypress directory. Within the integration directory, create a file called test.cy.js:

cypress/
├─ e2e/
├─ fixtures/
├─ integration/ 
│  ├─ test.cy.js
├─ support/ 
node_modules/
vendor/
web/
.editorconfig
.gitattributes
composer.json
composer.lock
cypress.config.js
package-lock.json
package.json

Add the following contents to your test.cy.js file:

describe('Loads the front page', () => {
  it('Loads the front page', () => {
    cy.visit('/')
    cy.get('h1.page-title')
      .should('exist')
  });
});
 
describe('Tests logging in using an incorrect password', () => {
  it('Fails authentication using incorrect login credentials', () => {
    cy.visit('/user/login')
    cy.get('#edit-name')
      .type('Sir Lancelot of Camelot')
    cy.get('#edit-pass')
      .type('tacos')
    cy.get('input#edit-submit')
      .contains('Log in')
      .click()
    cy.contains('Unrecognized username or password.')
  });
});

When you click on test.cy.js in the Cypress application, watch each test description on the left as Cypress performs the steps in each describe() section.

This spec demonstrates how to tell Cypress to navigate your website, access HTML elements by ID, enter content into input elements, and submit the form. This process is how I discovered that I needed to add the assertion that the <input id="edit-submit"> element contains the text Log in before the input was clickable. Apparently, the flex styling of the submit input impeded Cypress' ability to "see" the input, so it couldn't click on it. Testing really works!

Customize Cypress for Drupal

You can write your own custom Cypress commands, too. Remember the supportFile entry in the cypress.config.js file? It points to a file that Cypress added, which in turn imports the ./commands files. Incidentally, Cypress is so clever that when importing logic or data fixtures, you don't need to specify the file extension, so you import ./commands, not ./commands.js. Cypress looks for any of a dozen or so popular file extensions and understands how to recognize and parse each of them.

Enter commands into commands.js to define them:

/**
 * Logs out the user.
 */
 
Cypress.Commands.add('drupalLogout', () => {
  cy.visit('/user/logout');
})
 
/**
 * Basic user login command. Requires valid username and password.
 *
 * @param {string} username
 *   The username with which to log in.
 * @param {string} password
 *   The password for the user's account.
 */
 
Cypress.Commands.add('loginAs', (username, password) => {
  cy.drupalLogout();
  cy.visit('/user/login');
  cy.get('#edit-name')
    .type(username);
  cy.get('#edit-pass').type(password, {
    log: false,
  });
 
  cy.get('#edit-submit').contains('Log in').click();
});

This example defines a custom Cypress command called drupalLogout(), which you can use in any subsequent logic, even other custom commands. To log a user out, call cy.drupalLogout(). This is the first event in the custom command loginAs to ensure that Cypress is logged out before attempting to log in as a specific user.

Using environment variables, you can even create a Cypress command called drush(), which you can use to execute Drush commands in your tests or custom commands. Look at how simple this makes it to define a custom Cypress command that logs a user in using their UID:

/**
* Logs a user in by their uid via drush uli.
*/
 
Cypress.Commands.add('loginUserByUid', (uid) => {
 cy.drush('user-login', [], { uid, uri: Cypress.env('baseUrl') })
   .its('stdout')
   .then(function (url) {
     cy.visit(url);
   });
});

This example uses the drush user-login command (drush uli for short) and takes the authenticated user to the site's base URL.

Consider the security benefit of never reading or storing user passwords in your testing. Personally, I find it amazing that a front-end technology like Cypress can execute Drush commands, which I've always thought of as being very much on the back end.

Testing, testing

There's a lot more to Cypress, like fixtures (files that hold test data) and various tricks for navigating the sometimes complex data structures that produce a website's user interface. For a look into what's possible, watch the Cypress Testing for Drupal Websites webinar, particularly the section on fixtures that begins at 18:33. That webinar goes into greater detail about some interesting use cases, including an Ajax-enabled form. Once you start using it, feel free to use or fork Aten's public repository of Cypress Testing for Drupal.

Happy testing!

Original article source at: https://opensource.com/

#cypress #test #drupal #website 

How to Test your Drupal website with Cypress

Как протестировать свой сайт на Drupal с помощью Cypress

Тестирование делает все лучше. Узнайте, как использовать Cypress для вашего сайта на Drupal.

Если вы не включаете тесты в свою разработку Drupal, скорее всего, это потому, что вы думаете, что это усложняет и увеличивает расходы без пользы. Cypress — это инструмент с открытым исходным кодом, обладающий множеством преимуществ:

  • Надежно тестирует все, что работает в веб-браузере
  • Работает на любой веб-платформе (отлично подходит для тестирования проектов с использованием передовых технологий, таких как React ) .
  • Расширяемый
  • все более популярным
  • Простота в освоении и реализации
  • Защищает от регрессии по мере усложнения ваших проектов
  • Может сделать ваш процесс разработки более эффективным

В этой статье рассматриваются три темы, которые помогут вам начать тестирование вашего проекта Drupal с помощью Cypress:

  1. Установка Кипариса
  2. Написание и запуск базовых тестов с помощью Cypress
  3. Настройка Cypress для Drupal

Установить Кипарис

Для целей этого руководства я предполагаю, что вы создали локальную среду разработки для своего проекта Drupal, используя проект `drupal/recommended-project`. Хотя подробности создания такого проекта выходят за рамки этой статьи, я рекомендую  Начало работы с Lando и Drupal 9 .

Ваш проект имеет по крайней мере эту базовую структуру:

vendor/
web/
.editorconfig
.gitattributes
composer.json
composer.lock

На сайте cypress.io есть полные инструкции по установке для различных сред. Для этой статьи я установил Cypress с помощью npm .

Инициализируйте свой проект с помощью команды npm init. Ответьте на вопросы, которые задает вам Node.js, и тогда у вас будет файл package.json, который выглядит примерно так:

{
  "name": "cypress",
  "version": "1.0.0",
  "description": "Installs Cypress in a test project.",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Установите Cypress в свой проект:

$ npm install cypress --save-dev

Запустите Cypress в первый раз:

$ npx cypress open

Поскольку вы не добавили конфигурацию или какие-либо файлы поддержки в Cypress, приложение Cypress отображает экран приветствия, чтобы помочь вам настроить проект. Чтобы настроить проект для E2E (сквозного) тестирования, нажмите кнопку «Не настроено» для E2E-тестирования. Cypress добавляет в ваш проект несколько файлов:

cypress/
node_modules/
vendor/ 
web/
.editorconfig
.gitattributes
composer.json
composer.lock
cypress.config.js
package-lock.json
package.json

Нажмите «Продолжить» и выберите предпочитаемый браузер для тестирования. Нажмите «Начать E2E-тестирование» в [выбранном вами браузере] . Для этой статьи я использую браузер на основе Chromium.

В отдельном окне браузер откроет страницу Create your first spec :

Кипарис в веб-браузере

(Джордан Грэм, CC BY-SA 4.0)

Нажмите на кнопку примеров спецификаций Scaffold , чтобы создать пару новых папок с примерами спецификаций, которые помогут вам понять, как использовать Cypress. Прочтите их в своем редакторе кода, и вы, вероятно, обнаружите, что язык (основанный на JavaScript) интуитивно понятен и прост в использовании.

Нажмите на любой в тестовом браузере. Это показывает две панели. Слева текстовая панель показывает каждый шаг активной спецификации. Справа смоделированное окно браузера показывает реальный пользовательский опыт, когда Cypress проходит через спецификацию.

Откройте cypress.config.jsфайл в корне вашего проекта и измените его следующим образом:

const { defineConfig } = require("cypress");
 
module.exports = defineConfig({
  component: {
    fixturesFolder: "cypress/fixtures",
    integrationFolder: "cypress/integration",
    pluginsFile: "cypress/plugins/index.js",
    screenshotsFolder: "cypress/screenshots",
    supportFile: "cypress/support/e2e.js",
    videosFolder: "cypress/videos",
    viewportWidth: 1440,
    viewportHeight: 900,
  },

  e2e: {
    setupNodeEvents(on, config) {
      // implement node event listeners here
    },
    baseUrl: "https://[your-local-dev-url]",
    specPattern: "cypress/**/*.{js,jsx,ts,tsx}",
    supportFile: "cypress/support/e2e.js",
    fixturesFolder: "cypress/fixtures"
   },
 });

Измените baseUrlURL-адрес вашего проекта в локальной среде разработки.

Эти изменения сообщают Cypress, где найти свои ресурсы и как найти все спецификации в вашем проекте.

Пишите и запускайте базовые тесты с помощью Cypress.

Создайте новый каталог с именем integrationв вашем /cypressкаталоге. В integrationкаталоге создайте файл с именем test.cy.js:

cypress/
├─ e2e/
├─ fixtures/
├─ integration/ 
│  ├─ test.cy.js
├─ support/ 
node_modules/
vendor/
web/
.editorconfig
.gitattributes
composer.json
composer.lock
cypress.config.js
package-lock.json
package.json

Добавьте в файл следующее содержимое test.cy.js:

describe('Loads the front page', () => {
  it('Loads the front page', () => {
    cy.visit('/')
    cy.get('h1.page-title')
      .should('exist')
  });
});
 
describe('Tests logging in using an incorrect password', () => {
  it('Fails authentication using incorrect login credentials', () => {
    cy.visit('/user/login')
    cy.get('#edit-name')
      .type('Sir Lancelot of Camelot')
    cy.get('#edit-pass')
      .type('tacos')
    cy.get('input#edit-submit')
      .contains('Log in')
      .click()
    cy.contains('Unrecognized username or password.')
  });
});

Когда вы нажимаете test.cy.jsв приложении Cypress, смотрите описание каждого теста слева, поскольку Cypress выполняет шаги в каждом describe()разделе.

Эта спецификация демонстрирует, как заставить Cypress перемещаться по вашему веб-сайту, получать доступ к элементам HTML по идентификатору, вводить содержимое в элементы ввода и отправлять форму. Именно в этом процессе я обнаружил, что мне нужно добавить утверждение, что элемент <input id="edit-submit">содержит текст «Войти» , прежде чем ввод будет доступен для клика. По-видимому, гибкий стиль ввода для отправки мешал Cypress «видеть» ввод, поэтому он не мог щелкнуть по нему. Тестирование действительно работает!

Настроить Cypress для Drupal

Вы также можете написать свои собственные команды Cypress. Помните supportFileзапись в cypress.config.jsфайле? Он указывает на файл, добавленный Cypress, который, в свою очередь, импортирует файлы ./commands. Кстати, Cypress настолько умен, что при импорте логики или фикстур данных вам не нужно указывать расширение файла, поэтому вы импортируете ./commands, а не ./commands.js. Cypress ищет любое из дюжины или около того популярных расширений файлов и понимает, как распознавать и анализировать каждое из них.

Введите команды, commands.jsчтобы определить их:

/**
 * Logs out the user.
 */
 
Cypress.Commands.add('drupalLogout', () => {
  cy.visit('/user/logout');
})
 
/**
 * Basic user login command. Requires valid username and password.
 *
 * @param {string} username
 *   The username with which to log in.
 * @param {string} password
 *   The password for the user's account.
 */
 
Cypress.Commands.add('loginAs', (username, password) => {
  cy.drupalLogout();
  cy.visit('/user/login');
  cy.get('#edit-name')
    .type(username);
  cy.get('#edit-pass').type(password, {
    log: false,
  });
 
  cy.get('#edit-submit').contains('Log in').click();
});

В этом примере определяется пользовательская команда Cypress с именем drupalLogout(), которую вы можете использовать в любой последующей логике, даже в других пользовательских командах. Чтобы выйти из системы, вызовите cy.drupalLogout(). Это первое событие в пользовательской команде loginAs, гарантирующее, что Cypress вышел из системы, прежде чем пытаться войти в систему как конкретный пользователь.

Используя переменные среды, вы даже можете создать команду Cypress с именем drush(), которую вы можете использовать для выполнения команд Drush в своих тестах или пользовательских командах. Посмотрите, как просто это позволяет определить пользовательскую команду Cypress, которая регистрирует пользователя, используя его UID:

/**
* Logs a user in by their uid via drush uli.
*/
 
Cypress.Commands.add('loginUserByUid', (uid) => {
 cy.drush('user-login', [], { uid, uri: Cypress.env('baseUrl') })
   .its('stdout')
   .then(function (url) {
     cy.visit(url);
   });
});

В этом примере используется drush user-loginкоманда ( drush uliдля краткости) и переводит аутентифицированного пользователя на базовый URL-адрес сайта.

Учитывайте преимущество безопасности, заключающееся в том, что вы никогда не читаете и не храните пароли пользователей при тестировании. Лично я нахожу удивительным, что интерфейсная технология, такая как Cypress, может выполнять команды Drush, которые я всегда считал очень важными для серверной части.

Тестирование, тестирование

В Cypress есть намного больше, например, фикстуры (файлы, содержащие тестовые данные) и различные приемы для навигации по иногда сложным структурам данных, которые создают пользовательский интерфейс веб-сайта. Чтобы узнать, что возможно, посмотрите веб-семинар Cypress Testing for Drupal Websites , особенно раздел о фикстурах, который начинается в 18:33 . На этом вебинаре более подробно рассматриваются некоторые интересные варианты использования, в том числе форма с поддержкой Ajax. Как только вы начнете использовать его, не стесняйтесь использовать или разветвлять публичный репозиторий Cypress Testing for Drupal от Aten .

Удачного тестирования!

Оригинальный источник статьи: https://opensource.com/

#cypress #test #drupal #website 

Как протестировать свой сайт на Drupal с помощью Cypress
木村  直子

木村 直子

1682570100

如何使用 Cypress 测试您的 Drupal 网站

测试让一切变得更好。了解如何将 Cypress 用于您的 Drupal 网站。

如果您不在 Drupal 开发中包含测试,很可能是因为您认为它增加了复杂性和费用而没有好处。Cypress是一种开源工具,具有许多优点:

  • 可靠地测试在网络浏览器中运行的任何东西
  • 适用于任何网络平台(非常适合使用React等前端技术测试项目)
  • 高度可扩展
  • 越来越受欢迎
  • 易于学习和实施
  • 随着您的项目变得更加复杂,防止回归
  • 可以让你的开发过程更有效率

本文涵盖三个主题,可帮助您开始使用 Cypress 测试您的 Drupal 项目:

  1. 安装赛普拉斯
  2. 使用 Cypress 编写和运行基本测试
  3. 为 Drupal 定制赛普拉斯

安装赛普拉斯

出于本教程的目的,我假设您已经使用 `drupal/recommended-project` 项目为您的 Drupal 项目构建了一个本地开发环境。虽然创建此类项目的详细信息超出了本文的范围,但我建议 使用 Lando 和 Drupal 9 入门

您的项目至少具有以下基本结构:

vendor/
web/
.editorconfig
.gitattributes
composer.json
composer.lock

cypress.io 站点有针对各种环境的完整安装说明。对于本文,我使用npm安装了 Cypress 。

使用命令初始化您的项目npm init。回答 Node.js 问你的问题,然后你会得到一个package.json看起来像这样的文件:

{
  "name": "cypress",
  "version": "1.0.0",
  "description": "Installs Cypress in a test project.",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

在您的项目中安装 Cypress:

$ npm install cypress --save-dev

第一次运行 Cypress:

$ npx cypress open

由于您尚未向 Cypress 添加配置或任何脚手架文件,因此 Cypress 应用程序会显示欢迎屏幕以帮助您配置项目。要为 E2E(端到端)测试配置您的项目,请单击E2E 测试的未配置按钮。赛普拉斯将一些文件添加到您的项目中:

cypress/
node_modules/
vendor/ 
web/
.editorconfig
.gitattributes
composer.json
composer.lock
cypress.config.js
package-lock.json
package.json

单击继续并选择您喜欢的浏览器进行测试。单击[您选择的浏览器] 中的 Start E2E Testing。我在本文中使用基于 Chromium 的浏览器。

在一个单独的窗口中,浏览器打开到创建您的第一个规范页面:

网络浏览器中的赛普拉斯

(乔丹格雷厄姆,CC BY-SA 4.0)

单击Scaffold example specs按钮创建几个包含示例规范的新文件夹,以帮助您了解如何使用 Cypress。在您的代码编辑器中通读这些内容,您可能会发现该语言(基于 JavaScript)直观且易于理解。

单击测试浏览器中的任何一个。这揭示了两个面板。在左侧,文本面板显示了活动规范中的每个步骤。在右侧,一个模拟的浏览器窗口显示了赛普拉斯逐步执行规范时的实际用户体验。

打开cypress.config.js项目根目录中的文件并按如下方式更改它:

const { defineConfig } = require("cypress");
 
module.exports = defineConfig({
  component: {
    fixturesFolder: "cypress/fixtures",
    integrationFolder: "cypress/integration",
    pluginsFile: "cypress/plugins/index.js",
    screenshotsFolder: "cypress/screenshots",
    supportFile: "cypress/support/e2e.js",
    videosFolder: "cypress/videos",
    viewportWidth: 1440,
    viewportHeight: 900,
  },

  e2e: {
    setupNodeEvents(on, config) {
      // implement node event listeners here
    },
    baseUrl: "https://[your-local-dev-url]",
    specPattern: "cypress/**/*.{js,jsx,ts,tsx}",
    supportFile: "cypress/support/e2e.js",
    fixturesFolder: "cypress/fixtures"
   },
 });

在本地开发环境中将更改baseUrl为项目的 URL。

这些更改告诉赛普拉斯在哪里可以找到它的资源以及如何找到项目中的所有规范。

使用 Cypress 编写和运行基本测试

integration在您的目录中创建一个名为的新目录/cypress。在integration目录中,创建一个名为的文件test.cy.js

cypress/
├─ e2e/
├─ fixtures/
├─ integration/ 
│  ├─ test.cy.js
├─ support/ 
node_modules/
vendor/
web/
.editorconfig
.gitattributes
composer.json
composer.lock
cypress.config.js
package-lock.json
package.json

将以下内容添加到您的test.cy.js文件中:

describe('Loads the front page', () => {
  it('Loads the front page', () => {
    cy.visit('/')
    cy.get('h1.page-title')
      .should('exist')
  });
});
 
describe('Tests logging in using an incorrect password', () => {
  it('Fails authentication using incorrect login credentials', () => {
    cy.visit('/user/login')
    cy.get('#edit-name')
      .type('Sir Lancelot of Camelot')
    cy.get('#edit-pass')
      .type('tacos')
    cy.get('input#edit-submit')
      .contains('Log in')
      .click()
    cy.contains('Unrecognized username or password.')
  });
});

当您在 Cypress 应用程序中单击时,在 Cypress 执行每个部分test.cy.js中的步骤时,请注意左侧的每个测试描述。describe()

本规范演示了如何让 Cypress 导航您的网站、通过 ID 访问 HTML 元素、将内容输入到输入元素中以及提交表单。在这个过程中,我发现我需要添加断言,即元素<input id="edit-submit">包含文本Log in before input was clickable。显然,提交输入的灵活样式阻碍了赛普拉斯“看到”输入的能力,因此它无法点击它。测试确实有效!

为 Drupal 定制赛普拉斯

您也可以编写自己的自定义 Cypress 命令。还记得文件supportFile中的条目cypress.config.js吗?它指向赛普拉斯添加的文件,后者又导入文件./commands。顺便说一下,Cypress 非常聪明,在导入逻辑或数据夹具时,您不需要指定文件扩展名,所以您导入的是./commands,而不是./commands.js. 赛普拉斯寻找十几个流行的文件扩展名中的任何一个,并了解如何识别和解析它们中的每一个。

输入命令来commands.js定义它们:

/**
 * Logs out the user.
 */
 
Cypress.Commands.add('drupalLogout', () => {
  cy.visit('/user/logout');
})
 
/**
 * Basic user login command. Requires valid username and password.
 *
 * @param {string} username
 *   The username with which to log in.
 * @param {string} password
 *   The password for the user's account.
 */
 
Cypress.Commands.add('loginAs', (username, password) => {
  cy.drupalLogout();
  cy.visit('/user/login');
  cy.get('#edit-name')
    .type(username);
  cy.get('#edit-pass').type(password, {
    log: false,
  });
 
  cy.get('#edit-submit').contains('Log in').click();
});

此示例定义了一个名为 的自定义 Cypress 命令drupalLogout(),您可以在任何后续逻辑中使用它,甚至可以在其他自定义命令中使用它。要注销用户,请调用cy.drupalLogout()。这是自定义命令中的第一个事件,loginAs用于确保在尝试以特定用户身份登录之前注销 Cypress。

使用环境变量,您甚至可以创建一个名为 的 Cypress 命令drush(),您可以使用它在您的测试或自定义命令中执行 Drush 命令。看看这使得定义一个自定义 Cypress 命令来记录用户使用他们的 UID 是多么简单:

/**
* Logs a user in by their uid via drush uli.
*/
 
Cypress.Commands.add('loginUserByUid', (uid) => {
 cy.drush('user-login', [], { uid, uri: Cypress.env('baseUrl') })
   .its('stdout')
   .then(function (url) {
     cy.visit(url);
   });
});

此示例使用drush user-login命令(drush uli简称)并将经过身份验证的用户带到站点的基本 URL。

考虑在测试中从不读取或存储用户密码的安全优势。就个人而言,我觉得像 Cypress 这样的前端技术可以执行 Drush 命令真是太神奇了,我一直认为这在后端非常重要。

测试,测试

Cypress 还有很多其他功能,例如固定装置(保存测试数据的文件)和用于导航生成网站用户界面的有时复杂的数据结构的各种技巧。要了解可能性,请观看Cypress Testing for Drupal Websites网络研讨会,特别是 18:33 开始的关于固定装置的部分。该网络研讨会更详细地介绍了一些有趣的用例,包括支持 Ajax 的表单。一旦开始使用它,请随意使用或分叉Aten 的 Cypress Testing for Drupal 公共存储库

测试愉快!

文章原文出处:https: //opensource.com/

#cypress #test #drupal #website 

如何使用 Cypress 测试您的 Drupal 网站
Monty  Boehm

Monty Boehm

1682040300

Flask-matomo: Track requests to your Flask website with Matomo

Flask-Matomo

Flask-Matomo is a library which lets you track the requests of your Flask website using Matomo (Piwik).

Installation

pip install flask-matomo

Usage

from flask import Flask, render_template
from flask_matomo import *

app = Flask(__name__)
matomo = Matomo(app, matomo_url="https://matomo.mydomain.com",
                id_site=5, token_auth="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")

@app.route("/")
def index():
  return render_template("index.html")

if __name__ == "__main__":
  app.run()

In the code above:

  1. The Matomo object is created by passing in the Flask application and arguments to configure Matomo.
  2. The matomo_url parameter is the url to your Matomo installation.
  3. The id_site parameter is the id of your site. This is used if you track several websites with on Matomo installation. It can be found if you open your Matomo dashboard, change to site you want to track and look for &idSite= in the url.
  4. The token_auth parameter can be found in the area API in the settings of Matomo. It is required for tracking the ip address.

Meta

Lucas Hild - https://lucas-hild.de


Download Details:

Author: LucasHild
Source Code: https://github.com/LucasHild/flask-matomo 
License: MIT license

#flask #website #track 

Flask-matomo: Track requests to your Flask website with Matomo
Web Monster

Web Monster

1680451850

Build a Responsive Admin Dashboard Using HTML CSS & JS & Bootstrap

Every web developer needs to build a Admin Dashboard Application. Learn how to create the best and most modern one simply by watching this course. This Admin Panel includes one Dashboard, Three Pages, Four Apps, and Seven fully functional charts!

 


🔔 Subscribe for more! 

https://bit.ly/3UbNw7F

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

❤ Get template 

https://www.buymeacoffee.com/webmonster/e/127536

💙 Get template by PayPal 

https://ko-fi.com/s/d373f647c5

🔗 Source code 

https://www.buymeacoffee.com/webmonster/e/127536

https://ko-fi.com/s/d373f647c5

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

🔥 Follow me! 

Facebook https://bit.ly/3IMfk04

Instagram https://bit.ly/3GHoQyT

Twitter https://bit.ly/3IOBEqc

Linkedin https://bit.ly/3INnwNY

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

☕️ Support me 

buymeacoffee.com/webmonster 

💙 Support me by PayPal 

https://ko-fi.com/webmonster01 

👍 Thanks for watching, I appreciate it Made with ❤ by Web Monster 

Tags: #responsivedashboard #dashboard #htmlcssjs #webmonster #html #css #javascript #webdesign #website #react #bootstrap

 

➤Link of The Video => https://youtu.be/-8I-r6_TSvs 

Build a Responsive Admin Dashboard Using HTML CSS & JS & Bootstrap

Как анимировать контент сайта с помощью JavaScript и CSS

В этой статье объясняется, как добавить визуальные эффекты или анимацию к содержимому вашего веб-сайта всего с помощью 5 строк JavaScript и нескольких строк CSS😎.

Как мы все знаем, добавление визуальных эффектов на веб-страницы улучшает красоту сайта и повышает уровень интереса к вашему сайту.

Начало🎉

Первое , что нам нужно, это HTML-код того, что мы хотим анимировать. Убедитесь, что вы добавили атрибут класса , чтобы мы могли выбрать его в нашем коде JS.
Для этой статьи я бы использовал это

    <div class="main">
        <h1>This is the title of this div</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>

Примечание. Этот код имеет класс main.

Во-вторых , я бы придал ему немного стиля, чтобы он выглядел организованно.

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body{
    font-family: sans-serif;
    display: flex;
    justify-content: center;
    align-content: center;
}

.main{
    height: 380px;
    width: 400px;
    box-shadow: 0 0 20px 1px rgba(0,0,0,0.19), 0 0 30px 1px rgba(0,0,0,0.23);
    border-radius: 5px;
    padding: 20px;
}
.main h1{
    font-size: 20px;
    text-transform: uppercase;
}
.main p{
    margin-top: 30px;
    line-height: 26px;
}

Как только это будет сделано, мы можем приступить к написанию нашего кода Javascript.

Шаги

  • Создать функцию
  • Выберите HTML-код/элемент атрибута класса, который вы хотите анимировать.
  • Add a class and then call the function.

Не позволяйте этому утомлять вас, вот код:

function mainAppear(){
    var mainText = document.querySelector('.main');
    mainText.classList.add('main-appear');
}
mainAppear();

Примечание. В коде JS мы создали новый class( main-appear) в том же элементе, стиль которого позже будет применен в коде CSS.

Как только мы закончим с этим, бум🔥🎉, но еще одна вещь, нам нужно будет настроить наш код CSS, потому что это действительно парень, стоящий за всей анимацией 😂.

Добавьте это в атрибут класса HTML-кода.

opacity: 0; 
transform: translateY(100px);   
transition: 1s all ease-in-out;

И, наконец, чтобы все анимировалось, верните их в нормальное состояние, используя класс, который вы создали в своем коде JavaScript. 😕 Думаю, вы уже заскучали, но вот последний код.

.main-appear{
    opacity: 1;
    transform: translateY(0px);
}

Если вы все еще можете читать дальше, я объясню все, что только что произошло, должным образом.

Объяснение кода🔥

HTML-код

Это было очень легко понять. Просто имейте в виду, что мы использовали атрибут класса, который содержит материалы, которые мы хотим анимировать.

CSS-код

Как правило, за исключением нескольких кодов, добавленных позже, все остальные коды CSS являются обычным стилем.

Код, который мы добавили позже, просто помог нам добиться анимации через несколько секунд.

Мы добавили непрозрачность 0 к основному классу материалов, которые нужно анимировать, чтобы он сначала ничего не отображал, пока не будет вызван новый класс.

Мы также добавили переход на 0,5 секунды ко всем материалам в этом классе и сделали его плавным, чтобы он не происходил внезапно (чтобы он мог выглядеть реальным).

Можно было бы добавить много других вещей для улучшения визуального эффекта, например:
Преобразование, которое мы использовали для этого. Мы заставили его переводить по вертикали с помощью translateX или по горизонтали с помощью translateY и установили значение, с которого оно будет начинаться.

Свойство transform позволяет визуально манипулировать элементом путем наклона, вращения, перемещения или масштабирования.

Вы можете узнать больше о свойстве преобразования здесь.

Круто, мы почти закончили, но нам нужно отменить все, кроме перехода в новом классе, который мы добавили в коде JavaScript.

Javascript-код

Вот последнее, мы бы создали функцию

Вызов класса элемента, который мы хотим анимировать

Затем, наконец, добавьте новый класс и вызовите функцию.

При этом вы можете добавлять другие анимации на свой веб-сайт/приложение, просто понимая концепцию анимации.

Спасибо за прочтение!

Вот ссылка - https://codepen.io/olawanlejoel/pen/wvMPXVo на код, если вам не интересно много читать. Но если вы не торопитесь, я объясню все, что вам нужно знать.

Оригинальный источник статьи: https://dev.to/olawanle_joel/

#javascript #css #website #content 

Как анимировать контент сайта с помощью JavaScript и CSS
木村  直子

木村 直子

1680089160

如何使用 JavaScript 和 CSS 为网站内容制作动画

本文将解释如何使用 5 行 JavaScript 和几行 CSS 为您的网站内容添加视觉效果或动画😎。

众所周知,为网页添加视觉效果可以增强网站美感并增加对您网站的兴趣程度。

开始🎉

我们需要的第一件事是我们想要动画的 HTML 代码。确保你添加了一个属性,这样我们就可以在我们的 JS 代码中选择它。
对于这篇文章,我将使用这个

    <div class="main">
        <h1>This is the title of this div</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>

注意:这段代码有一类main.

其次,我会给它一点风格,让它看起来井井有条。

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body{
    font-family: sans-serif;
    display: flex;
    justify-content: center;
    align-content: center;
}

.main{
    height: 380px;
    width: 400px;
    box-shadow: 0 0 20px 1px rgba(0,0,0,0.19), 0 0 30px 1px rgba(0,0,0,0.23);
    border-radius: 5px;
    padding: 20px;
}
.main h1{
    font-size: 20px;
    text-transform: uppercase;
}
.main p{
    margin-top: 30px;
    line-height: 26px;
}

一旦完成,我们现在可以继续编写我们的 Javascript 代码

脚步

  • 创建函数
  • 选择要设置动画的类属性 HTML 代码/项目
  • 添加一个类,然后调用该函数。

不要让它让你厌烦,这里是代码:

function mainAppear(){
    var mainText = document.querySelector('.main');
    mainText.classList.add('main-appear');
}
mainAppear();

注意:在 JS 代码中,我们main-appear在稍后将在 CSS 代码中设置样式的同一元素中创建了一个新的 class()。

一旦我们完成了那个,boom🔥🎉,但还有一件事,我们需要调整我们的 CSS 代码,因为它真的是整个动画背后的人😂。

将其添加到 HTML 代码的类属性中

opacity: 0; 
transform: translateY(100px);   
transition: 1s all ease-in-out;

最后,为了使所有内容都具有动画效果,请使用您在 JavaScript 代码中创建的类将它们恢复正常。😕 我想你已经很无聊了,但这是最后一个代码。

.main-appear{
    opacity: 1;
    transform: translateY(0px);
}

如果你还能继续读下去,我会好好解释刚刚发生的一切。

代码说明🔥

网页代码

那绝对是非常容易理解的。请记住,我们使用了一个包含我们想要动画的东西的类属性。

CSS代码

一般除了后面加的那几段代码外,其他的CSS代码都是正常的样式。

我们后面添加的代码只是帮我们实现了几秒后的动画。

我们向要动画的东西的主类添加了 0 的不透明度,因此在调用新类之前它一开始什么都不显示。

我们还为该类中的所有内容添加了 0.5 秒的过渡,并使其缓慢发生,这样它就不会突然发生(因此它看起来很真实)。

可以添加许多其他东西来增强视觉效果,例如:
我们为此使用的变换。我们使用 translateX 使其垂直平移,或使用 translateY 使其水平平移,并设置它的起始值。

transform 属性允许您通过倾斜、旋转、平移或缩放来直观地操作元素。

您可以在此处了解有关转换属性的更多信息

太棒了,我们几乎完成了,但我们必须反转所有内容,除了我们在 JavaScript 代码中添加的新类中的转换。

Javascript 代码

这是最后一件事,我们将创建一个函数

调用我们想要动画的元素的类

然后最后添加一个新的类然后调用函数。

有了这个,您只需了解动画背后的概念,就可以将其他动画添加到您的网站/应用程序中。

谢谢阅读!

这是代码的链接 - https://codepen.io/olawanlejoel/pen/wvMPXVo以防您对阅读不感兴趣。但如果你不着急,我会解释你需要知道的一切。

原始文章来源:https: //dev.to/olawanle_joel/

#javascript #css #website #content 

如何使用 JavaScript 和 CSS 为网站内容制作动画

How to Animate Website Content with JavaScript and CSS

This article will explain how to add visual effects or animation to your website content with just 5 lines of JavaScript and a few lines of CSS😎.

As we all know that adding visual effects to web pages enhances site beauty and increases the level of interest in your site.

Getting Started🎉

The first thing we need is the HTML code of what we want to animate. Make sure you add a class attribute so we can be able to select it in our JS code.
For this article I would use this

    <div class="main">
        <h1>This is the title of this div</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>

Note: This code has a class of main.

Secondly, I would give it a little style so it looks organized.

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body{
    font-family: sans-serif;
    display: flex;
    justify-content: center;
    align-content: center;
}

.main{
    height: 380px;
    width: 400px;
    box-shadow: 0 0 20px 1px rgba(0,0,0,0.19), 0 0 30px 1px rgba(0,0,0,0.23);
    border-radius: 5px;
    padding: 20px;
}
.main h1{
    font-size: 20px;
    text-transform: uppercase;
}
.main p{
    margin-top: 30px;
    line-height: 26px;
}

Once that is done, we can now proceed to write our Javascript code

Steps

  • Create a function
  • Select the class attribute HTML code/item you want to animate
  • Add a class and then call the function.

Don't let that bore you, here is the code:

function mainAppear(){
    var mainText = document.querySelector('.main');
    mainText.classList.add('main-appear');
}
mainAppear();

Note: In the JS code we created a new class(main-appear) in the same element which we would be styling in the CSS code later.

Once we are done with that, boom🔥🎉, but One more thing, we would need to adjust our CSS code because it's really the guy behind the whole animation 😂.

Add this to the class attribute of the HTML code

opacity: 0; 
transform: translateY(100px);   
transition: 1s all ease-in-out;

And finally, to make everything animate, return them back to normal using the class you created in your JavaScript Code. 😕 I guess you are bored already, but here is the last code.

.main-appear{
    opacity: 1;
    transform: translateY(0px);
}

If you can still read on, I will explain everything that just happened properly.

Code Explanation🔥

Html Code

That was absolutely very easy to understand. Just bear in mind we made use of a class attribute that contains the stuffs we want to animate.

CSS code

Generally, aside from the few codes added later, every other CSS codes are the normal styling.

The code we added later just helped us achieve animation after a few seconds.

We added an opacity of 0 to the main class of the stuffs to be animated so it displays nothing at first until the new class is called.

We also added transition of 0.5 seconds to all stuffs in that class and made it happen gently so it doesn't just happen suddenly(so it could look real).

Many other things could be added to enhance the visual effect like :
Transform which we used for this. We made it translate vertically using translateX or horizontally using translateY and set the value of which it would start from.

The transform property allows you to visually manipulate an element by skewing, rotating, translating, or scaling.

You can learn more about the transform property here.

Cool, we are almost done but we have to reverse everything except the transition in the new class we added in the JavaScript Code.

Javascript code

Here is the last thing, we would create a function

Call the class of the element we want to animate

Then finally add a new class and then call the function.

With this, you can add other animations to your website/app by just understanding the concept behind the animation.

Thanks for reading!

Here is a link - https://codepen.io/olawanlejoel/pen/wvMPXVo to the code in case you are not interested in reading much. But if you are not in a hurry, I will explain everything you need to know.

Original article source at: https://dev.to/olawanle_joel/

#javascript #css #website #content 

How to Animate Website Content with JavaScript and CSS

Analytics: Simple, Open-source, Lightweight (< 1 KB)

Plausible Analytics

Plausible Analytics is a simple, lightweight (< 1 KB), open source and privacy-friendly alternative to Google Analytics. It doesn’t use cookies and is fully compliant with GDPR, CCPA and PECR. You can self-host or have us run Plausible for you in the cloud. Here's the live demo of our own website stats. Made and hosted in the EU 🇪🇺

We are dedicated to making web analytics more privacy-friendly. Our mission is to reduce corporate surveillance by providing an alternative web analytics tool which doesn’t come from the AdTech world. We are completely independent and solely funded by our subscribers.

Plausible Analytics

Why Plausible?

Here's what makes Plausible a great Google Analytics alternative and why we're trusted by thousands of paying subscribers to deliver their website and business insights:

  • Clutter Free: Plausible Analytics provides simple web analytics and it cuts through the noise. No layers of menus, no need for custom reports. Get all the important insights on one single page. No training necessary.
  • GDPR/CCPA/PECR compliant: Measure traffic, not individuals. No personal data or IP addresses are ever stored in our database. We don't use cookies or any other persistent identifiers. Read more about our data policy
  • Lightweight: Plausible Analytics works by loading a script on your website, like Google Analytics. Our script is 45x smaller, making your website quicker to load.
  • Email or Slack reports: Keep an eye on your traffic with weekly and/or monthly email or Slack reports. You can also get traffic spike notifications.
  • Open website stats: You have the option to be transparent and open your web analytics to everyone. Your website stats are private by default but you can choose to make them public so anyone with your custom link can view them.
  • Define key goals and track conversions: Set custom events or page URLs as your goals and see how they convert over time to understand and identify the trends that matter. Includes easy ways to track outbound link clicks and 404 error pages.
  • Search keywords: Integrate your dashboard with Google Search Console to get the most accurate reporting on your search keywords.
  • SPA support: Plausible is built with modern web frameworks in mind and it works automatically with any pushState based router on the frontend. We also support frameworks that use the URL hash for routing. See our documentation.

Interested to learn more? Read more on our website, learn more about the team and the goals of the project on our about page or explore the documentation.

Why is Plausible Analytics Cloud not free like Google Analytics?

Plausible Analytics is an independently owned and actively developed project. To keep the project development going, to stay in business, to continue putting effort into building a better product and to cover our costs, we need to charge a fee.

Google Analytics is free because Google has built their company and their wealth by collecting and analyzing huge amounts of personal information from web users and using these personal and behavioral insights to sell advertisements.

Plausible has no part in that business model. No personal data is being collected and analyzed either. With Plausible, you 100% own and control all of your website data. This data is not being shared with or sold to any third-parties.

We choose the subscription business model rather than the business model of surveillance capitalism. See reasons why we believe you should stop using Google Analytics on your website.

Getting started with Plausible

The easiest way to get started with Plausible is with our official managed service in the cloud. It takes 2 minutes to start counting your stats with a worldwide CDN, high availability, backups, security and maintenance all done for you by us.

In order to be compliant with the GDPR and the Schrems II ruling, all visitor data for our managed service in the cloud is exclusively processed on servers and cloud infrastructure owned and operated by European providers. Your website data never leaves the EU.

Our managed hosting can save a substantial amount of developer time and resources. For most sites this ends up being the best value option and the revenue goes to funding the maintenance and further development of Plausible. So you’ll be supporting open source software and getting a great service!

Can Plausible Analytics be self-hosted?

Plausible is fully open source web analytics and we have a free as in beer Plausible Analytics Self-Hosted solution. It’s exactly the same product as our cloud solution with a less frequent release schedule (think of it as a long term support release).

Bug fixes and new features are released to the cloud version several times per week. Features are battle-tested in the cloud which allows us to fix any bugs before the general self-hosted release. Every six months or so we combine all the changes into a new self-hosted release.

The main difference between the two is that the self-hosted version you have to install, host and manage yourself on your own infrastructure while the cloud version we manage everything for your ease and convenience. Here's the overview of all the differences:

 Plausible CloudSelf-Hosting
HostingEasy and convenient. It takes 2 minutes to start counting your stats with a worldwide CDN, high availability, backups, security and maintenance all done for you by us. We manage everything so you don’t have to worry about anything and can focus on your stats.You do it all yourself. You need to get a server and you need to manage your infrastructure. You are responsible for installation, maintenance, upgrades, server capacity, uptime, backup, security, stability, consistency, loading time and so on.
StorageAll visitor data is exclusively processed on EU-owned cloud infrastructure. We keep your site data on a secure, encrypted and green energy powered server in Germany. This ensures that your site data is protected by the strict European Union data privacy laws and ensures compliance with GDPR. Your website data never leaves the EU.You have full control and can host your instance on any server in any country that you wish. Host it on a server in your basement or host it with any cloud provider wherever you want, even those that are not GDPR compliant.
ReleasesContinuously developed and improved with new features and updates multiple times per week.It's a long term release published approximately twice per year so latest features won't be immediately available. You can see all the currently unreleased features in the changelog.
Raw dataYou see all your site stats and metrics on our modern-looking, simple to use and fast loading dashboard. You can only see the stats aggregated in the dashboard. You can download the stats using the CSV export, stats API or tools such as the Data Studio Connector.Do you want access to the raw data? Self-hosting gives you that option. You can take the data directly from the ClickHouse database.
Premium SupportReal support delivered by real human beings who build and maintain Plausible.Premium support is not included. Self-hosting is community supported only.
CostsThere's a cost associated with providing an analytics service so we charge a subscription fee. We choose the subscription business model rather than the business model of surveillance capitalism. Your money funds further development of Plausible.You need to pay for your server, CDN, backups and whatever other cost there is associated with running the infrastructure. You never have to pay any fees to us. Your money goes to 3rd party companies with no connection to us.

Interested in self-hosting Plausible on your server? Take a look at our self-hosting installation instructions.

Plausible Self-Hosted is a community supported project and there are no guarantees that you will get support from the creators of Plausible to troubleshoot your self-hosting issues. There is a community supported forum where you can ask for help.

Our only source of funding is our premium, managed service for running Plausible in the cloud. If you're looking for an alternative way to support the project, we've put together some sponsorship packages. If you choose to self-host Plausible you can become a sponsor which is a great way to give back to the community and to contribute to the long-term sustainability of the project.

Technology

Plausible Analytics is a standard Elixir/Phoenix application backed by a PostgreSQL database for general data and a Clickhouse database for stats. On the frontend we use TailwindCSS for styling and React to make the dashboard interactive.

Feedback & Roadmap

We welcome feedback from our community. We have a public roadmap driven by the features suggested by the community members. Take a look at our feedback board directly here on GitHub. Please let us know if you have any requests and vote on open issues so we can better prioritize.

To stay up to date with all the latest news and product updates, make sure to follow us on Twitter, LinkedIn or Mastodon.


Download Details:

Author: Plausible
Source Code: https://github.com/plausible/analytics/ 
License: AGPL-3.0 license

#elixir #website #charts #marketing #cloud 

Analytics: Simple, Open-source, Lightweight (< 1 KB)

Running_page: Make Your Own Running Home Page

Running page

Create a personal running home page 

demo

English | 简体中文 | Wiki

Runner's Page Show

Running page runners

RunnerpageApp
zhubao315https://zhubao315.github.io/runningStrava
shaonianchehttps://run.duanfei.orgStrava
yihong0618https://yihong.runNike
superleeyomhttps://running.leeyom.topNike
geekpluxhttps://activities.geekplux.comNike
guanlanhttps://grun.vercel.appStrava
tuzimoehttps://run.tuzi.moeNike
ben_29https://running.ben29.xyzStrava
kcllfhttps://running-tau.vercel.appGarmin-cn
mqhttps://running-iota.vercel.appKeep
zhaohongxuanhttps://running-page-psi.vercel.appKeep
yvetterowehttps://run.haoluo.ioStrava
love-exercisehttps://run.kai666666.topKeep
zstone12https://running-page.zstone12.vercel.appKeep
Laxhttps://lax.github.io/runningKeep
lusuzihttps://running.lusuzi.vercel.appNike
wh1994https://run4life.funGarmin
liuyihuihttps://run.foolishfox.cnKeep
sunyunxianhttps://sunyunxian.github.io/running_pageStrava
AhianZhanghttps://running.ahianzhang.comNike
L1cardohttps://run.licardo.cnNike
luckylele666https://0000928.xyzStrava
MFYDevhttps://mfydev.runGarmin-cn
Eishedhttps://run.iknow.funKeep
Liuxinhttps://liuxin.runNike
loucxhttps://loucx.github.io/runningNike
winf42https://winf42.github.ioGarmin-cn
sun0225SUNhttps://run.sunguoqi.comNike
Zhanhttps://run.zlog.inNike
Dennishttps://run.domon.cnGarmin-cn
hanpeihttps://running.nexts.topGarmin-cn
liugezhouhttps://run.liugezhou.onlineStrava
Jason Tanhttps://jason-cqtan.github.io/running_pageNike
Congehttps://conge.github.io/running_pageStrava
zHElEARNhttps://workouts.zhelearn.comStrava
Ym9ihttps://bobrun.vercel.app/Strava
jianchengwanghttps://jianchengwang.github.io/running_pageSuunto
fxbinhttps://fxbin.github.io/sport-records/Keep
shensl4499https://waner.runcodoon

How it works

image

Features

  1. GitHub Actions manages automatic synchronization of runs and generation of new pages.
  2. Gatsby-generated static pages, fast
  3. Support for Vercel (recommended) and GitHub Pages automated deployment
  4. React Hooks
  5. Mapbox for map display
  6. Supports most sports apps such as nike strava...

automatically backup gpx data for easy backup and uploading to other software.
Note: If you don't want to make the data public, you can choose strava's fuzzy processing, or private repositories.

Download

Clone or fork the repo.

git clone https://github.com/yihong0618/running_page.git --depth=1

Installation and testing (node >= 12 and <= 14 python >= 3.7)

pip3 install -r requirements.txt
yarn install
yarn develop

Open your browser and visit http://localhost:8000/

Docker

#build
# NRC
docker build -t running_page:latest . --build-arg app=NRC --build-arg nike_refresh_token=""
# Garmin
docker build -t running_page:latest . --build-arg app=Garmin --build-arg email=""  --build-arg password="" 
# Garmin-CN
docker build -t running_page:latest . --build-arg app=Garmin-CN --build-arg email=""  --build-arg password="" 
# Strava
docker build -t running_page:latest . --build-arg app=Strava --build-arg client_id=""  --build-arg client_secret=""  --build-arg refresch_token="" 
#Nike_to_Strava
docker build -t running_page:latest . --build-arg app=Nike_to_Strava  --build-arg nike_refresh_token="" --build-arg client_id=""  --build-arg client_secret=""  --build-arg refresch_token="" 

#run
docker run -itd -p 80:80   running_page:latest

#visit
Open your browser and visit localhost:80

Local sync data

Modifying Mapbox token in src/utils/const.js

If you use English please change IS_CHINESE = false in src/utils/const.js 
Suggested changes to your own Mapbox token

const MAPBOX_TOKEN =
  'pk.eyJ1IjoieWlob25nMDYxOCIsImEiOiJja2J3M28xbG4wYzl0MzJxZm0ya2Fua2p2In0.PNKfkeQwYuyGOTT_x9BJ4Q';

Custom your page

  • Find gatsby-config.js in the repository directory, find the following content, and change it to what you want.
siteMetadata: {
  siteTitle: 'Running Page', #website title
  siteUrl: 'https://yihong.run', #website url
  logo: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQTtc69JxHNcmN1ETpMUX4dozAgAN6iPjWalQ&usqp=CAU', #logo img
  description: 'Personal site and blog',
  navLinks: [
    {
      name: 'Blog', #navigation name
      url: 'https://yihong.run/running', #navigation url
    },
    {
      name: 'About',
      url: 'https://github.com/yihong0618/running_page/blob/master/README-CN.md',
    },
  ],
},
  • Modifying styling in src/utils/const.js
// styling: set to `false` if you want to disable dash-line route
const USE_DASH_LINE = true;
// styling: route line opacity: [0, 1]
const LINE_OPACITY = 0.4;

Download your running data and do not forget to generate svg in total page

GPX

Make your GPX data

Copy all your gpx files to GPX_OUT or new gpx files

python3(python) scripts/gpx_sync.py

TCX

Make your TCX data

Copy all your tcx files to TCX_OUT or new tcx files

python3(python) scripts/tcx_sync.py

Garmin

Get your Garmin data
If you only want to sync `type running` add args --only-run If you only want `tcx` files add args --tcx

python3(python) scripts/garmin_sync.py ${your email} ${your password}

example:

python3(python) scripts/garmin_sync.py example@gmail.com example

only-run:

python3(python) scripts/garmin_sync.py example@gmail.com example --only-run

Garmin-CN(China)

Get your Garmin-CN data
If you only want to sync `type running` add args --only-run If you only want `tcx` files add args --tcx

python3(python) scripts/garmin_sync.py ${your email} ${your password} --is-cn

example:

python3(python) scripts/garmin_sync.py example@gmail.com example --is-cn

Nike Run Club

Get your Nike Run Club data

Please note: When you choose to deploy running_page on your own server, due to Nike has blocked some IDC's IP band, maybe your server cannot sync Nike Run Club's data correctly and display 403 error, then you have to change another way to host it.

Get Nike's refresh_token

  1. Login Nike website
  2. In Develop -> Application-> Storage -> https:unite.nike.com look for refresh_token
     

image

  • Execute in the root directory:
python3(python) scripts/nike_sync.py ${nike refresh_token}

example:

python3(python) scripts/nike_sync.py eyJhbGciThiMTItNGIw******

example img

Strava

Get your Strava data

Sign in/Sign up Strava account

Open after successful Signin Strava Developers -> Create & Manage Your App

Create My API Application: Enter the following information

My API Application

Created successfully:

  • Use the link below to request all permissions: Replace ${your_id} in the link with My API Application Client ID
https://www.strava.com/oauth/authorize?client_id=${your_id}&response_type=code&redirect_uri=http://localhost/exchange_token&approval_prompt=force&scope=read_all,profile:read_all,activity:read_all,profile:write,activity:write

get_all_permissions

  • Get the code value in the link

example:

http://localhost/exchange_token?state=&code=1dab37edd9970971fb502c9efdd087f4f3471e6e&scope=read,activity:write,activity:read_all,profile:write,profile:read_all,read_all

code value:

1dab37edd9970971fb502c9efdd087f4f3471e6

get_code

  • Use Client_idClient_secretCode get refresch_token: Execute in Terminal/iTerm
curl -X POST https://www.strava.com/oauth/token \
-F client_id=${Your Client ID} \
-F client_secret=${Your Client Secret} \
-F code=${Your Code} \
-F grant_type=authorization_code

example:

curl -X POST https://www.strava.com/oauth/token \
-F client_id=12345 \
-F client_secret=b21******d0bfb377998ed1ac3b0 \
-F code=d09******b58abface48003 \
-F grant_type=authorization_code

get_refresch_token

  • Sync Strava data
python3(python) scripts/strava_sync.py ${client_id} ${client_secret} ${refresch_token}

References:

TCX_to_Strava

upload all tcx files to strava
 

  1. follow the strava steps
  2. copy all your tcx files to TCX_OUT
  3. Execute in the root directory:
python3(python) scripts/tcx_to_strava_sync.py ${client_id} ${client_secret}  ${strava_refresch_token}

example:

python3(python) scripts/tcx_to_strava_sync.py xxx xxx xxx
or
python3(python) scripts/tcx_to_strava_sync.py xxx xxx xxx --all
  • if you want to all files add args --all

GPX_to_Strava

upload all gpx files to strava
 

  1. follow the strava steps
  2. copy all your gpx files to GPX_OUT
  3. Execute in the root directory:
python3(python) scripts/gpx_to_strava_sync.py ${client_id} ${client_secret}  ${strava_refresch_token}

example:

python3(python) scripts/gpx_to_strava_sync.py xxx xxx xxx
or
python3(python) scripts/tcx_to_strava_sync.py xxx xxx xxx --all
  • if you want to all files add args --all

Nike_to_Strava

Get your Nike Run Club data and upload to strava
 

  1. follow the nike and strava steps
  2. Execute in the root directory:
python3(python) scripts/nike_to_strava_sync.py ${nike_refresh_token} ${client_id} ${client_secret} ${strava_refresch_token}

example:

python3(python) scripts/nike_to_strava_sync.py eyJhbGciThiMTItNGIw******  xxx xxx xxx

Garmin_to_Strava

Get your Garmin data and upload to strava
 

  1. finish garmin and strava setps
  2. Execute in the root directory:
python3(python) scripts/garmin_to_strava_sync.py  ${client_id} ${client_secret} ${strava_refresch_token} ${garmin_email} ${garmin_password} --is-cn

e.g.

python3(python) scripts/garmin_to_strava_sync.py  xxx xxx xxx xx xxx

Strava_to_Garmin

Get your Strava data and upload to Garmin
 

  1. finish garmin and strava setps, at the same time, you need to add additional strava config in Github Actions secret: secrets.STRAVA_EMAILsecrets.STRAVA_PASSWORD
  2. Execute in the root directory:
python3(python) scripts/strava_to_garmin_sync.py ${{ secrets.STRAVA_CLIENT_ID }} ${{ secrets.STRAVA_CLIENT_SECRET }} ${{ secrets.STRAVA_CLIENT_REFRESH_TOKEN }}  ${{ secrets.GARMIN_EMAIL }} ${{ secrets.GARMIN_PASSWORD }} ${{ secrets.STRAVA_EMAIL }} ${{ secrets.STRAVA_PASSWORD }}

if your garmin account region is China, you need to execute the command:

python3(python) scripts/strava_to_garmin_sync.py ${{ secrets.STRAVA_CLIENT_ID }} ${{ secrets.STRAVA_CLIENT_SECRET }} ${{ secrets.STRAVA_CLIENT_REFRESH_TOKEN }}  ${{ secrets.GARMIN_CN_EMAIL }} ${{ secrets.GARMIN_CN_PASSWORD }} ${{ secrets.STRAVA_EMAIL }} ${{ secrets.STRAVA_PASSWORD }} --is-cn

ps: when initializing for the first time, if you have a large amount of strava data, some data may fail to upload, just retry several times.

Total Data Analysis

Running data display
 

python scripts/gen_svg.py --from-db --title "${{ env.TITLE }}" --type github --athlete "${{ env.ATHLETE }}" --special-distance 10 --special-distance2 20 --special-color yellow --special-color2 red --output assets/github.svg --use-localtime --min-distance 0.5
python scripts/gen_svg.py --from-db --title "${{ env.TITLE_GRID }}" --type grid --athlete "${{ env.ATHLETE }}"  --output assets/grid.svg --min-distance 10.0 --special-color yellow --special-color2 red --special-distance 20 --special-distance2 40 --use-localtime

Generate year circular svg show

python3(python) scripts/gen_svg.py --from-db --type circular --use-localtime

For more display effects, see: https://github.com/flopp/GpxTrackPoster

server(recommendation vercel)

Use Vercel to deploy
 

  • vercel connects to your GitHub repo.


 

image

  • import repo


 

image

  1. Awaiting completion of deployment
  2. Visits

Use Cloudflare to deploy
 

Click Create a project in Pages to connect to your Repo.

After clicking Begin setup, modify Project's Build settings.

Select Framework preset to Gatsby

Scroll down, click Environment variables, then variable below:

Variable name = PYTHON_VERSION, Value = 3.7

Click Save and Deploy

Deploy to GitHub Pages

If you are using a custom domain for GitHub Pages, open .github/workflows/gh-pages.yml, change fqdn value to the domain name of your site.

(Skip this step if you're NOT using a custom domain) Modify gatsby-config.js, change pathPrefix value to the root path. If the repository name is running_page, the value will be /running_page.

Go to repository's Actions -> Workflows -> All Workflows, choose Publish GitHub Pages from the left panel, click Run workflow. Make sure the workflow runs without errors, and gh-pages branch is created.

Go to repository's Settings -> GitHub Pages -> Source, choose Branch: gh-pages, click Save.

GitHub Actions

Modifying information in GitHub Actions 
 

Actions source code The following steps need to be taken

  • change to your app type and info
     

image

  • Add your secret in repo Settings > Secrets (add only the ones you need).


 

image

  • My secret is as follows
     

image

  • Go to repository's Settings -> Code and automation -> Actions ->General, Scroll to the bottom, find Workflow permissions, choose the first option Read and write permissions, click Save.

TODO

  •  Complete this document.
  •  Support Garmin, Garmin China
  •  support for nike+strava
  •  Support English
  •  Refine the code
  •  add new features
  •  tests
  •  support the world map
  •  support multiple types, like hiking, biking~

Contribution

  • Any Issues PR welcome.
  • You can PR share your Running page in README I will merge it.

Before submitting PR:

  • Format Python code with black (black .)

Special thanks

Recommended Forks

Support

Just enjoy it~

FAQ

Strava Api limit

https://www.strava.com/settings/api https://developers.strava.com/docs/#rate-limiting

Strava API Rate Limit Exceeded. Retry after 100 seconds
Strava API Rate Limit Timeout. Retry in 799.491622 seconds

注:如果是之前 clone 或 Fork 的朋友 vercel 显示 404 可能需要更新下代码


Download Details:

Author: yihong0618
Source Code: https://github.com/yihong0618/running_page 
License: MIT license

#python #datavisualization #dataanalysis #mapbox 

Running_page: Make Your Own Running Home Page