Blog

  • typographie.js

    #Typographie.js Build Status Dependency Status

    Library for preparation of russian texts to web publication.
    Core of Typographie web service.

    Installation

    Via npm:

    npm install typographie --save
    

    Via Bower:

    bower install typographie --save
    

    In a browser:

    <script src="https://github.com/asleepwalker/lib/typographie.js"></script>
    

    Example

    var Typographie = require('typographie');
    var engine = new Typographie(['quotes', 'dashes', 'specials', 'paragraphs']);
    
    var raw = 'Сервис "Typographie" - подготовка текстов к веб-публикации онлайн (с) 2014-2017';
    var result = engine.process(raw);
    
    console.log(result);
    // > Сервис «Typographie» — подготовка текстов к веб-публикации онлайн © 2014–2017
    

    Actions

    quotes : Correction of quotes: “” becomes «».
    inquot (needs quotes) : Nested quotes: «„“» (otherwise — duplicate quotes stashing).
    dashes : If necessary replace hyphens with dashes and minus signs.
    angles : Replace asterisks and quotes with degrees, feet, inches.
    dblspace : Fix duplicate spaces in the text.
    specials : Insert special characters (from the symbol table).
    mathchars : Insert mathematical symbols (from the same table).
    punctuation : Fix punctuation, such as spaces before commas.
    specialspaces : Fix the wrong skip special characters with spaces.
    nbsp : Attach short words to following words in the text.
    hellip : Replace repeating dot symbols with ellipsis.
    paragraphs : Puts paragraphs (<p>) when converting to HTML (with empty string as a delimeter).
    safehtml : Don’t process text inside of <code> and <pre> blocks.
    entities : Replace special chars with HTML entities.

    If the list of actions was skiped in constructor, all of them will be performed.

    Beside defining in the object constructor, you can change configuration by method actions:

    engine.actions(['punctuation', 'dblspace']);
    console.log(engine.process('К  чёрту орфографию ,главное   все понимают !Ведь так  ?..'));
    // > К чёрту орфографию, главное все понимают! Ведь так?..
    

    Modes

    plain : Just plain text.
    html : Safe HTML processing.

    The mode could be defined in the constructor:

    var engine = new Typographie(['quotes', 'dashes'], input, output);
    

    Or by method mode:

    engine.mode('html', 'plain');
    

    Default congifuration is plain mode for both input and output.

    License

    The MIT License.

    Visit original content creator repository https://github.com/asleepwalker/typographie.js
  • Manufacturing-Plant-Construction-Project

    Manufacturing Plant Construction Project

    This work is aimed at simulating a real process of preparing a technical-economic offer for the construction of some parts of an industrial plant (building and a processing line for motor vehicle heads), as part of a tender for international procurement. The offer will consist of graphic and descriptive drawings according to the specifications provided.

    The exercise (carried out in teams) intends to simulate a real professional situation: each group must imagine being a proposal team operating within a construction engineering & contracting company.

    During the final evaluation of the exercise, the teachers will represent the client who requested the offer and who must award the order to the best contractor according to the most economically advantageous offer according to the criteria set out in the RFP.

    Proposal

    In the folder Proposal there are the following files for the proposal:

    • Project Plan (WBS, ReBS, WBS/OBS, CBS)
    • Executive Summary
    • Time Schedule
    • Crashing (time-cost tradeoff)
    • RBS/RBM/contingency
    • Risk assessment plan
    • Value added plan
    • Price and schedule proposal
    • Price calculations & Cash flow graphs
    • Project Budget

    This project is a part of Project management exam of Polytechnic of Turin.

    Visit original content creator repository
    https://github.com/luca-bajardi/Manufacturing-Plant-Construction-Project

  • kavlan-html-bootstrap

    Kavlan – Bootstrap 5 HTML Responsive Admin Template

    Overview

    Kavlan is the perfect dark admin panel template to make your administration system a breeze to navigate and maintain. Clean, responsive, and easy-to-use, Kavlan delivers a user experience that will help you create a successful interface. And above all, it’s free!

    View Demo | Download ZIP

    Bootstrap 5 Responsive HTML Admin Panel

    Table of contents

    Requirements

    If you do not intend to work with the template source code (and that means you will not be compiling it or running the Webpack dev server), you do not need to install anything. You can simply navigate to the dist folder and start editing the files.

    Most developers will be editing the source code and will also be running Webpack to recompile the template files. If that’s the case, then ensure that you have Node.js installed. You can download it from here

    Quick Start

    • Download the latest release OR clone the repo: git clone https://github.com/PixelRocket-Shop/kavlan-html-bootstrap.git
    • Install Node.js if you don’t already have it on your system.
    • Open the project root in your command line.
    • run npm install in your command line.
    • run npm start to start Webpack devserver.
    • if you want to recompile the template files (which output to the dist folder), run npm run build

    Template Pages

    The template consists of 6 pages:

    • Dashboard
    • Login Page
    • Register Page
    • Forgot Password Page
    • 404 Page
    • Blank Page

    To keep code repetition to a minimum, we’ve used Handlebars.js as the templating engine and partials to quickly add the same code to different pages. We also use a Handlebars plugin for JSON data – this allows us to use loops and output a single HTML code block instead of repeating the same HTML.

    Demo Link

    Demo URL

    Please note that this is an HTML template only. It does not connect to a database, and will not automatically work in a content management system (WordPress etc). You will need to incorporate our code into your application.

    Template Key Features

    • Chart.js integration with 3 different chart types
    • Built with Bootstrap 5
    • Fully responsive
    • Latest orders component
    • Collapsible sidebar (auto collapses on browser resize)
    • Notifications component
    • Avatar component
    • Login/register component

    Template File structure

    📁 dist – Generated version of the template. Go here if you do not want to work with the template source code. But be warned: if you customise anything in this folder directly, and then later recompile the template using webpack, unless you move the dist folder out of the template, your changes will be overridden.

    📁 node_modules – Directory where NPM installs dependancies. You will not see this folder until you complete the template installation. You do not need to create this folder.

    📁 src – Template source code. Go here to customise your template.

    📁 src/assets – Template assets such as CSS, JS, Images etc.

    📁 src/data – Template JSON Data files. We use these JSON files to make your job easier to insert content into the template.

    📁 src/html – Template pages. Go here to edit existing pages or add new pages.

    📁 src/partials – Handlebars partial templates.

    Handlebars

    Handlebars is a template engine that allows us to keep our template source code as organised and as clean as possible. It cuts down on code duplication and through the use of helper functions, allows template developers to very quickly output large amounts of data with minimal code. You can read more about it here.

    Example Handlebars Partial

    Open the following file in our template: src/html/index.html.

    Around line 21 you’ll see the following code:

    {{> content/breadcrumbs }}
    

    That’s a Handlebars partial. That code tells Handlebars to look inside a folder called content (located in the partials folder) and then to find a file called breadcrumbs and insert it into the index.html file when it is compiled.

    There are a few important notes about our use of Handlebars partials:

    • All of our partials are stored inside src/partials. Do not place partials anywhere else.
    • We use .html as our partial file extension. We have also added .svg as a valid partial file extension.
    • If you have folders within folders inside your partial folder, only reference the folder the partial resides in. So “partials/header/navbars/navbar.html” would be referenced as “navbars/navbar”.
    • Do not include the partial file extension. Note in the example above that we output “breadcrumbs” and not “breadcrumbs.html”

    Template JSON Data

    The Webpack Handlebars plugin that we use comes with a very handy utility that allows us to pass in JSON files as template data.

    Please navigate to: src/data. Here is where our template data JSON files reside. You can edit, remove or add your own to this folder.

    Customise Template Styles

    All of the template’s source CSS/SASS files are kept inside the template’s assets folder. Navigate to src/assets/scss. Open up theme.scss with your editor.

    This is the main entry point for all other SASS/CSS files.

    Create New Pages

    To create a new page, navigate in your code editor to: src/html. To make it easier to get the correct HTML in place, clone an existing page. Rename the newly-created file to whatever URL you require. And that’s it. You are now free to open the new page with your code editor, make your changes, and then save the file. Quit Webpack devserver and restart it for the page to show up.

    Bootstrap Documentation

    Bootstrap already has a comprehensive documentation site that will guide you in setting up and using all default Bootstrap features. Bootstrap 5 is fully integrated to our template’s source code. Please refer to Bootstrap’s doc site first for any default Bootstrap features: Visit Bootstrap’s Doc Site

    Credits

    Bootstrap

    chart.js

    Unsplash

    Pexels

    Pixabay

    Simplebar.js

    Contact Us

    You can find our website here or you can email us at support@pixelrocket.store

    Visit original content creator repository
    https://github.com/PixelRocket-Shop/kavlan-html-bootstrap

  • ansible-bootstrap-server

    ansible-bootstrap-server

    Build status

    Targets Debian and RHEL based systems

    • bootstrap-server:

      Currently, it has roles for

      • update : update the apt-cache and upgrades it
      • install-minimal-packages : Installs some bare bones apt-packages
      • create-new-user: Creates a new user called {{ username }} (specified inside the defaults/main.yml) and copies the host’s .ssh/id_rsa over to the new user’s .ssh dir and adds this user to the sudoers list
        • specify your hashed password inside the file roles/create_new_user/defaults/main.yml
        • generate your hashed password using
       python -c 'import crypt; print crypt.crypt("<your-password>", "<your-key>")'
      • basic-server-hardening:
        • Disallow root SSH access
        • Disallow password authentication
        • Enable a basic firewall (ufw in this case )
      • vimrc-server-flavor: places the .vimrc server taken from my dotfiles and places it into the ~/.vimrc for the user {{ usnername }}
      • pip
        • Installs pip and mkvirtualenv for managing python virtual environments

    Running it

    NOTE: You need to have sshpass on your machine. Ref

    For Mac

    • brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb

    For Debian based systems

    • apt-get install sshpass
    $ cp inventory.example inventory
    $ cat inventory.example
    [remotenode]
    <ip-addr>
    
    [all:vars]
    ansible_connection=ssh
    ansible_ssh_user=root
    ansible_ssh_pass=<your-pass>

    If everything is good, check the ssh connection once

    $ ansible -m ping -i inventory remotenode
    <ip-addr> | SUCCESS => {
        "changed": false,
        "ping": "pong"
    }

    Change the variable in play.yml named your-username with the new user that you want to create

    $ ansible-playbook play.yml -i inventory -vvv

    LICENSE

    GPLv3

    Donation

    If you have found my little bits of software being of any use to you, do consider helping me pay my internet bills 🙂

    PayPal Donate via PayPal!
    Gratipay Support via Gratipay
    Patreon Support me on Patreon
    £ (GBP) Donate via TransferWise!
    € Euros Donate via TransferWise!
    ₹ (INR) Donate via instamojo
    Visit original content creator repository https://github.com/tasdikrahman/ansible-bootstrap-server
  • WeihanLi.Extensions.Localization.Json

    WeihanLi.Extensions.Localization.Json WeihanLi.Extensions.Localization.Json

    Intro

    dotnet JSON file based localization

    Build

    AzureDevOps Build Status

    Github Build Status

    GetStarted

    register required services:

    services.AddJsonLocalization(options =>
        {
            options.ResourcesPath = Configuration.GetAppSetting("ResourcesPath");
            options.ResourcesPathType = ResourcesPathType.TypeBased; // by default, looking for resourceFile like Microsoft do
            // options.ResourcesPathType = ResourcesPathType.CultureBased; // looking for resource file in culture sub dir see details follows
        });

    middleware config(the same with before):

    app.UseRequestLocalization();

    That’s it~

    Add your resource files

    TypeBasedResourcePath

    For Types:

    Home/Index => Controllers/HomeController

    the resource path looking for:

    • Controllers/HomeController.[cultureName].json

    for example:

    • Resources/Controllers/HomeController.en.json
    • Resources/Controllers/HomeController.zh.json

    For RazorViews:

    for example:

    • Resources/Views/Home/Index.en.json
    • Resources/Views/Home/Index.zh.json

    CultureBasedResourcePath

    For Types:

    Home/Index => Controllers/HomeController

    the resource path looking for:

    • Resources/[cultureName]/Controllers/HomeController.json

    for example:

    • Resources/en/Controllers/HomeController.json
    • Resources/zh/Controllers/HomeController.json

    For RazorViews:

    for example:

    • Resources/en/Views/Home/Index.json
    • Resources/zh/Views/Home/Index.json

    Copy your resource files to output:

    you had to set resource files copy to output to make it works normal

    add the follows sample config to your startup project file:

    <ItemGroup>
    <Content Update="Resources\**\*.json">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    </ItemGroup>

    the config above is made to make sure your json resource files in Resources dir copied to output, change it if you need

    Use

    just like what you do before:

    Controller sample:

    public class ValuesController : Controller
    {
        private readonly IStringLocalizer<ValuesController> _localizer;
    
        public ValuesController(IStringLocalizer<ValuesController> localizer)
        {
            _localizer = localizer;
        }
    
        // GET: api/<controller>
        [HttpGet]
        public string Get()
        {
            return _localizer["Culture"];
        }
    }

    Razor View Sample:

    @using Microsoft.AspNetCore.Mvc.Localization
    @using Microsoft.Extensions.Localization
    @using WeihanLi.Extensions.Localization.Json.Sample.Controllers
    @inject IHtmlLocalizer<HomeController> HtmlLocalizer
    @inject IStringLocalizer<HomeController> StringLocalizer
    @inject IViewLocalizer ViewLocalizer
    @{
        ViewData["Title"] = "Index";
    }
    
    <h2>Index</h2>
    
    <div>string: @StringLocalizer["Hello"]</div>
    
    <div>html: @HtmlLocalizer["Hello"]</div>
    
    <div>view: @ViewLocalizer["Hello"]</div>

    Resource file sample:

    {
      "Culture": "English"
    }

    Samples

    Contact

    Contact me via weihanli@outlook.com if you need

    Visit original content creator repository https://github.com/WeihanLi/WeihanLi.Extensions.Localization.Json
  • node-character.ai

    Character AI Unofficial API

    Node.js client for the unofficial Character AI API.

    Intro

    This is a Node.js client for the unofficial Character AI API. It is not affiliated with Character AI in any way. It is a community project. TS typings are included.

    You can use it to start building projects powered by your CharacterAI entitites, like chatbots, websites, etc.

    Installation

    npm install node-character.ai

    Usage

    // You can find this test script in the src folder
    import CharacterAI from 'node-character.ai';
    
    export class Test {
      public static async sendMessage(message: string): Promise<void> {
        const characterAi = new CharacterAI();
        // accessToken is required; keep reading for details.
        await characterAi.authenticate(process.env.CHARACTERAI_TOKEN);
    
        // you can find your characterId in the URL of a Character's chat page. Keep reading for details.
        const chat = await characterAi.continueOrCreateChat(
          process.env.CHARACTERAI_CHARID,
        );
    
        // send a message and wait for the response
        const response = await chat.sendAndAwaitResponse({
          message,
          singleReply: true, // if you want just what would show up in the chat, set this to true
        });
    
        // response can be either an array of possible responses or a single response
        console.log(response);
      }
    }
    
    Test.sendMessage('Greetings! What are your plans for today?');

    Access Token

    This package requires a valid session token from Character AI. You can get one by logging in to your Character AI account and copying the value of the accessToken in the localStorage of your browser.

    1. Open the Character AI website in your browser
    2. Open the developer tools F12 and go to the Application tab.
    3. Go to the Storage section and click on Local Storage.
    4. Look for the @@auth0spajs@@::dyD3gE281MqgISG7FuIXYhL2WEknqZzv::https://auth0.character.ai/::openid profile email offline_access key.
    5. Open the body and copy the access token.

    Access Token

    Character ID

    You can find your character ID in the URL of a Character’s chat page. For example, if you go to the chat page of the character Test Character you will see the URL https://character.ai/chat/chat?char=5f7f9b9b9b9b9b9b9b9b9b9b. The last part of the URL is the character ID:

    Character ID

    Visit original content creator repository https://github.com/RichardDorian/node-character.ai
  • Mega-EverDrive-Uploader

    Mega-EverDrive-Uploader

    Скорректированная и оптимизированная юзер-френдли сборка mega-usb – утилиты управления картриджем Mega EverDrive (стоковый исходный код на сайте разработчика Mega EverDrive).

    mega-everdrive

    Плюшки:

    • Встроена справочная легенда по формату использования и параметрам (/?);
    • Детализированы сообщения по ходу работы утилиты;
    • Исправлены недочеты, добавлены дополнительные проверки;
    • Исходник сформатирован «по-красоте» 😉

    При подключении Mega EverDrive к ПК (Windows-система) соединение организуется в виде виртуального USB-COM-порта (требуется драйвер). Когда Mega EverDrive уже включен и загружен с подготовленной карты памяти в нем (на экране Сеги “меню”) – игры загружаются в одну команду, для загрузки другой игры нужно вернуться обратно в меню (напр. по сбросу). Если SD-карты в Mega EverDrive нет, то сначала загружаем (через USB, данной утилитой) конфигурацию FPGA (*.rbf), потом ОС контроллера (MEGA.BIN) или одной командой враз, а лишь затем игру – далее можно загружать игры также только после сброса “ресетом” (до цикла питания).

    Конфигурация SVP.rbf самодостаточна (можно использовать вместо MEGA.rbf для любых игр) – но после ее применения будут также работать загружаемые программы, использующие сопроцессор SVP эмулируемый в FPGA (даже заголовок ROM не учитывается, в то же время при загрузке программы с карты памяти для активации SVP по адресу 0x000150 должно быть написано «Virtua Racing»). Рекомендую использовать комплект версии 3.13 (последняя – 3.14 работает некорректно, т.е. не работает).

    По-умолчанию (без опций) образ ROM загружается и запускается как «обычный» (т.е. без маппера – размер до 4МБ); при наличии в заголовке указания на маппер «SSF», он активируется и на Mega EverDrive (вне зависимости от размера образа); если ROM больше 4МБ и не содержит указания SSF в заголовке – то будет активирован режим «M10» («сквозная адресация», которая может быть несовместима с подключенными перманентно Mega-CD или встроенными играми, а также с 32X; режим «M10» используется самоделками и хаками). Указание опций превалирует над указанным порядком. Максимальный размер загружаемого ROM (даже в режиме SSF) – 15МБ (аппаратное ограничение Mega EverDrive).

    Использовать так:

    mega-usb <имя_файла> [-опции]
    
    Упрощенное использование (без опций):
    
    *.RBF		- Загрузка конфигурации в FPGA
    MEGA.BIN	- Загрузка образа ОС 68k в Mega EverDrive v2(x7), x3 ,x5
    MEGAOS.bin	- Загрузка образа ОС 68k в Mega EverDrive v1 (не для v2)
    *.SMS		- Загрузка программы (игры) в режиме MasterSystem
    *.*		- Загрузка программы (игры) в режиме MegaDrive (SMD, М10, SSF - см. выше)
    
    Опции (не применяются к фиксированным маскам, указанным выше):
    
    -smd		- Загрузка файла как SMD, обычный ROM (зачастую избыточно, т.к. по-умолчанию)
    -m10		- Загрузка файла как SMD "big-ROM" (10MB без маппера)
    -ssf		- Загрузка файла как SMD ROM с маппером SSF (исп. также для доступа к функциям EverDrive, см. ниже)
    -cd		- Загрузка файла как Mega-CD addon ROM BIOS (требуется соотв. оборудование)
    -32x		- Загрузка файла как 32X addon ROM (требуется соотв. оборудование)
    -sms		- Загрузка файла как MasterSystem ROM
    -os		- Загрузка файла как EverDrive приложения
    -o		- Загрузка образа ОС в Mega EverDrive v1 (не для v2)
    		  (Аналогично MEGAOS.bin без опций)
    -fo		- Загрузка образа в т.ч. Прошивки в Mega EverDrive v1 (не для v2)
    		  (Часть MEGAOS.bin прошивается, часть загружается)
    

    PS. Не забываем, что Mega EverDrive для разработчиков SMD-приложений предоставляет также следующий функционал:

    • Связь с внешней системой (ПК или другой USB-хост) через виртуальный COM-порт (на стороне хоста) и регистры в адресном пространстве на стороне SMD (необходимо включать режим SSF);
    • Возможность хранения контента на SD-карте Mega EverDrive (необходимо включать режим SSF) и его энергонезависимой памяти («на батарейке»);
    • Возможность использования адресного пространства памяти ROM картриджа Mega EverDrive как ОЗУ (необходимо включать режим SSF);

    (см. примеры разработчика)

    • Есть аппаратно-эмулируемый графический сопроцессор SVP (в режиме SVP недоступны регистры SSF, а вместе с этим и функционал EverDrive по работе с USB-соединением и пр.);
    • Есть аппаратно-эмулируемый синтезатор YM2413;
    • Есть сопроцессор умножения/деления чисел (MEGA.rbf до версии 3.03 включительно).

    PPS. Скомпиллированный, зазипованный экзешник: mega-usb.exe.zip

    Visit original content creator repository https://github.com/MiGeRA/Mega-EverDrive-Uploader
  • gas-deno-starter

    Gas Deno Starter

    The starter template for Google Apps Script by clasp and deno

    Getting started

    1. Install Deno

    How to install Deno

    2. Clone template

    Please click
    Use this template

    or

    Run on your terminal:

    git clone --depth=1 https://github.com/proudust/gas-deno-starter <your_project_name>
    cd <your_project_name>
    rm -rf .git

    3. Login @google/clasp

    Run on your terminal:

    deno run -A npm:@google/clasp@2.4.2 login

    After login, ~/.clasprc.json will be generated. If you want to deploy Google
    Apps Script from GitHub Actions, paste the contents of ~/.clasprc.json into
    your repository secrets with the name CLASPRC.

    4. Change Template Files

    .clasp.json

    What is Script ID ?

    {
      "scriptId": "<YOUR_SCRIPT_ID>",
      "rootDir": "dist"
    }

    appsscript.json

    What is appsscript.json ?

    {
      "timeZone": "<Your Time Zone>",
      "exceptionLogging": "STACKDRIVER",
      "runtimeVersion": "V8"
    }

    LICENSE

    MIT License
    
    Copyright (c) [Year] [Your Name]
    
    Permission is hereby granted, free of charge, to any person obtaining a copy

    5. Deploy your scripts

    Build and Deploy

    deno task deploy

    $ deno task deploy
    Task deploy deno task build && deno task build deploy
    Task build deno run --allow-env --allow-net --allow-read --allow-run --allow-write --unstable _build.ts
    Task build deno run --allow-env --allow-net --allow-read --allow-run --allow-write --unstable _build.ts "deploy"
    Warning: Not implemented: process.on("rejectionHandled")
    └─ dist/appsscript.json
    └─ dist/out.js
    Pushed 2 files.
    

    Build Only

    deno task build

    Dependencies

    Visit original content creator repository
    https://github.com/proudust/gas-deno-starter

  • play-use-any-sound

    Copyright (C) 2018-2020, 2022-2023 ZwerOxotnik <zweroxotnik@gmail.com>
    
    This project is licensed under the European Union Public License (EUPL)
    The license is available in the 23 official languages of the EU. The English version is included here.
    Please see https://joinup.ec.europa.eu/collection/eupl/eupl-text-11-12 for official translations of the other languages.
    
    EUPL Guidelines for users and developers: https://joinup.ec.europa.eu/collection/eupl/guidelines-users-and-developers
    
    -------------------------------------------------------------
    EUROPEAN UNION PUBLIC LICENCE v. 1.2
    EUPL © the European Union 2007, 2016
    
    This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined below) which is provided under the
    terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such
    use is covered by a right of the copyright holder of the Work).
    The Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following
    notice immediately following the copyright notice for the Work:
                              Licensed under the EUPL
    or has expressed by any other means his willingness to license under the EUPL.
    
    1.Definitions
    In this Licence, the following terms have the following meaning:
    — ‘The Licence’:this Licence.
    — ‘The Original Work’:the work or software distributed or communicated by the Licensor under this Licence, available
    as Source Code and also as Executable Code as the case may be.
    — ‘Derivative Works’:the works or software that could be created by the Licensee, based upon the Original Work or
    modifications thereof. This Licence does not define the extent of modification or dependence on the Original Work
    required in order to classify a work as a Derivative Work; this extent is determined by copyright law applicable in
    the country mentioned in Article 15.
    — ‘The Work’:the Original Work or its Derivative Works.
    — ‘The Source Code’:the human-readable form of the Work which is the most convenient for people to study and
    modify.
    — ‘The Executable Code’:any code which has generally been compiled and which is meant to be interpreted by
    a computer as a program.
    — ‘The Licensor’:the natural or legal person that distributes or communicates the Work under the Licence.
    — ‘Contributor(s)’:any natural or legal person who modifies the Work under the Licence, or otherwise contributes to
    the creation of a Derivative Work.
    — ‘The Licensee’ or ‘You’:any natural or legal person who makes any usage of the Work under the terms of the
    Licence.
    — ‘Distribution’ or ‘Communication’:any act of selling, giving, lending, renting, distributing, communicating,
    transmitting, or otherwise making available, online or offline, copies of the Work or providing access to its essential
    functionalities at the disposal of any other natural or legal person.
    
    2.Scope of the rights granted by the Licence
    The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, sublicensable licence to do the following, for
    the duration of copyright vested in the Original Work:
    — use the Work in any circumstance and for all usage,
    — reproduce the Work,
    — modify the Work, and make Derivative Works based upon the Work,
    — communicate to the public, including the right to make available or display the Work or copies thereof to the public
    and perform publicly, as the case may be, the Work,
    — distribute the Work or copies thereof,
    — lend and rent the Work or copies thereof,
    — sublicense rights in the Work or copies thereof.
    Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the
    applicable law permits so.
    In the countries where moral rights apply, the Licensor waives his right to exercise his moral right to the extent allowed
    by law in order to make effective the licence of the economic rights here above listed.
    The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to any patents held by the Licensor, to the
    extent necessary to make use of the rights granted on the Work under this Licence.
    
    3.Communication of the Source Code
    The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as
    Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with
    each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to
    the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to
    distribute or communicate the Work.
    
    4.Limitations on copyright
    Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the
    exclusive rights of the rights owners in the Work, of the exhaustion of those rights or of other applicable limitations
    thereto.
    
    5.Obligations of the Licensee
    The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the Licensee. Those
    obligations are the following:
    
    Attribution right: The Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to
    the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the
    Licence with every copy of the Work he/she distributes or communicates. The Licensee must cause any Derivative Work
    to carry prominent notices stating that the Work has been modified and the date of modification.
    
    Copyleft clause: If the Licensee distributes or communicates copies of the Original Works or Derivative Works, this
    Distribution or Communication will be done under the terms of this Licence or of a later version of this Licence unless
    the Original Work is expressly distributed only under this version of the Licence — for example by communicating
    ‘EUPL v. 1.2 only’. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the
    Work or Derivative Work that alter or restrict the terms of the Licence.
    
    Compatibility clause: If the Licensee Distributes or Communicates Derivative Works or copies thereof based upon both
    the Work and another work licensed under a Compatible Licence, this Distribution or Communication can be done
    under the terms of this Compatible Licence. For the sake of this clause, ‘Compatible Licence’ refers to the licences listed
    in the appendix attached to this Licence. Should the Licensee's obligations under the Compatible Licence conflict with
    his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail.
    
    Provision of Source Code: When distributing or communicating copies of the Work, the Licensee will provide
    a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available
    for as long as the Licensee continues to distribute or communicate the Work.
    Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names
    of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and
    reproducing the content of the copyright notice.
    
    6.Chain of Authorship
    The original Licensor warrants that the copyright in the Original Work granted hereunder is owned by him/her or
    licensed to him/her and that he/she has the power and authority to grant the Licence.
    Each Contributor warrants that the copyright in the modifications he/she brings to the Work are owned by him/her or
    licensed to him/her and that he/she has the power and authority to grant the Licence.
    Each time You accept the Licence, the original Licensor and subsequent Contributors grant You a licence to their contributions
    to the Work, under the terms of this Licence.
    
    7.Disclaimer of Warranty
    The Work is a work in progress, which is continuously improved by numerous Contributors. It is not a finished work
    and may therefore contain defects or ‘bugs’ inherent to this type of development.
    For the above reason, the Work is provided under the Licence on an ‘as is’ basis and without warranties of any kind
    concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or
    errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this
    Licence.
    This disclaimer of warranty is an essential part of the Licence and a condition for the grant of any rights to the Work.
    
    8.Disclaimer of Liability
    Except in the cases of wilful misconduct or damages directly caused to natural persons, the Licensor will in no event be
    liable for any direct or indirect, material or moral, damages of any kind, arising out of the Licence or of the use of the
    Work, including without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss
    of data or any commercial damage, even if the Licensor has been advised of the possibility of such damage. However,
    the Licensor will be liable under statutory product liability laws as far such laws apply to the Work.
    
    9.Additional agreements
    While distributing the Work, You may choose to conclude an additional agreement, defining obligations or services
    consistent with this Licence. However, if accepting obligations, You may act only on your own behalf and on your sole
    responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify,
    defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by
    the fact You have accepted any warranty or additional liability.
    
    10.Acceptance of the Licence
    The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ placed under the bottom of a window
    displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of
    applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms
    and conditions.
    Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You
    by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution
    or Communication by You of the Work or copies thereof.
    
    11.Information to the public
    In case of any Distribution or Communication of the Work by means of electronic communication by You (for example,
    by offering to download the Work from a remote location) the distribution channel or media (for example, a website)
    must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence
    and the way it may be accessible, concluded, stored and reproduced by the Licensee.
    
    12.Termination of the Licence
    The Licence and the rights granted hereunder will terminate automatically upon any breach by the Licensee of the terms
    of the Licence.
    Such a termination will not terminate the licences of any person who has received the Work from the Licensee under
    the Licence, provided such persons remain in full compliance with the Licence.
    
    13.Miscellaneous
    Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the
    Work.
    If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or
    enforceability of the Licence as a whole. Such provision will be construed or reformed so as necessary to make it valid
    and enforceable.
    The European Commission may publish other linguistic versions or new versions of this Licence or updated versions of
    the Appendix, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence.
    New versions of the Licence will be published with a unique version number.
    All linguistic versions of this Licence, approved by the European Commission, have identical value. Parties can take
    advantage of the linguistic version of their choice.
    
    14.Jurisdiction
    Without prejudice to specific agreement between parties,
    — any litigation resulting from the interpretation of this License, arising between the European Union institutions,
    bodies, offices or agencies, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice
    of the European Union, as laid down in article 272 of the Treaty on the Functioning of the European Union,
    — any litigation arising between other parties and resulting from the interpretation of this License, will be subject to
    the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business.
    
    15.Applicable Law
    Without prejudice to specific agreement between parties,
    — this Licence shall be governed by the law of the European Union Member State where the Licensor has his seat,
    resides or has his registered office,
    — this licence shall be governed by Belgian law if the Licensor has no seat, residence or registered office inside
    a European Union Member State.
    
    
                                                             Appendix
    
    ‘Compatible Licences’ according to Article 5 EUPL are:
    — GNU General Public License (GPL) v. 2, v. 3
    — GNU Affero General Public License (AGPL) v. 3
    — Open Software License (OSL) v. 2.1, v. 3.0
    — Eclipse Public License (EPL) v. 1.0
    — CeCILL v. 2.0, v. 2.1
    — Mozilla Public Licence (MPL) v. 2
    — GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
    — Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for works other than software
    — European Union Public Licence (EUPL) v. 1.1, v. 1.2
    — Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong Reciprocity (LiLiQ-R+).
    
    The European Commission may update this Appendix to later versions of the above licences without producing
    a new version of the EUPL, as long as they provide the rights granted in Article 2 of this Licence and protect the
    covered Source Code from exclusive appropriation.
    All other changes or additions to this Appendix require the production of a new EUPL version.

    Visit original content creator repository
    https://github.com/ZwerOxotnik/play-use-any-sound

  • Gencycler

    Gencycler

    latest version

    A Boilerplate free RecyclerView adapter. Gencycler uses annotation processing to analyze your code and generates the Recyclerview adapter for you, which means you only need to worry about your logic and not about the adapter

    • Written in Kotlin <3, for Kotlin and Java
    • Generates human readable code(plus comments, minus the human errors)
    • Clean and optimized code – Generates only what is required
    • Click / Long-Click listeners
    • Multi view types
    • Expandable items
    • Swipe to delete
    • Headers
    • Footers
    • Simple Drag and drop
    • Filter
    • Easily extensible
    • Custom variable naming
    • Parses your layout file so no more findViewById
    • Comes with useful Helpers
    • No runtime cost – everything happens at compile-time
    • Multi flavor support
    • Butterknife R2 support

    Gencycler works in compile time so no runtime performance impact,

    Gencycler will generated a readable multi view type RecyclerView Adapter with a thread-safe accessing mechanism. Gencycler eliminates The need to write all of the boilerplate code needed for writing an adapter and leaves you with only the bare minimum needed to write your business logic.

    Implement in your project

    Using maven

    Kotlin

     apply plugin: 'kotlin-kapt'
    
      repositories {
         maven { url "https://jitpack.io" }
      }
      dependencies {
            implementation "com.github.gilgoldzweig.Gencycler:gencycler:latest_version"
            kapt "com.github.gilgoldzweig.Gencycler:compiler:latest_version"
      }
    

    Java

    apply plugin: 'kotlin-android'
    
    repositories {
      maven { url "https://jitpack.io" }
    }
    
    dependencies {
         implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$latest_kotlin_version"
         implementation "com.github.gilgoldzweig.Gencycler:gencycler:latest_version"
         annotationProcessor "com.github.gilgoldzweig.Gencycler:compiler:latest_version"
    }
    

    How to use

    1. Implement your model

    Just create a class which implements the GencyclerModel and annotate it with @GencyclerViewHolder

    Each class represents a ViewHolder & Data model. In order to associate the class with a layout we place the layout id of what the item should look like inside the annotation as shown below.

    Kotlin

    @GencyclerViewHolder(R.layout.item_simple)  
    data class SimpleModel(val name: String, val description: String) : GencyclerModel
    

    Java

    @GencyclerViewHolder(R.layout.item_simple)  
    public class SimpleModel implements GencyclerModel {  
        private String name;  
        private String description;  
      
        public SimpleModel(String name, String description) {  
               this.name = name;
               this.description = description;
        }  
    }
    

    2. Implement your adapter

    Just create a class and annotate it with @GencyclerAdapter place every model you want the adapter to use inside the annotation as shown below.

    Kotlin – Single view type

    @GencyclerAdapter(SimpleModel::class)
    class SimpleAdapter
    

    Kotlin – Mutli view type

    @GencyclerAdapter(SimpleModel::class, AnotherModel::class) //for multiple view types just seperated each model by a comma 
    class SimpleAdapter
    

    Java – Single view type

    @GencyclerAdapter(SimpleModel.class)
    public class SimpleAdapter {}
    

    Java – Multi view type

    @GencyclerAdapter({SimpleModel.class, AnotherModel.class})  //for multiple view types just provide an array
    public class SimpleAdapter {}
    

    3. Compile

    Compile your project and when the compilation finishes your adapters and view holders will be generated.

    The generated adapter will be named Generated + Your adapter class name and will be an abstract class with a bind function for every model you provided The ViewHolder we be Generated and implemented automatically

    4. Implementing the generated adapter

    Now that we have the generated code all we need to do is implement it

    The generated adapter will require 3 parameters

    • context: Context | Used to inflate the layout of the ViewHolder

    • elements: MutableList with the type of the provided model or GencyclerModel when multiple models wer’e provided. Default: ArrayList() | Each element represents a Generated ViewHolder

    • updateUi: Boolean Default: true

      • The generated adapter comes with many helper methods (add, remove, etc…) each action will update the elements in the adapter but if updateUi is True the adapter will also run a UI Thread check and call the appropriate notify method of the adapter (notifyItemInserted, notifyItemRemoved, etc…) whenever one of those function is called

    And a onBind abstract function

    The complete adapter will look like this

    Kotlin

    @GencyclerAdapter(SimpleModel::class)
    class SimpleAdapter(context: Context, elements: ArrayList<SimpleModel>) : GeneratedSimpleAdapter(context, elements) {  
     
        	override fun onBindSimpleModelViewHolder(
            	simpleModelViewHolder: SimpleModelViewHolder, //Generated ViewHolder, all the views from your layout are here
            	simpleModel: SimpleModel, 
            	position: Int) { 
            	
                	//Your logic here
        }  
    }
    

    Java

    @GencyclerAdapter(SimpleModel.class)  
    public class SimpleAdapter extends GeneratedSimpleAdapter {  
      
        public SimpleAdapter(Context context, ArrayList<SimpleModel> elements) { 
            super(context, elements);  
        }  
      
        @Override  
        public void onBindSimpleModelViewHolder(
                    @NotNull SimpleModelViewHolder simpleModelViewHolder,
                    @NotNull SimpleModel simpleModel,
                    int position) {  
    
                        //Your logic here  
        }  
    }
    

    Advance/Extras

    Custom naming

    Gencycler provides renaming options to the adapter and the variables inside the ViewHolder

    Adapter

    By default the generated adapter will be named Generated + Your adapter name but you can select a custom name for your adapter by specifying it inside the @GencyclerAdapter as shown below

    Kotlin

    @GencyclerAdapter(SimpleModel::class, customName = "CustomNameAdapter")
    class SimpleAdapter
    

    Java

    @GencyclerAdapter(value = SimpleModel.class, customName = "CustomNameAdapter")
    public class SimpleAdapter {}
    

    Variables

    By default the processor turns the id of every view in the xml layout to variable name and converts it to lower camel-case

    You can change the names of the variables by specifying a naming adapter inside the @GencyclerViewHolder as shown below

    Kotlin

    @GencyclerViewHolder(R.layout.item_simple, NamingCase.NAMING_CASE_SNAKE)  
    data class SimpleModel(val name: String, val description: String) : GencyclerModel
    

    Java

    @GencyclerViewHolder(value = R.layout.java_profile_type, namingCase = NamingCase.NAMING_CASE_SNAKE)  
    public class SimpleModel implements GencyclerModel {  
        private String name;  
        private String description;  
      
        public SimpleModel(String name, String description) {  
            this.name = name;
            this.description = description;
        }  
    }
    

    You can choose between the following

    enum class NamingCase {  
        NAMING_CASE_NONE,  
        NAMING_CASE_CAMEL,  //Default
        NAMING_CASE_SNAKE  
    }
    

    Event listeners

    For now Genecycler supports two listeners but if you want to create one for yourself just create and send pull request

    Click / Long Click

    1. Annotate your adapter with @Clickable or @LongClickable

    To add listeners for item click all you need to do is annotate your adapter with @Clickable or @LongClickable (You can both at the same time) as shown below

    Kotlin

    @GencyclerAdapter(SimpleModel::class)
    @Clickable
    @LongClickable
    class SimpleAdapter
    

    Java

    @GencyclerAdapter(value = SimpleModel.class)
    @Clickable
    @LongClickable
    public class SimpleAdapter {}
    

    2. Compile

    Once the compilation completes an interface will be added to the generated adapter constructor

    • OnItemClickedListener<T> for @Clickable
    • OnItemLongClickedListener<T> for @LongClickable

    T a generic type Your model for single type GencyclerModel for multi view types

    Simple gestures(Drag and Drop, Swipe to delete)

    Create a new SimpleGesturesHelper and provide it your generated adapter

    Kotlin

    val gesturesHelper = SimpleGesturesHelper(adapter)
    
    gesturesHelper.setSwipeEnabled(enabled: Boolean, vararg directions: Int) //ItemTouchHelper.START or ItemTouchHelper.END
    gesturesHelper.setDragAndDropEnabled(enabled: Boolean, longPressOnly: Boolean = false)
    
    gesturesHelper.attachToRecyclerView(recyclerView)
    

    Java

    SimpleGesturesHelper gesturesHelper = new SimpleGesturesHelper(adapter);
    
    gesturesHelper.setSwipeEnabled(Boolean enabled, Integer... directions); //ItemTouchHelper.START or ItemTouchHelper.END
    
    gesturesHelper.setDragAndDropEnabled(Boolean enabled); //longPressOnly default: false
    gesturesHelper.setDragAndDropEnabled(Boolean enabled, Boolean longPressOnly);
    
    gesturesHelper.attachToRecyclerView(recyclerView);
    

    Filter

    Gencycler provides you with a way to filter your items in order to that you need to do the following

    1. Annotate your adapter with @Filterable

    Kotlin

    @GencyclerAdapter(SimpleModel::class)
    @Filterable
    class SimpleAdapter
    

    Java

    @GencyclerAdapter(value = SimpleModel.class)
    @Filterable
    public class SimpleAdapter {}
    

    2. Compile

    3. Implement the performFilter method

    Kotlin

    @GencyclerAdapter(SimpleModel::class)  
    @Filterable  
    class SimpleAdapter(context: Context, elements: ArrayList<SimpleModel>) : GeneratedSimpleAdapter(context, elements) {  
          
    	//other methods
         
    	override fun performFilter(constraint: CharSequence, simpleModel: SimpleModel): Boolean {  
    	    //return true if the item should be retained and false if the item should be removed.
    	}  
    }
    

    Java

    @GencyclerAdapter(SimpleModel::class)  
    @Filterable  
    class SimpleAdapter : GeneratedSimpleAdapter {  
          
    	//other methods
         
    	@Overrides 
      	public Boolean performFilter(CharSequence constraint, SimpleModel simpleModel) {  
      		//return true if the item should be retained and false if the item should be removed.
        }  
    }
    

    To filter the items, inside your Activity/Fragment call

    Call this in onQueryTextSubmit() & onQueryTextChange() when using SearchView
    

    Kotlin

    adapter.filter("yourSearchTerm")
    

    Java

    adapter.filter("yourSearchTerm");
    

    Custom view recycling

    Gencycler generates functions for binding and recycling of ViewHolders

    The amount of functions will be the same for binding and recycling functions

    Binding function are abstract because the system does not provide a default option Recycling on the other hand do have a default option which you should edit in order to improve performance

    The generated functions look as shown below

    Kotlin

    override fun onRecycledSimpleModelViewHolder(simpleModelViewHolder: SimpleModelViewHolder,
                                                 position: Int) {
                                                 
    	super.onRecycledSimpleModelViewHolder(simpleModelViewHolder, position) //remove this line
    	//apply your custom recycleing logic
    }
    

    Java

    @Override 
    public void onRecycledSimpleModelViewHolder(SimpleModelViewHolder simpleModelViewHolder,
                                                Integer position) {
                                                 
    	super.onRecycledSimpleModelViewHolder(simpleModelViewHolder, position); //remove this line
    	//apply your custom recycleing logic
    }
    

    Miscellaneous(Optional)

    Gencycler supports number of custom options regarding customized build/flavors All of the option are inputed as shown below

    android {
        //your project configuration
        defaultConfig {
            //your project default config
            
            //Add this section
            javaCompileOptions {
                annotationProcessorOptions {
                    arguments = [
                        "androidManifestFile": Providing specific file path to the manifest
                        "rClassPackage": Providing R class package - Just like when you do import but with the .R at the end (example: com.example.app.R = com.example.app)
                        "androidUseR2": true / false if you want to use Butterknife's R2 instead of R 
                        "resourcesFolder": In case you use multi flavor layouts you need to use getCurrentFlavor()
                    ]
                }
            }
        }
    }
    

    This only applies if you have duplicate layouts for multi flavors here is a function to get the current flavor

    Add the following function to your gradle file

    def getCurrentFlavor() {
    
    	Gradle gradle = getGradle()
    	Pattern pattern;
        
    	String taskRequest = gradle.getStartParameter().getTaskRequests().toString()
    
    	if (taskRequest.contains("assemble")) {
    		pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
    	} else {
    		pattern = Pattern.compile("generate(\\w+)(Release|Debug)")
    	}
    
    	Matcher matcher = pattern.matcher(taskRequest)
    
    	if (matcher.find()) {
    		return matcher.group(1).toLowerCase()
    	} else {
    		println "NO MATCH FOUND"
    		return "";
    	}
    }
    

    How it works

    I’m working on the blog post

    Contributing

    If you want to contribute to this project check if there are any open issues or just send a pull request and I’ll do my best to look at it

    License

    MIT License
    
    Copyright (c) 2018 Gil Goldzweig Goldbaum
    
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
    
    Visit original content creator repository https://github.com/gilgoldzweig/Gencycler