text:
package org.apache.amber;

/**
 * Identifier for the OAuth Authorization message parameter.
 *
 * @version $Id$
 */
public final class OAuthMessageParameter extends AbstractParameter<OAuthParameter> {

	/**
	 * @param key
	 * @param value
	 */
    public OAuthMessageParameter(OAuthParameter key, String value) {
        super(key, value);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int hashCode() {
        int result = INITIAL_ODD_NUMBER;
        result = MULTIPLIER_ODD_NUMBER * result + ((this.getKey() == null) ? 0 : this.getKey().hashCode());
        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (this.getClass() != obj.getClass()) {
            return false;
        }

        AbstractParameter<?> other = (AbstractParameter<?>) obj;

        if (this.getKey() == null) {
            if (other.getKey() != null) {
                return false;
            }
        } else if (!String.valueOf(this.getKey()).equals(String.valueOf(other.getKey()))) {
            return false;
        }

        return true;
    }

}


text:
import os
import sys
import subprocess
import threading

# Assumes meteor-1.5.jar is in the same directory as meteor.py.  Change as needed.
METEOR_JAR = 'meteor-1.5.jar'
# print METEOR_JAR

class Meteor:

    def __init__(self):
        self.meteor_cmd = ['java', '-jar', '-Xmx2G', METEOR_JAR, \
                '-', '-', '-stdio', '-l', 'en', '-norm']
        self.meteor_p = subprocess.Popen(self.meteor_cmd, \
                cwd=os.path.dirname(os.path.abspath(__file__)), \
                stdin=subprocess.PIPE, \
                stdout=subprocess.PIPE, \
                stderr=subprocess.PIPE)
        # Used to guarantee thread safety
        self.lock = threading.Lock()

    def compute_score(self, gts, res):
        assert(gts.keys() == res.keys())
        imgIds = gts.keys()
        scores = []

        eval_line = 'EVAL'
        self.lock.acquire()
        for i in imgIds:
            assert(len(res[i]) == 1)
            stat = self._stat(res[i][0], gts[i])
            eval_line += ' ||| {}'.format(stat)

        self.meteor_p.stdin.write('{}\n'.format(eval_line))
        for i in range(0,len(imgIds)):
            scores.append(float(self.meteor_p.stdout.readline().strip()))
        score = float(self.meteor_p.stdout.readline().strip())
        self.lock.release()

        return score, scores

    def method(self):
        return "METEOR"

    def _stat(self, hypothesis_str, reference_list):
        # SCORE ||| reference 1 words ||| reference n words ||| hypothesis words
        hypothesis_str = hypothesis_str.replace('|||','').replace('  ',' ')
        score_line = ' ||| '.join(('SCORE', ' ||| '.join(reference_list), hypothesis_str))
        self.meteor_p.stdin.write('{}\n'.format(score_line))
        return self.meteor_p.stdout.readline().strip()

    def _score(self, hypothesis_str, reference_list):
        self.lock.acquire()
        # SCORE ||| reference 1 words ||| reference n words ||| hypothesis words
        hypothesis_str = hypothesis_str.replace('|||','').replace('  ',' ')
        score_line = ' ||| '.join(('SCORE', ' ||| '.join(reference_list), hypothesis_str))
        self.meteor_p.stdin.write('{}\n'.format(score_line))
        stats = self.meteor_p.stdout.readline().strip()
        eval_line = 'EVAL ||| {}'.format(stats)
        # EVAL ||| stats
        self.meteor_p.stdin.write('{}\n'.format(eval_line))
        score = float(self.meteor_p.stdout.readline().strip())
        self.lock.release()
        return score

    def __exit__(self):
        self.lock.acquire()
        self.meteor_p.stdin.close()
        self.meteor_p.wait()
        self.lock.release()

redpajama_set_name: RedPajamaGithub


text:
@interface SXMainTabBarController : UITabBarController<SXtabBarDelegate>

@end


text:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using Minalear;
using Minalear.UI;
using OpenTK.Input;

namespace DongLife.Scenes
{
    public class EndScene : Scene
    {
        private bool goodEnding;
        private Texture2D background;
        private Font font;
        private string message;

        public EndScene(string sceneName, bool goodEnding, string endingText)
            : base(sceneName)
        {
            this.goodEnding = goodEnding;
            this.message = endingText;
        }

        public override void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(background, OpenTK.Vector2.Zero, OpenTK.Graphics.Color4.White);

            base.Draw(spriteBatch);
        }

        public override void LoadContent(ContentManager content)
        {
            font = new Font("Comic Sans MS", 24f);

            using (Bitmap bmp = new Bitmap(GameSettings.WindowWidth, GameSettings.WindowHeight))
            {
                using (Graphics gfx = Graphics.FromImage(bmp))
                {
                    if (goodEnding)
                        gfx.FillRectangle(Brushes.MediumPurple, 0, 0, bmp.Width, bmp.Height);
                    else
                        gfx.FillRectangle(Brushes.Crimson, 0, 0, bmp.Width, bmp.Height);

                    gfx.DrawString(
                        message, font, Brushes.White,
                        new RectangleF(40, 40, bmp.Width - 80, bmp.Height - 80),
                        new StringFormat(StringFormatFlags.MeasureTrailingSpaces)
                        { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
                }

                BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                background = new Texture2D(bmp.Width, bmp.Height, data.Scan0);
                bmp.UnlockBits(data);
            }

            base.LoadContent(content);
        }

        public override void UnloadContent()
        {
            font.Dispose();
            background.Dispose();

            base.UnloadContent();
        }

        public override void OnMouseDown(MouseButtonEventArgs e)
        {
            if (!(Manager as VNSceneManager).Transitioning)
                Manager.ChangeScene("MainMenuScene");

            base.OnMouseDown(e);
        }
    }
}


text:
'use strict';

// there has to be a better way to bootstrap package models for mocha tests
require('../../../server/models/character');

/**
 * Module dependencies.
 */
var should = require('should'),
    mongoose = require('mongoose'),
    Character = mongoose.model('Character');

//Globals
var character;

//The tests
describe('<Unit Test>', function() {
    describe('Model Character:', function() {
        beforeEach(function(done) {
            character = new Character({
                name: 'Character Name'
            });

            done();
        });

        describe('Method Save', function() {
            it('should be able to save without problems', function(done) {
                return character.save(function(err) {
                    should.not.exist(err);
                    done();
                });
            });

            it('should have set the default character data', function(done) {
                // check defaults
                character.should.have.property('hunger',0);
                character.should.have.property('health',100);
                character.should.have.property('age',0);
                character.should.have.property('strength',1);
                character.should.have.property('speed',1);
                done();
            });

            it('should show an error when try to save without name', function(done) {
                character.name = '';

                return character.save(function(err) {
                    should.exist(err);
                    done();
                });
            });

            it('should show an error when try to save a negative age', function(done) {
                character.age = -1;

                return character.save(function(err) {
                    should.exist(err);
                    done();
                });
            });

            it('should show an error when try to save an invalid health (too low)', function(done) {
                character.health = -1;

                return character.save(function(err) {
                    should.exist(err);
                    done();
                });
            });

            it('should show an error when try to save an invalid health (too high)', function(done) {
                character.health = 101;

                return character.save(function(err) {
                    should.exist(err);
                    done();
                });
            });

            it('should show an error when try to save an invalid speed (too low)', function(done) {
                character.speed =- 1;

                return character.save(function(err) {
                    should.exist(err);
                    done();
                });
            });

            it('should show an error when try to save an invalid speed (too high)', function(done) {
                character.speed = 101;

                return character.save(function(err) {
                    should.exist(err);
                    done();
                });
            });

            it('should show an error when try to save an invalid strength (too low)', function(done) {
                character.strength =- 1;

                return character.save(function(err) {
                    should.exist(err);
                    done();
                });
            });

            it('should show an error when try to save an invalid strength (too high)', function(done) {
                character.strength = 101;

                return character.save(function(err) {
                    should.exist(err);
                    done();
                });
            });

            it('should show an error when try to save an invalid hunger (too low)', function(done) {
                character.hunger =- 1;

                return character.save(function(err) {
                    should.exist(err);
                    done();
                });
            });

            it('should show an error when try to save an invalid hunger (too high)', function(done) {
                character.hunger = 101;

                return character.save(function(err) {
                    should.exist(err);
                    done();
                });
            });

            it('should show an error when try to save an invalid locationx (too low)', function(done) {
                character.locationx =- 1;

                return character.save(function(err) {
                    should.exist(err);
                    done();
                });
            });

            it('should show an error when try to save an invalid locationy (too low)', function(done) {
                character.locationy = -1;

                return character.save(function(err) {
                    should.exist(err);
                    done();
                });
            });

        });

        afterEach(function(done) {
            character.remove();
            done();
        });
    });
});


text:
package jp.gr.java_conf.kgd.example.blog.collections.iterable.randomaccess;

import jp.gr.java_conf.kgd.example.blog.collections.iterable.bidirectional.BidirectionalInsertInputIterable;
import jp.gr.java_conf.kgd.example.blog.collections.iterator.variation.randomaccess.RandomAccessInsertInputIterator;

public interface RandomAccessInsertInputIterable<T> extends RandomAccessInputIterable<T>, BidirectionalInsertInputIterable<T> {

    @Override
    RandomAccessInsertInputIterator<T> firstIterator();

    @Override
    RandomAccessInsertInputIterator<T> lastIterator();
}


text:
<?php
namespace Aliyun\Core\Exceptions;

class ClientException extends \Exception
{
    private $errorCode;

    private $errorMessage;

    private $errorType;

    public function  __construct($errorMessage, $errorCode)
    {
        parent::__construct($errorMessage);
        $this->errorMessage = $errorMessage;
        $this->errorCode    = $errorCode;
        $this->setErrorType("Client");
    }

    public function getErrorCode()
    {
        return $this->errorCode;
    }

    public function setErrorCode($errorCode)
    {
        $this->errorCode = $errorCode;
    }

    public function getErrorMessage()
    {
        return $this->errorMessage;
    }

    public function setErrorMessage($errorMessage)
    {
        $this->errorMessage = $errorMessage;
    }

    public function getErrorType()
    {
        return $this->errorType;
    }

    public function setErrorType($errorType)
    {
        $this->errorType = $errorType;
    }
}


text:
#pragma once
#include <gl\glew.h>
class Shader
{
public:
	Shader();

	~Shader();
	/*
	loads the shaders from a path
	*/
	GLuint LoadShaders(const char * vertex_file_path, const char * fragment_file_path);
	/*
	loads the shaders from a source.
	*/
	GLuint LoadShadersFromSource(const char* vertexSource, const char* fragmentSource);
};


text:
    overflow: hidden;
    display: block;
    font-family: inherit;
    font-size: 42px;
    width: 320px;
    color: white;
    background-color: darkred;
    padding: 1px;
    margin-top: 120px;
    border: 4px dashed red;
    border-radius: 16px;
    outline: none;
    cursor: pointer;
}

#delete > div{
    display: inline-block;
    position: relative;
    left: 0px;
    top: 10px;
}

#delete > img{
    width: 80px;
    height: 80px;
    float: left;
}

#delete:hover{
    background-color: white;
    border-style: solid;
    color: black;
}


text:
extern HINSTANCE self_instance;

#pragma pack(push, 1)
struct RemoteThreadArgs
{
    FARPROC LoadLibraryW; // 0
    FARPROC GetProcAddress; // 4
    FARPROC MessageBoxW; // 8
    wchar_t *library_name; // c
    char *proc_name; // 10
    wchar_t *error; // 14
    wchar_t *load_library_name; // 18
    wchar_t *get_proc_address_name; // 1c
    FARPROC FreeLibrary; // 20
};
#pragma pack(pop)

/// Allocates small piece of code and data in process' address space, which can used called with
/// CreateRemoteThread. The code loads this .dll and calls Initialize()
/// Returns tuple (code, param), should VirtualFreeEx code after using (param is on same block)
tuple<void *, void *> CreateInjectCode(HANDLE process)
{
    // The assembly is written as uint8_t array to make it work easily across different compilers
    const uint8_t assembly[] = {
        //0xeb, 0xfe,             // infloop for debugging
        0x8b, 0x5c, 0xe4, 0x04, // mov ebx, [esp + 4] (arg struct)
        0xff, 0x73, 0x0c,       // push dword [ebx + c] (lib name)
        0xff, 0x13,             // call dword [ebx + 0] (LoadLibraryW)
        0x85, 0xc0,             // test eax, eax
        0x75, 0x12,             // jne load_ok
        0x6a, 0x00,             // push 0
        0xff, 0x73, 0x18,       // push dword [ebx + 18] (L"LoadLibraryW failed")
        0xff, 0x73, 0x14,       // push dword [ebx + 14] (L"Error")
        0x6a, 0x00,             // push 0
        0xff, 0x53, 0x08,       // call dword [ebx + 8] (MessageBoxW)
        0x31, 0xc0,             // xor eax, eax
        0xc2, 0x04, 0x00,       // ret 4
        // load_ok:
        0x89, 0xc6,             // mov esi, eax
        0xff, 0x73, 0x10,       // push dword [ebx + 10] (proc name)
        0x50,                   // push eax
        0xff, 0x53, 0x04,       // call dword [ebx + 4] (GetProcAddress)
        0x85, 0xc0,             // test eax, eax
        0x75, 0x16,             // jne proc_ok
        0x6a, 0x00,             // push 0
        0xff, 0x73, 0x1c,       // push dword [ebx + 1c] (L"GetProcAddress failed")
        0xff, 0x73, 0x14,       // push dword [ebx + 14] (L"Error")
        0x6a, 0x00,             // push 0
        0xff, 0x53, 0x08,       // call dword [ebx + 8] (MessageBoxW)
        0x56,                   // push esi
        0xff, 0x53, 0x20,       // call dword [ebx + 20] (FreeLibrary)
        0x31, 0xc0,             // xor eax, eax
        0xc2, 0x04, 0x00,       // ret 4
        // proc_ok:
        0xff, 0xd0,             // call eax
        0x31, 0xc0,             // xor eax, eax
        0xc2, 0x04, 0x00,       // ret 4
    };
    int asm_len = sizeof assembly;
    wchar_t library_name[MAX_PATH];
    int lib_name_len = GetModuleFileNameW(self_instance, library_name, MAX_PATH);
    if (lib_name_len == 0 || lib_name_len == MAX_PATH)
    {
        MessageBoxW(0, L"GetModuleFileNameW failed", L"Limit plugin", 0);
        return make_tuple(nullptr, nullptr);
    }
    lib_name_len = (lib_name_len + 1) * sizeof(wchar_t);
    const char *proc_name = "Initialize";
    int proc_name_len = strlen(proc_name) + 1;
    const wchar_t *error = L"Limit plugin error";
    int error_len = (wcslen(error) + 1) * sizeof(wchar_t);
    const wchar_t *load_library_error = L"LoadLibraryW failed";
    int load_library_error_len = (wcslen(load_library_error) + 1) * sizeof(wchar_t);
    const wchar_t *get_proc_address_error = L"GetProcAddress failed";
    int get_proc_address_error_len = (wcslen(get_proc_address_error) + 1) * sizeof(wchar_t);

    auto kernel32 = LoadLibraryW(L"kernel32");
    auto user32 = LoadLibraryW(L"user32");
    RemoteThreadArgs args = {
        GetProcAddress(kernel32, "LoadLibraryW"),
        GetProcAddress(kernel32, "GetProcAddress"),
        GetProcAddress(user32, "MessageBoxW"),
        nullptr,
        nullptr,
        nullptr,
        nullptr,
        nullptr,
        GetProcAddress(kernel32, "FreeLibrary"),
    };
    FreeLibrary(kernel32);
    FreeLibrary(user32);

    void *memory = VirtualAllocEx(process, NULL, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    if (memory == NULL)
    {
        MessageBoxW(0, L"VirtualAllocEx failed", L"Limit plugin", 0);
        return make_tuple(nullptr, nullptr);
    }

    uintptr_t data_pos = (uintptr_t)memory + asm_len + sizeof(RemoteThreadArgs);
    args.library_name = (wchar_t *)data_pos;
    data_pos += lib_name_len;
    args.proc_name = (char *)data_pos;
    data_pos += proc_name_len;
    args.error = (wchar_t *)data_pos;
    data_pos += error_len;
    args.load_library_name = (wchar_t *)data_pos;
    data_pos += load_library_error_len;
    args.get_proc_address_name = (wchar_t *)data_pos;
    data_pos += get_proc_address_error_len;

#define CheckWriteProcessMemoryError(s) if (s == 0)\
        { MessageBoxW(0, L"WriteProcessMemory failed", L"Limit plugin", 0); return make_tuple(nullptr, nullptr); }
    data_pos = (uintptr_t)memory;
    auto result = WriteProcessMemory(process, (void *)data_pos, assembly, asm_len, NULL);
    CheckWriteProcessMemoryError(result);
    data_pos += asm_len;
    result = WriteProcessMemory(process, (void *)data_pos, &args, sizeof(RemoteThreadArgs), NULL);
    CheckWriteProcessMemoryError(result);
    data_pos += sizeof(RemoteThreadArgs);
    result = WriteProcessMemory(process, (void *)data_pos, library_name, lib_name_len, NULL);
    CheckWriteProcessMemoryError(result);
    data_pos += lib_name_len;
    result = WriteProcessMemory(process, (void *)data_pos, proc_name, proc_name_len, NULL);
    CheckWriteProcessMemoryError(result);
    data_pos += proc_name_len;
    result = WriteProcessMemory(process, (void *)data_pos, error, error_len, NULL);
    CheckWriteProcessMemoryError(result);
    data_pos += error_len;
    result = WriteProcessMemory(process, (void *)data_pos, load_library_error, load_library_error_len, NULL);
    CheckWriteProcessMemoryError(result);
    data_pos += load_library_error_len;
    result = WriteProcessMemory(process, (void *)data_pos, get_proc_address_error, get_proc_address_error_len, NULL);
    CheckWriteProcessMemoryError(result);
#undef CheckWriteProcessMemoryError

    DWORD old_protect;
    result = VirtualProtectEx(process, memory, 0x1000, PAGE_EXECUTE_READ, &old_protect);
    if (result == 0)
    {
        // Ideally should not matter..
    }
    return make_tuple(memory, (void *)((uintptr_t)memory + asm_len));
}

/// Really sketchy function to inject this plugin to another process
BOOL InjectToProcess(HANDLE process)
{
    auto tuple = CreateInjectCode(process);
    void *code = std::get<0>(tuple);
    void *param = std::get<1>(tuple);
    if (code == nullptr || param == nullptr)
        return FALSE;

    HANDLE thread = CreateRemoteThread(process, NULL, 0, (LPTHREAD_START_ROUTINE)code, param, 0, NULL);
    if (thread == NULL)
    {
        MessageBoxW(0, L"CreateRemoteThread failed", L"Limits plugin", 0);
        return FALSE;
    }
    auto result = WaitForSingleObject(thread, 25000);
    CloseHandle(thread);
    if (result == WAIT_TIMEOUT)
    {
        MessageBoxW(0, L"Timeout while waiting for the inject thread", L"Limits plugin", 0);
        // Return TRUE anyways, just leaks the VirtualAllocEx memory (and may crash if didn't patch everything yet)
        return TRUE;
    }

    VirtualFreeEx(process, code, 0, MEM_RELEASE);
    if (result != WAIT_OBJECT_0)
    {
        MessageBoxW(0, L"WaitForSingleObject failed", L"Limits plugin", 0);
        return FALSE;
    }
    return TRUE;
}

/// Bwlauncher plugin entry point
extern "C" BOOL ApplyPatchSuspended(HANDLE process, DWORD process_id)
{
    return InjectToProcess(process);
}

/// Bwlauncher plugin post window creation hook
extern "C" BOOL ApplyPatch(HANDLE process, DWORD process_id)
{
    return TRUE;
}

struct ExchangeData
{
    int iPluginAPI;
    int iStarCraftBuild;
    BOOL bNotSCBWmodule;                //Inform user that closing BWL will shut down your plugin
    BOOL bConfigDialog;                 //Is Configurable
};

/// Bwlauncher plugin query
extern "C" void GetPluginAPI(ExchangeData *data)
{
    data->iPluginAPI = 4;
    data->iStarCraftBuild = 13; // 1.16.1
    data->bNotSCBWmodule = FALSE;
    data->bConfigDialog = FALSE;
}

/// Bwlauncher info query
extern "C" void GetData(char *name, char *description, char *url)
{
    // How large are these buffers??
    strcpy(name, "Limits plugin");
    strcpy(description, "Removes unit/bullet/etc limits from the game.\r\n\
Every player needs to be using this plugin for it to work in multiplayer \
and there is no compatibility with vanilla Starcraft.");
    strcpy(url, "");
}


text:
import Roulette from './Roulette'

export default Roulette


text:
from collections import defaultdict
import sys
import django
django.setup()

from busshaming.models import Agency, RouteDate, Feed

FEED_SLUG = 'nsw-buses'

MIN_TRIPS = 500
MIN_RT_ENTRIES = 0

def main(is_best, verylate):
    feed = Feed.objects.get(slug=FEED_SLUG)
    routedates = defaultdict(list)
    for rd in RouteDate.objects.filter(route__feed=feed).prefetch_related('route').all():
        routedates[rd.route.agency.name].append(rd)

    results = []
    for agency_name in routedates:
        rds = routedates[agency_name]
        num_trips = sum([rd.num_trips for rd in rds])
        if num_trips == 0:
            continue
        total_ontime = sum([rd.trip_ontime_count for rd in rds])
        total_verylate = sum([rd.trip_verylate_count for rd in rds])
        result = [
            agency_name,
            num_trips,
            100 * total_ontime / num_trips,
            100 * total_verylate / num_trips,
        ]
        results.append(result)

    if verylate:
        results.sort(key=lambda x: x[3], reverse=not best)
    else:
        results.sort(key=lambda x: x[2], reverse=best)

    for i, res in enumerate(results):
        desc = res[0]
        out = f'{i+1}\t{res[1]}\t{res[2]:.2f}\t{res[3]:.2f}\t' + desc
        print(out)

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print(f'Usage: {sys.argv[0]} <best|worst> <ontime|verylate>')
        sys.exit(1)

    best = sys.argv[1] == 'best'
    verylate = sys.argv[2] == 'verylate'

    main(best, verylate)


text:
import path from 'path'
import {
  summaryLogger,
} from '@pnpm/core-loggers'
import PnpmError from '@pnpm/error'
import { getContextForSingleImporter } from '@pnpm/get-context'
import { linkBinsOfPackages } from '@pnpm/link-bins'
import {
  getLockfileImporterId,
  ProjectSnapshot,
  writeCurrentLockfile,
  writeLockfiles,
} from '@pnpm/lockfile-file'
import logger, { streamParser } from '@pnpm/logger'
import {
  getPref,
  getSpecFromPackageManifest,
  guessDependencyType,
  PackageSpecObject,
  updateProjectManifestObject,
} from '@pnpm/manifest-utils'
import { prune } from '@pnpm/modules-cleaner'
import { pruneSharedLockfile } from '@pnpm/prune-lockfile'
import readProjectManifest from '@pnpm/read-project-manifest'
import { symlinkDirectRootDependency } from '@pnpm/symlink-dependency'
import {
  DependenciesField,
  DEPENDENCIES_FIELDS,
  DependencyManifest,
  ProjectManifest,
} from '@pnpm/types'
import normalize from 'normalize-path'
import pathAbsolute from 'path-absolute'
import clone from 'ramda/src/clone'
import {
  extendOptions,
  LinkOptions,
} from './options'

type LinkFunctionOptions = LinkOptions & {
  linkToBin?: string
  dir: string
}

export { LinkFunctionOptions }

export default async function link (
  linkFromPkgs: Array<{alias: string, path: string} | string>,
  destModules: string,
  maybeOpts: LinkFunctionOptions
) {
  const reporter = maybeOpts?.reporter
  if ((reporter != null) && typeof reporter === 'function') {
    streamParser.on('data', reporter)
  }
  const opts = await extendOptions(maybeOpts)
  const ctx = await getContextForSingleImporter(opts.manifest, {
    ...opts,
    extraBinPaths: [], // ctx.extraBinPaths is not needed, so this is fine
  }, true)

  const importerId = getLockfileImporterId(ctx.lockfileDir, opts.dir)
  const currentLockfile = clone(ctx.currentLockfile)
  const linkedPkgs: Array<{path: string, manifest: DependencyManifest, alias: string}> = []
  const specsToUpsert = [] as PackageSpecObject[]

  for (const linkFrom of linkFromPkgs) {
    let linkFromPath: string
    let linkFromAlias: string | undefined
    if (typeof linkFrom === 'string') {
      linkFromPath = linkFrom
    } else {
      linkFromPath = linkFrom.path
      linkFromAlias = linkFrom.alias
    }
    const { manifest } = await readProjectManifest(linkFromPath) as { manifest: DependencyManifest }
    if (typeof linkFrom === 'string' && manifest.name === undefined) {
      throw new PnpmError('INVALID_PACKAGE_NAME', `Package in ${linkFromPath} must have a name field to be linked`)
    }

    specsToUpsert.push({
      alias: manifest.name,
      pref: getPref(manifest.name, manifest.name, manifest.version, {
        pinnedVersion: opts.pinnedVersion,
      }),
      saveType: (opts.targetDependenciesField ?? (ctx.manifest && guessDependencyType(manifest.name, ctx.manifest))) as DependenciesField,
    })

    const packagePath = normalize(path.relative(opts.dir, linkFromPath))
    const addLinkOpts = {
      linkedPkgName: linkFromAlias ?? manifest.name,
      manifest: ctx.manifest,
      packagePath,
    }
    addLinkToLockfile(ctx.currentLockfile.importers[importerId], addLinkOpts)
    addLinkToLockfile(ctx.wantedLockfile.importers[importerId], addLinkOpts)

    linkedPkgs.push({
      alias: linkFromAlias ?? manifest.name,
      manifest,
      path: linkFromPath,
    })
  }

  const updatedCurrentLockfile = pruneSharedLockfile(ctx.currentLockfile)

  const warn = (message: string) => logger.warn({ message, prefix: opts.dir })
  const updatedWantedLockfile = pruneSharedLockfile(ctx.wantedLockfile, { warn })

  await prune(
    [
      {
        binsDir: opts.binsDir,
        id: importerId,
        modulesDir: ctx.modulesDir,
        rootDir: opts.dir,
      },
    ],
    {
      currentLockfile,
      hoistedDependencies: ctx.hoistedDependencies,
      hoistedModulesDir: (opts.hoistPattern != null) ? ctx.hoistedModulesDir : undefined,
      include: ctx.include,
      lockfileDir: opts.lockfileDir,
      publicHoistedModulesDir: (opts.publicHoistPattern != null) ? ctx.rootModulesDir : undefined,
      registries: ctx.registries,
      skipped: ctx.skipped,
      storeController: opts.storeController,
      virtualStoreDir: ctx.virtualStoreDir,
      wantedLockfile: updatedCurrentLockfile,
    }
  )

  // Linking should happen after removing orphans
  // Otherwise would've been removed
  for (const { alias, manifest, path } of linkedPkgs) {
    // TODO: cover with test that linking reports with correct dependency types
    const stu = specsToUpsert.find((s) => s.alias === manifest.name)
    await symlinkDirectRootDependency(path, destModules, alias, {
      fromDependenciesField: stu?.saveType ?? opts.targetDependenciesField,
      linkedPackage: manifest,
      prefix: opts.dir,
    })
  }

  const linkToBin = maybeOpts?.linkToBin ?? path.join(destModules, '.bin')
  await linkBinsOfPackages(linkedPkgs.map((p) => ({ manifest: p.manifest, location: p.path })), linkToBin, {
    warn: (message: string) => logger.info({ message, prefix: opts.dir }),
  })

  let newPkg!: ProjectManifest
  if (opts.targetDependenciesField) {
    newPkg = await updateProjectManifestObject(opts.dir, opts.manifest, specsToUpsert)
    for (const { alias } of specsToUpsert) {
      updatedWantedLockfile.importers[importerId].specifiers[alias] = getSpecFromPackageManifest(newPkg, alias)
    }
  } else {
    newPkg = opts.manifest
  }
  const lockfileOpts = { forceSharedFormat: opts.forceSharedLockfile }
  if (opts.useLockfile) {
    await writeLockfiles({
      currentLockfile: updatedCurrentLockfile,
      currentLockfileDir: ctx.virtualStoreDir,
      wantedLockfile: updatedWantedLockfile,
      wantedLockfileDir: ctx.lockfileDir,
      ...lockfileOpts,
    })
  } else {
    await writeCurrentLockfile(ctx.virtualStoreDir, updatedCurrentLockfile, lockfileOpts)
  }

  summaryLogger.debug({ prefix: opts.dir })

  if ((reporter != null) && typeof reporter === 'function') {
    streamParser.removeListener('data', reporter)
  }

  return newPkg
}

function addLinkToLockfile (
  projectSnapshot: ProjectSnapshot,
  opts: {
    linkedPkgName: string
    packagePath: string
    manifest?: ProjectManifest
  }
) {
  const id = `link:${opts.packagePath}`
  let addedTo: DependenciesField | undefined
  for (const depType of DEPENDENCIES_FIELDS) {
    if (!addedTo && opts.manifest?.[depType]?.[opts.linkedPkgName]) {
      addedTo = depType
      projectSnapshot[depType] = projectSnapshot[depType] ?? {}
      projectSnapshot[depType]![opts.linkedPkgName] = id
    } else if (projectSnapshot[depType] != null) {
      delete projectSnapshot[depType]![opts.linkedPkgName]
    }
  }

  // package.json might not be available when linking to global
  if (opts.manifest == null) return

  const availableSpec = getSpecFromPackageManifest(opts.manifest, opts.linkedPkgName)
  if (availableSpec) {
    projectSnapshot.specifiers[opts.linkedPkgName] = availableSpec
  } else {
    delete projectSnapshot.specifiers[opts.linkedPkgName]
  }
}

export async function linkFromGlobal (
  pkgNames: string[],
  linkTo: string,
  maybeOpts: LinkOptions & {globalDir: string}
) {
  const reporter = maybeOpts?.reporter
  if ((reporter != null) && typeof reporter === 'function') {
    streamParser.on('data', reporter)
  }
  const opts = await extendOptions(maybeOpts)
  const globalPkgPath = pathAbsolute(maybeOpts.globalDir)
  const linkFromPkgs = pkgNames.map((pkgName) => path.join(globalPkgPath, 'node_modules', pkgName))
  const newManifest = await link(linkFromPkgs, path.join(linkTo, 'node_modules'), opts)

  if ((reporter != null) && typeof reporter === 'function') {
    streamParser.removeListener('data', reporter)
  }

  return newManifest
}

export async function linkToGlobal (
  linkFrom: string,
  maybeOpts: LinkOptions & {
    globalBin: string
    globalDir: string
  }
) {
  const reporter = maybeOpts?.reporter
  if ((reporter != null) && typeof reporter === 'function') {
    streamParser.on('data', reporter)
  }
  maybeOpts.lockfileDir = maybeOpts.lockfileDir ?? maybeOpts.globalDir
  const opts = await extendOptions(maybeOpts)
  const globalPkgPath = pathAbsolute(maybeOpts.globalDir)
  const newManifest = await link([linkFrom], path.join(globalPkgPath, 'node_modules'), {
    ...opts,
    dir: maybeOpts.globalDir,
    linkToBin: maybeOpts.globalBin,
  })

  if ((reporter != null) && typeof reporter === 'function') {
    streamParser.removeListener('data', reporter)
  }

  return newManifest
}


text:
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"

/** @addtogroup STM32F1xx_HAL_Driver
  * @{
  */

/** @defgroup RTC RTC
  * @brief RTC HAL module driver
  * @{
  */

#ifdef HAL_RTC_MODULE_ENABLED

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup RTC_Private_Constants RTC Private Constants
  * @{
  */
#define RTC_ALARM_RESETVALUE_REGISTER    (uint16_t)0xFFFF
#define RTC_ALARM_RESETVALUE             0xFFFFFFFFU

/**
  * @}
  */

/* Private macro -------------------------------------------------------------*/
/** @defgroup RTC_Private_Macros RTC Private Macros
  * @{
  */
/**
  * @}
  */

/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup RTC_Private_Functions RTC Private Functions
  * @{
  */
static uint32_t           RTC_ReadTimeCounter(RTC_HandleTypeDef* hrtc);
static HAL_StatusTypeDef  RTC_WriteTimeCounter(RTC_HandleTypeDef* hrtc, uint32_t TimeCounter);
static uint32_t           RTC_ReadAlarmCounter(RTC_HandleTypeDef* hrtc);
static HAL_StatusTypeDef  RTC_WriteAlarmCounter(RTC_HandleTypeDef* hrtc, uint32_t AlarmCounter);
static HAL_StatusTypeDef  RTC_EnterInitMode(RTC_HandleTypeDef* hrtc);
static HAL_StatusTypeDef  RTC_ExitInitMode(RTC_HandleTypeDef* hrtc);
static uint8_t            RTC_ByteToBcd2(uint8_t Value);
static uint8_t            RTC_Bcd2ToByte(uint8_t Value);
static uint8_t            RTC_IsLeapYear(uint16_t nYear);
static void               RTC_DateUpdate(RTC_HandleTypeDef* hrtc, uint32_t DayElapsed);
static uint8_t            RTC_WeekDayNum(uint32_t nYear, uint8_t nMonth, uint8_t nDay);

/**
  * @}
  */

/* Private functions ---------------------------------------------------------*/
/** @defgroup RTC_Exported_Functions RTC Exported Functions
  * @{
  */

/** @defgroup RTC_Exported_Functions_Group1 Initialization and de-initialization functions
 *  @brief    Initialization and Configuration functions
 *
@verbatim
 ===============================================================================
              ##### Initialization and de-initialization functions #####
 ===============================================================================
   [..] This section provides functions allowing to initialize and configure the
         RTC Prescaler (Asynchronous), disable RTC registers Write protection,
         enter and exit the RTC initialization mode,
         RTC registers synchronization check and reference clock detection enable.
         (#) The RTC Prescaler should be programmed to generate the RTC 1Hz time base.
         (#) All RTC registers are Write protected. Writing to the RTC registers
             is enabled by setting the CNF bit in the RTC_CRL register.
         (#) To read the calendar after wakeup from low power modes (Standby or Stop)
             the software must first wait for the RSF bit (Register Synchronized Flag)
             in the RTC_CRL register to be set by hardware.
             The HAL_RTC_WaitForSynchro() function implements the above software
             sequence (RSF clear and RSF check).

@endverbatim
  * @{
  */

/**
  * @brief  Initializes the RTC peripheral
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc)
{
  uint32_t prescaler = 0U;
  /* Check input parameters */
  if(hrtc == NULL)
  {
     return HAL_ERROR;
  }

  /* Check the parameters */
  assert_param(IS_RTC_ALL_INSTANCE(hrtc->Instance));
  assert_param(IS_RTC_CALIB_OUTPUT(hrtc->Init.OutPut));
  assert_param(IS_RTC_ASYNCH_PREDIV(hrtc->Init.AsynchPrediv));

  if(hrtc->State == HAL_RTC_STATE_RESET)
  {
    /* Allocate lock resource and initialize it */
    hrtc->Lock = HAL_UNLOCKED;

    /* Initialize RTC MSP */
    HAL_RTC_MspInit(hrtc);
  }

  /* Set RTC state */
  hrtc->State = HAL_RTC_STATE_BUSY;

  /* Waiting for synchro */
  if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK)
  {
    /* Set RTC state */
    hrtc->State = HAL_RTC_STATE_ERROR;

    return HAL_ERROR;
  }

  /* Set Initialization mode */
  if(RTC_EnterInitMode(hrtc) != HAL_OK)
  {
    /* Set RTC state */
    hrtc->State = HAL_RTC_STATE_ERROR;

    return HAL_ERROR;
  }
  else
  {
    /* Clear Flags Bits */
    CLEAR_BIT(hrtc->Instance->CRL, (RTC_FLAG_OW | RTC_FLAG_ALRAF | RTC_FLAG_SEC));

    if(hrtc->Init.OutPut != RTC_OUTPUTSOURCE_NONE)
    {
      /* Disable the selected Tamper pin */
      CLEAR_BIT(BKP->CR, BKP_CR_TPE);
    }

    /* Set the signal which will be routed to RTC Tamper pin*/
    MODIFY_REG(BKP->RTCCR, (BKP_RTCCR_CCO | BKP_RTCCR_ASOE | BKP_RTCCR_ASOS), hrtc->Init.OutPut);

    if (hrtc->Init.AsynchPrediv != RTC_AUTO_1_SECOND)
    {
      /* RTC Prescaler provided directly by end-user*/
      prescaler = hrtc->Init.AsynchPrediv;
    }
    else
    {
      /* RTC Prescaler will be automatically calculated to get 1 second timebase */
      /* Get the RTCCLK frequency */
      prescaler = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_RTC);

      /* Check that RTC clock is enabled*/
      if (prescaler == 0U)
      {
        /* Should not happen. Frequency is not available*/
        hrtc->State = HAL_RTC_STATE_ERROR;
        return HAL_ERROR;
      }
      else
      {
        /* RTC period = RTCCLK/(RTC_PR + 1) */
        prescaler = prescaler - 1U;
      }
    }

    /* Configure the RTC_PRLH / RTC_PRLL */
    MODIFY_REG(hrtc->Instance->PRLH, RTC_PRLH_PRL, (prescaler >> 16U));
    MODIFY_REG(hrtc->Instance->PRLL, RTC_PRLL_PRL, (prescaler & RTC_PRLL_PRL));

    /* Wait for synchro */
    if(RTC_ExitInitMode(hrtc) != HAL_OK)
    {
      hrtc->State = HAL_RTC_STATE_ERROR;

      return HAL_ERROR;
    }

    /* Initialize date to 1st of January 2000 */
    hrtc->DateToUpdate.Year = 0x00U;
    hrtc->DateToUpdate.Month = RTC_MONTH_JANUARY;
    hrtc->DateToUpdate.Date = 0x01U;

    /* Set RTC state */
    hrtc->State = HAL_RTC_STATE_READY;

    return HAL_OK;
  }
}

/**
  * @brief  DeInitializes the RTC peripheral
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @note   This function does not reset the RTC Backup Data registers.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc)
{
  /* Check input parameters */
  if(hrtc == NULL)
  {
     return HAL_ERROR;
  }

  /* Check the parameters */
  assert_param(IS_RTC_ALL_INSTANCE(hrtc->Instance));

  /* Set RTC state */
  hrtc->State = HAL_RTC_STATE_BUSY;

  /* Set Initialization mode */
  if(RTC_EnterInitMode(hrtc) != HAL_OK)
  {
    /* Set RTC state */
    hrtc->State = HAL_RTC_STATE_ERROR;

    /* Release Lock */
    __HAL_UNLOCK(hrtc);

    return HAL_ERROR;
  }
  else
  {
    CLEAR_REG(hrtc->Instance->CNTL);
    CLEAR_REG(hrtc->Instance->CNTH);
    WRITE_REG(hrtc->Instance->PRLL, 0x00008000U);
    CLEAR_REG(hrtc->Instance->PRLH);

    /* Reset All CRH/CRL bits */
    CLEAR_REG(hrtc->Instance->CRH);
    CLEAR_REG(hrtc->Instance->CRL);

    if(RTC_ExitInitMode(hrtc) != HAL_OK)
    {
      hrtc->State = HAL_RTC_STATE_ERROR;

      /* Process Unlocked */
      __HAL_UNLOCK(hrtc);

      return HAL_ERROR;
    }
  }

  /* Wait for synchro*/
  HAL_RTC_WaitForSynchro(hrtc);

  /* Clear RSF flag */
  CLEAR_BIT(hrtc->Instance->CRL, RTC_FLAG_RSF);

  /* De-Initialize RTC MSP */
  HAL_RTC_MspDeInit(hrtc);

  hrtc->State = HAL_RTC_STATE_RESET;

  /* Release Lock */
  __HAL_UNLOCK(hrtc);

  return HAL_OK;
}

/**
  * @brief  Initializes the RTC MSP.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval None
  */
__weak void HAL_RTC_MspInit(RTC_HandleTypeDef* hrtc)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hrtc);
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_RTC_MspInit could be implemented in the user file
   */
}

/**
  * @brief  DeInitializes the RTC MSP.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval None
  */
__weak void HAL_RTC_MspDeInit(RTC_HandleTypeDef* hrtc)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hrtc);
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_RTC_MspDeInit could be implemented in the user file
   */
}

/**
  * @}
  */

/** @defgroup RTC_Exported_Functions_Group2 Time and Date functions
 *  @brief   RTC Time and Date functions
 *
@verbatim
 ===============================================================================
                 ##### RTC Time and Date functions #####
 ===============================================================================

 [..] This section provides functions allowing to configure Time and Date features

@endverbatim
  * @{
  */

/**
  * @brief  Sets RTC current time.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  sTime: Pointer to Time structure
  * @param  Format: Specifies the format of the entered parameters.
  *          This parameter can be one of the following values:
  *            @arg RTC_FORMAT_BIN: Binary data format
  *            @arg RTC_FORMAT_BCD: BCD data format
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format)
{
  uint32_t counter_time = 0U, counter_alarm = 0U;

  /* Check input parameters */
  if((hrtc == NULL) || (sTime == NULL))
  {
     return HAL_ERROR;
  }

 /* Check the parameters */
  assert_param(IS_RTC_FORMAT(Format));

  /* Process Locked */
  __HAL_LOCK(hrtc);

  hrtc->State = HAL_RTC_STATE_BUSY;

  if(Format == RTC_FORMAT_BIN)
  {
    assert_param(IS_RTC_HOUR24(sTime->Hours));
    assert_param(IS_RTC_MINUTES(sTime->Minutes));
    assert_param(IS_RTC_SECONDS(sTime->Seconds));

    counter_time = (uint32_t)(((uint32_t)sTime->Hours * 3600U) + \
                        ((uint32_t)sTime->Minutes * 60U) + \
                        ((uint32_t)sTime->Seconds));
  }
  else
  {
    assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sTime->Hours)));
    assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sTime->Minutes)));
    assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sTime->Seconds)));

    counter_time = (((uint32_t)(RTC_Bcd2ToByte(sTime->Hours)) * 3600U) + \
              ((uint32_t)(RTC_Bcd2ToByte(sTime->Minutes)) * 60U) + \
              ((uint32_t)(RTC_Bcd2ToByte(sTime->Seconds))));
  }

  /* Write time counter in RTC registers */
  if (RTC_WriteTimeCounter(hrtc, counter_time) != HAL_OK)
  {
    /* Set RTC state */
    hrtc->State = HAL_RTC_STATE_ERROR;

    /* Process Unlocked */
    __HAL_UNLOCK(hrtc);

    return HAL_ERROR;
  }
  else
  {
    /* Clear Second and overflow flags */
    CLEAR_BIT(hrtc->Instance->CRL, (RTC_FLAG_SEC | RTC_FLAG_OW));

    /* Read current Alarm counter in RTC registers */
    counter_alarm = RTC_ReadAlarmCounter(hrtc);

    /* Set again alarm to match with new time if enabled */
    if (counter_alarm != RTC_ALARM_RESETVALUE)
    {
      if(counter_alarm < counter_time)
      {
        /* Add 1 day to alarm counter*/
        counter_alarm += (uint32_t)(24U * 3600U);

        /* Write new Alarm counter in RTC registers */
        if (RTC_WriteAlarmCounter(hrtc, counter_alarm) != HAL_OK)
        {
          /* Set RTC state */
          hrtc->State = HAL_RTC_STATE_ERROR;

          /* Process Unlocked */
          __HAL_UNLOCK(hrtc);

          return HAL_ERROR;
        }
      }
    }

    hrtc->State = HAL_RTC_STATE_READY;

   __HAL_UNLOCK(hrtc);

   return HAL_OK;
  }
}

/**
  * @brief  Gets RTC current time.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  sTime: Pointer to Time structure
  * @param  Format: Specifies the format of the entered parameters.
  *          This parameter can be one of the following values:
  *            @arg RTC_FORMAT_BIN: Binary data format
  *            @arg RTC_FORMAT_BCD: BCD data format
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format)
{
  uint32_t counter_time = 0U, counter_alarm = 0U, days_elapsed = 0U, hours = 0U;

  /* Check input parameters */
  if((hrtc == NULL) || (sTime == NULL))
  {
     return HAL_ERROR;
  }

  /* Check the parameters */
  assert_param(IS_RTC_FORMAT(Format));

  /* Check if counter overflow occurred */
  if (__HAL_RTC_OVERFLOW_GET_FLAG(hrtc, RTC_FLAG_OW))
  {
      return HAL_ERROR;
  }

  /* Read the time counter*/
  counter_time = RTC_ReadTimeCounter(hrtc);

  /* Fill the structure fields with the read parameters */
  hours = counter_time / 3600U;
  sTime->Minutes  = (uint8_t)((counter_time % 3600U) / 60U);
  sTime->Seconds  = (uint8_t)((counter_time % 3600U) % 60U);

  if (hours >= 24U)
  {
    /* Get number of days elapsed from last calculation */
    days_elapsed = (hours / 24U);

    /* Set Hours in RTC_TimeTypeDef structure*/
    sTime->Hours = (hours % 24U);

    /* Read Alarm counter in RTC registers */
    counter_alarm = RTC_ReadAlarmCounter(hrtc);

    /* Calculate remaining time to reach alarm (only if set and not yet expired)*/
    if ((counter_alarm != RTC_ALARM_RESETVALUE) && (counter_alarm > counter_time))
    {
      counter_alarm -= counter_time;
    }
    else
    {
      /* In case of counter_alarm < counter_time */
      /* Alarm expiration already occurred but alarm not deactivated */
      counter_alarm = RTC_ALARM_RESETVALUE;
    }

    /* Set updated time in decreasing counter by number of days elapsed */
    counter_time -= (days_elapsed * 24U * 3600U);

    /* Write time counter in RTC registers */
    if (RTC_WriteTimeCounter(hrtc, counter_time) != HAL_OK)
    {
      return HAL_ERROR;
    }

    /* Set updated alarm to be set */
    if (counter_alarm != RTC_ALARM_RESETVALUE)
    {
      counter_alarm += counter_time;

      /* Write time counter in RTC registers */
      if (RTC_WriteAlarmCounter(hrtc, counter_alarm) != HAL_OK)
      {
        return HAL_ERROR;
      }
    }
    else
    {
      /* Alarm already occurred. Set it to reset values to avoid unexpected expiration */
      if (RTC_WriteAlarmCounter(hrtc, counter_alarm) != HAL_OK)
      {
        return HAL_ERROR;
      }
    }

    /* Update date */
    RTC_DateUpdate(hrtc, days_elapsed);
  }
  else
  {
    sTime->Hours = hours;
  }

  /* Check the input parameters format */
  if(Format != RTC_FORMAT_BIN)
  {
    /* Convert the time structure parameters to BCD format */
    sTime->Hours    = (uint8_t)RTC_ByteToBcd2(sTime->Hours);
    sTime->Minutes  = (uint8_t)RTC_ByteToBcd2(sTime->Minutes);
    sTime->Seconds  = (uint8_t)RTC_ByteToBcd2(sTime->Seconds);
  }

  return HAL_OK;
}

/**
  * @brief  Sets RTC current date.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  sDate: Pointer to date structure
  * @param  Format: specifies the format of the entered parameters.
  *          This parameter can be one of the following values:
  *            @arg RTC_FORMAT_BIN: Binary data format
  *            @arg RTC_FORMAT_BCD: BCD data format
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format)
{
  uint32_t counter_time = 0U, counter_alarm = 0U, hours = 0U;

  /* Check input parameters */
  if((hrtc == NULL) || (sDate == NULL))
  {
     return HAL_ERROR;
  }

  /* Check the parameters */
  assert_param(IS_RTC_FORMAT(Format));

 /* Process Locked */
 __HAL_LOCK(hrtc);

  hrtc->State = HAL_RTC_STATE_BUSY;

  if(Format == RTC_FORMAT_BIN)
  {
    assert_param(IS_RTC_YEAR(sDate->Year));
    assert_param(IS_RTC_MONTH(sDate->Month));
    assert_param(IS_RTC_DATE(sDate->Date));

    /* Change the current date */
    hrtc->DateToUpdate.Year  = sDate->Year;
    hrtc->DateToUpdate.Month = sDate->Month;
    hrtc->DateToUpdate.Date  = sDate->Date;
  }
  else
  {
    assert_param(IS_RTC_YEAR(RTC_Bcd2ToByte(sDate->Year)));
    assert_param(IS_RTC_MONTH(RTC_Bcd2ToByte(sDate->Month)));
    assert_param(IS_RTC_DATE(RTC_Bcd2ToByte(sDate->Date)));

    /* Change the current date */
    hrtc->DateToUpdate.Year  = RTC_Bcd2ToByte(sDate->Year);
    hrtc->DateToUpdate.Month = RTC_Bcd2ToByte(sDate->Month);
    hrtc->DateToUpdate.Date  = RTC_Bcd2ToByte(sDate->Date);
  }

  /* WeekDay set by user can be ignored because automatically calculated */
  hrtc->DateToUpdate.WeekDay = RTC_WeekDayNum(hrtc->DateToUpdate.Year, hrtc->DateToUpdate.Month, hrtc->DateToUpdate.Date);
  sDate->WeekDay = hrtc->DateToUpdate.WeekDay;

  /* Reset time to be aligned on the same day */
  /* Read the time counter*/
  counter_time = RTC_ReadTimeCounter(hrtc);

  /* Fill the structure fields with the read parameters */
  hours = counter_time / 3600U;
  if (hours > 24U)
  {
    /* Set updated time in decreasing counter by number of days elapsed */
    counter_time -= ((hours / 24U) * 24U * 3600U);
    /* Write time counter in RTC registers */
    if (RTC_WriteTimeCounter(hrtc, counter_time) != HAL_OK)
    {
      /* Set RTC state */
      hrtc->State = HAL_RTC_STATE_ERROR;

      /* Process Unlocked */
      __HAL_UNLOCK(hrtc);

      return HAL_ERROR;
    }

    /* Read current Alarm counter in RTC registers */
    counter_alarm = RTC_ReadAlarmCounter(hrtc);

    /* Set again alarm to match with new time if enabled */
    if (counter_alarm != RTC_ALARM_RESETVALUE)
    {
      if(counter_alarm < counter_time)
      {
        /* Add 1 day to alarm counter*/
        counter_alarm += (uint32_t)(24U * 3600U);

        /* Write new Alarm counter in RTC registers */
        if (RTC_WriteAlarmCounter(hrtc, counter_alarm) != HAL_OK)
        {
          /* Set RTC state */
          hrtc->State = HAL_RTC_STATE_ERROR;

          /* Process Unlocked */
          __HAL_UNLOCK(hrtc);

          return HAL_ERROR;
        }
      }
    }

  }

  hrtc->State = HAL_RTC_STATE_READY ;

  /* Process Unlocked */
  __HAL_UNLOCK(hrtc);

  return HAL_OK;
}

/**
  * @brief  Gets RTC current date.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  sDate: Pointer to Date structure
  * @param  Format: Specifies the format of the entered parameters.
  *          This parameter can be one of the following values:
  *            @arg RTC_FORMAT_BIN:  Binary data format
  *            @arg RTC_FORMAT_BCD:  BCD data format
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format)
{
  RTC_TimeTypeDef stime = {0U};

  /* Check input parameters */
  if((hrtc == NULL) || (sDate == NULL))
  {
     return HAL_ERROR;
  }

  /* Check the parameters */
  assert_param(IS_RTC_FORMAT(Format));

  /* Call HAL_RTC_GetTime function to update date if counter higher than 24 hours */
  if (HAL_RTC_GetTime(hrtc, &stime, RTC_FORMAT_BIN) != HAL_OK)
  {
    return HAL_ERROR;
  }

  /* Fill the structure fields with the read parameters */
  sDate->WeekDay  = hrtc->DateToUpdate.WeekDay;
  sDate->Year     = hrtc->DateToUpdate.Year;
  sDate->Month    = hrtc->DateToUpdate.Month;
  sDate->Date     = hrtc->DateToUpdate.Date;

  /* Check the input parameters format */
  if(Format != RTC_FORMAT_BIN)
  {
    /* Convert the date structure parameters to BCD format */
    sDate->Year   = (uint8_t)RTC_ByteToBcd2(sDate->Year);
    sDate->Month  = (uint8_t)RTC_ByteToBcd2(sDate->Month);
    sDate->Date   = (uint8_t)RTC_ByteToBcd2(sDate->Date);
  }
  return HAL_OK;
}

/**
  * @}
  */

/** @defgroup RTC_Exported_Functions_Group3 Alarm functions
 *  @brief   RTC Alarm functions
 *
@verbatim
 ===============================================================================
                 ##### RTC Alarm functions #####
 ===============================================================================

 [..] This section provides functions allowing to configure Alarm feature

@endverbatim
  * @{
  */

/**
  * @brief  Sets the specified RTC Alarm.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  sAlarm: Pointer to Alarm structure
  * @param  Format: Specifies the format of the entered parameters.
  *          This parameter can be one of the following values:
  *             @arg RTC_FORMAT_BIN: Binary data format
  *             @arg RTC_FORMAT_BCD: BCD data format
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format)
{
  uint32_t counter_alarm = 0U, counter_time;
  RTC_TimeTypeDef stime = {0U};

  /* Check input parameters */
  if((hrtc == NULL) || (sAlarm == NULL))
  {
     return HAL_ERROR;
  }

  /* Check the parameters */
  assert_param(IS_RTC_FORMAT(Format));
  assert_param(IS_RTC_ALARM(sAlarm->Alarm));

  /* Process Locked */
  __HAL_LOCK(hrtc);

  hrtc->State = HAL_RTC_STATE_BUSY;

  /* Call HAL_RTC_GetTime function to update date if counter higher than 24 hours */
  if (HAL_RTC_GetTime(hrtc, &stime, RTC_FORMAT_BIN) != HAL_OK)
  {
    return HAL_ERROR;
  }

  /* Convert time in seconds */
  counter_time = (uint32_t)(((uint32_t)stime.Hours * 3600U) + \
                      ((uint32_t)stime.Minutes * 60U) + \
                      ((uint32_t)stime.Seconds));

  if(Format == RTC_FORMAT_BIN)
  {
    assert_param(IS_RTC_HOUR24(sAlarm->AlarmTime.Hours));
    assert_param(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes));
    assert_param(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds));

    counter_alarm = (uint32_t)(((uint32_t)sAlarm->AlarmTime.Hours * 3600U) + \
                        ((uint32_t)sAlarm->AlarmTime.Minutes * 60U) + \
                        ((uint32_t)sAlarm->AlarmTime.Seconds));
  }
  else
  {
    assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)));
    assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)));
    assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds)));

    counter_alarm = (((uint32_t)(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)) * 3600U) + \
              ((uint32_t)(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)) * 60U) + \
              ((uint32_t)RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds)));
  }

  /* Check that requested alarm should expire in the same day (otherwise add 1 day) */
  if (counter_alarm < counter_time)
  {
    /* Add 1 day to alarm counter*/
    counter_alarm += (uint32_t)(24U * 3600U);
  }

  /* Write Alarm counter in RTC registers */
  if (RTC_WriteAlarmCounter(hrtc, counter_alarm) != HAL_OK)
  {
    /* Set RTC state */
    hrtc->State = HAL_RTC_STATE_ERROR;

    /* Process Unlocked */
    __HAL_UNLOCK(hrtc);

    return HAL_ERROR;
  }
  else
  {
    hrtc->State = HAL_RTC_STATE_READY;

   __HAL_UNLOCK(hrtc);

   return HAL_OK;
  }
}

/**
  * @brief  Sets the specified RTC Alarm with Interrupt
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  sAlarm: Pointer to Alarm structure
  * @param  Format: Specifies the format of the entered parameters.
  *          This parameter can be one of the following values:
  *             @arg RTC_FORMAT_BIN: Binary data format
  *             @arg RTC_FORMAT_BCD: BCD data format
  * @note   The HAL_RTC_SetTime() must be called before enabling the Alarm feature.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format)
{
  uint32_t counter_alarm = 0U, counter_time;
  RTC_TimeTypeDef stime = {0U};

  /* Check input parameters */
  if((hrtc == NULL) || (sAlarm == NULL))
  {
     return HAL_ERROR;
  }

  /* Check the parameters */
  assert_param(IS_RTC_FORMAT(Format));
  assert_param(IS_RTC_ALARM(sAlarm->Alarm));

  /* Process Locked */
  __HAL_LOCK(hrtc);

  hrtc->State = HAL_RTC_STATE_BUSY;

  /* Call HAL_RTC_GetTime function to update date if counter higher than 24 hours */
  if (HAL_RTC_GetTime(hrtc, &stime, RTC_FORMAT_BIN) != HAL_OK)
  {
    return HAL_ERROR;
  }

  /* Convert time in seconds */
  counter_time = (uint32_t)(((uint32_t)stime.Hours * 3600U) + \
                      ((uint32_t)stime.Minutes * 60U) + \
                      ((uint32_t)stime.Seconds));

  if(Format == RTC_FORMAT_BIN)
  {
    assert_param(IS_RTC_HOUR24(sAlarm->AlarmTime.Hours));
    assert_param(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes));
    assert_param(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds));

    counter_alarm = (uint32_t)(((uint32_t)sAlarm->AlarmTime.Hours * 3600U) + \
      ((uint32_t)sAlarm->AlarmTime.Minutes * 60U) + \
        ((uint32_t)sAlarm->AlarmTime.Seconds));
  }
  else
  {
    assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)));
    assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)));
    assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds)));

    counter_alarm = (((uint32_t)(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)) * 3600U) + \
                     ((uint32_t)(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)) * 60U) + \
                     ((uint32_t)RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds)));
  }

  /* Check that requested alarm should expire in the same day (otherwise add 1 day) */
  if (counter_alarm < counter_time)
  {
    /* Add 1 day to alarm counter*/
    counter_alarm += (uint32_t)(24U * 3600U);
  }

  /* Write alarm counter in RTC registers */
  if (RTC_WriteAlarmCounter(hrtc, counter_alarm) != HAL_OK)
  {
    /* Set RTC state */
    hrtc->State = HAL_RTC_STATE_ERROR;

    /* Process Unlocked */
    __HAL_UNLOCK(hrtc);

    return HAL_ERROR;
  }
  else
  {
    /* Clear flag alarm A */
    __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF);

    /* Configure the Alarm interrupt */
    __HAL_RTC_ALARM_ENABLE_IT(hrtc,RTC_IT_ALRA);

    /* RTC Alarm Interrupt Configuration: EXTI configuration */
    __HAL_RTC_ALARM_EXTI_ENABLE_IT();

    __HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE();

    hrtc->State = HAL_RTC_STATE_READY;

   __HAL_UNLOCK(hrtc);

   return HAL_OK;
  }
}

/**
  * @brief  Gets the RTC Alarm value and masks.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  sAlarm: Pointer to Date structure
  * @param  Alarm: Specifies the Alarm.
  *          This parameter can be one of the following values:
  *             @arg RTC_ALARM_A: Alarm
  * @param  Format: Specifies the format of the entered parameters.
  *          This parameter can be one of the following values:
  *             @arg RTC_FORMAT_BIN: Binary data format
  *             @arg RTC_FORMAT_BCD: BCD data format
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format)
{
  uint32_t counter_alarm = 0U;

  /* Prevent unused argument(s) compilation warning */
  UNUSED(Alarm);

  /* Check input parameters */
  if((hrtc == NULL) || (sAlarm == NULL))
  {
    return HAL_ERROR;
  }

  /* Check the parameters */
  assert_param(IS_RTC_FORMAT(Format));
  assert_param(IS_RTC_ALARM(Alarm));

  /* Read Alarm counter in RTC registers */
  counter_alarm = RTC_ReadAlarmCounter(hrtc);

  /* Fill the structure with the read parameters */
  /* Set hours in a day range (between 0 to 24)*/
  sAlarm->AlarmTime.Hours   = (uint32_t)((counter_alarm / 3600U) % 24U);
  sAlarm->AlarmTime.Minutes = (uint32_t)((counter_alarm % 3600U) / 60U);
  sAlarm->AlarmTime.Seconds = (uint32_t)((counter_alarm % 3600U) % 60U);

  if(Format != RTC_FORMAT_BIN)
  {
    sAlarm->AlarmTime.Hours   = RTC_ByteToBcd2(sAlarm->AlarmTime.Hours);
    sAlarm->AlarmTime.Minutes = RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes);
    sAlarm->AlarmTime.Seconds = RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds);
  }

  return HAL_OK;
}

/**
  * @brief  Deactive the specified RTC Alarm
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  Alarm: Specifies the Alarm.
  *          This parameter can be one of the following values:
  *            @arg RTC_ALARM_A:  AlarmA
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(Alarm);

  /* Check the parameters */
  assert_param(IS_RTC_ALARM(Alarm));

  /* Check input parameters */
  if(hrtc == NULL)
  {
     return HAL_ERROR;
  }

  /* Process Locked */
  __HAL_LOCK(hrtc);

  hrtc->State = HAL_RTC_STATE_BUSY;

  /* In case of interrupt mode is used, the interrupt source must disabled */
  __HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRA);

  /* Set Initialization mode */
  if(RTC_EnterInitMode(hrtc) != HAL_OK)
  {
    /* Set RTC state */
    hrtc->State = HAL_RTC_STATE_ERROR;

    /* Process Unlocked */
    __HAL_UNLOCK(hrtc);

    return HAL_ERROR;
  }
  else
  {
    /* Clear flag alarm A */
    __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF);

    /* Set to default values ALRH & ALRL registers */
    WRITE_REG(hrtc->Instance->ALRH, RTC_ALARM_RESETVALUE_REGISTER);
    WRITE_REG(hrtc->Instance->ALRL, RTC_ALARM_RESETVALUE_REGISTER);

    /* RTC Alarm Interrupt Configuration: Disable EXTI configuration */
    __HAL_RTC_ALARM_EXTI_DISABLE_IT();

    /* Wait for synchro */
    if(RTC_ExitInitMode(hrtc) != HAL_OK)
    {
      hrtc->State = HAL_RTC_STATE_ERROR;

      /* Process Unlocked */
      __HAL_UNLOCK(hrtc);

      return HAL_ERROR;
    }
  }
  hrtc->State = HAL_RTC_STATE_READY;

  /* Process Unlocked */
  __HAL_UNLOCK(hrtc);

  return HAL_OK;
}

/**
  * @brief  This function handles Alarm interrupt request.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval None
  */
void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef* hrtc)
{
  if(__HAL_RTC_ALARM_GET_IT_SOURCE(hrtc, RTC_IT_ALRA))
  {
    /* Get the status of the Interrupt */
    if(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAF) != (uint32_t)RESET)
    {
      /* AlarmA callback */
      HAL_RTC_AlarmAEventCallback(hrtc);

      /* Clear the Alarm interrupt pending bit */
      __HAL_RTC_ALARM_CLEAR_FLAG(hrtc,RTC_FLAG_ALRAF);
    }
  }

  /* Clear the EXTI's line Flag for RTC Alarm */
  __HAL_RTC_ALARM_EXTI_CLEAR_FLAG();

  /* Change RTC state */
  hrtc->State = HAL_RTC_STATE_READY;
}

/**
  * @brief  Alarm A callback.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval None
  */
__weak void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hrtc);
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_RTC_AlarmAEventCallback could be implemented in the user file
   */
}

/**
  * @brief  This function handles AlarmA Polling request.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  Timeout: Timeout duration
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
{
  uint32_t tickstart = HAL_GetTick();

  /* Check input parameters */
  if(hrtc == NULL)
  {
     return HAL_ERROR;
  }

  while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAF) == RESET)
  {
    if(Timeout != HAL_MAX_DELAY)
    {
      if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
      {
        hrtc->State = HAL_RTC_STATE_TIMEOUT;
        return HAL_TIMEOUT;
      }
    }
  }

  /* Clear the Alarm interrupt pending bit */
  __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF);

  /* Change RTC state */
  hrtc->State = HAL_RTC_STATE_READY;

  return HAL_OK;
}

/**
  * @}
  */

/** @defgroup RTC_Exported_Functions_Group4 Peripheral State functions
 *  @brief   Peripheral State functions
 *
@verbatim
 ===============================================================================
                     ##### Peripheral State functions #####
 ===============================================================================
    [..]
    This subsection provides functions allowing to
      (+) Get RTC state

@endverbatim
  * @{
  */
/**
  * @brief  Returns the RTC state.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval HAL state
  */
HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef* hrtc)
{
  return hrtc->State;
}

/**
  * @}
  */

/** @defgroup RTC_Exported_Functions_Group5 Peripheral Control functions
 *  @brief   Peripheral Control functions
 *
@verbatim
 ===============================================================================
                     ##### Peripheral Control functions #####
 ===============================================================================
    [..]
    This subsection provides functions allowing to
      (+) Wait for RTC Time and Date Synchronization

@endverbatim
  * @{
  */

/**
  * @brief  Waits until the RTC registers (RTC_CNT, RTC_ALR and RTC_PRL)
  *   are synchronized with RTC APB clock.
  * @note   This function must be called before any read operation after an APB reset
  *   or an APB clock stop.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef* hrtc)
{
  uint32_t tickstart = 0U;

  /* Check input parameters */
  if(hrtc == NULL)
  {
     return HAL_ERROR;
  }

  /* Clear RSF flag */
  CLEAR_BIT(hrtc->Instance->CRL, RTC_FLAG_RSF);

  tickstart = HAL_GetTick();

  /* Wait the registers to be synchronised */
  while((hrtc->Instance->CRL & RTC_FLAG_RSF) == (uint32_t)RESET)
  {
    if((HAL_GetTick() - tickstart ) >  RTC_TIMEOUT_VALUE)
    {
      return HAL_TIMEOUT;
    }
  }

  return HAL_OK;
}

/**
  * @}
  */

/**
  * @}
  */

/** @addtogroup RTC_Private_Functions
  * @{
  */

/**
  * @brief  Read the time counter available in RTC_CNT registers.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval Time counter
  */
static uint32_t RTC_ReadTimeCounter(RTC_HandleTypeDef* hrtc)
{
  uint16_t high1 = 0U, high2 = 0U, low = 0U;
  uint32_t timecounter = 0U;

  high1 = READ_REG(hrtc->Instance->CNTH & RTC_CNTH_RTC_CNT);
  low   = READ_REG(hrtc->Instance->CNTL & RTC_CNTL_RTC_CNT);
  high2 = READ_REG(hrtc->Instance->CNTH & RTC_CNTH_RTC_CNT);

  if (high1 != high2)
  { /* In this case the counter roll over during reading of CNTL and CNTH registers,
       read again CNTL register then return the counter value */
    timecounter = (((uint32_t) high2 << 16U) | READ_REG(hrtc->Instance->CNTL & RTC_CNTL_RTC_CNT));
  }
  else
  { /* No counter roll over during reading of CNTL and CNTH registers, counter
       value is equal to first value of CNTL and CNTH */
    timecounter = (((uint32_t) high1 << 16U) | low);
  }

  return timecounter;
}

/**
  * @brief  Write the time counter in RTC_CNT registers.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  TimeCounter: Counter to write in RTC_CNT registers
  * @retval HAL status
  */
static HAL_StatusTypeDef RTC_WriteTimeCounter(RTC_HandleTypeDef* hrtc, uint32_t TimeCounter)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Set Initialization mode */
  if(RTC_EnterInitMode(hrtc) != HAL_OK)
  {
    status = HAL_ERROR;
  }
  else
  {
    /* Set RTC COUNTER MSB word */
    WRITE_REG(hrtc->Instance->CNTH, (TimeCounter >> 16U));
    /* Set RTC COUNTER LSB word */
    WRITE_REG(hrtc->Instance->CNTL, (TimeCounter & RTC_CNTL_RTC_CNT));

    /* Wait for synchro */
    if(RTC_ExitInitMode(hrtc) != HAL_OK)
    {
      status = HAL_ERROR;
    }
  }

  return status;
}

/**
  * @brief  Read the time counter available in RTC_ALR registers.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval Time counter
  */
static uint32_t RTC_ReadAlarmCounter(RTC_HandleTypeDef* hrtc)
{
  uint16_t high1 = 0U, low = 0U;

  high1 = READ_REG(hrtc->Instance->ALRH & RTC_CNTH_RTC_CNT);
  low   = READ_REG(hrtc->Instance->ALRL & RTC_CNTL_RTC_CNT);

  return (((uint32_t) high1 << 16U) | low);
}

/**
  * @brief  Write the time counter in RTC_ALR registers.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  AlarmCounter: Counter to write in RTC_ALR registers
  * @retval HAL status
  */
static HAL_StatusTypeDef RTC_WriteAlarmCounter(RTC_HandleTypeDef* hrtc, uint32_t AlarmCounter)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Set Initialization mode */
  if(RTC_EnterInitMode(hrtc) != HAL_OK)
  {
    status = HAL_ERROR;
  }
  else
  {
    /* Set RTC COUNTER MSB word */
    WRITE_REG(hrtc->Instance->ALRH, (AlarmCounter >> 16U));
    /* Set RTC COUNTER LSB word */
    WRITE_REG(hrtc->Instance->ALRL, (AlarmCounter & RTC_ALRL_RTC_ALR));

    /* Wait for synchro */
    if(RTC_ExitInitMode(hrtc) != HAL_OK)
    {
      status = HAL_ERROR;
    }
  }

  return status;
}

/**
  * @brief  Enters the RTC Initialization mode.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval HAL status
  */
static HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef* hrtc)
{
  uint32_t tickstart = 0U;

  tickstart = HAL_GetTick();
  /* Wait till RTC is in INIT state and if Time out is reached exit */
  while((hrtc->Instance->CRL & RTC_CRL_RTOFF) == (uint32_t)RESET)
  {
    if((HAL_GetTick() - tickstart) >  RTC_TIMEOUT_VALUE)
    {
      return HAL_TIMEOUT;
    }
  }

  /* Disable the write protection for RTC registers */
  __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);

  return HAL_OK;
}

/**
  * @brief  Exit the RTC Initialization mode.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval HAL status
  */
static HAL_StatusTypeDef RTC_ExitInitMode(RTC_HandleTypeDef* hrtc)
{
  uint32_t tickstart = 0U;

  /* Disable the write protection for RTC registers */
  __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);

  tickstart = HAL_GetTick();
  /* Wait till RTC is in INIT state and if Time out is reached exit */
  while((hrtc->Instance->CRL & RTC_CRL_RTOFF) == (uint32_t)RESET)
  {
    if((HAL_GetTick() - tickstart) >  RTC_TIMEOUT_VALUE)
    {
      return HAL_TIMEOUT;
    }
  }

  return HAL_OK;
}

/**
  * @brief  Converts a 2 digit decimal to BCD format.
  * @param  Value: Byte to be converted
  * @retval Converted byte
  */
static uint8_t RTC_ByteToBcd2(uint8_t Value)
{
  uint32_t bcdhigh = 0U;

  while(Value >= 10U)
  {
    bcdhigh++;
    Value -= 10U;
  }

  return  ((uint8_t)(bcdhigh << 4U) | Value);
}

/**
  * @brief  Converts from 2 digit BCD to Binary.
  * @param  Value: BCD value to be converted
  * @retval Converted word
  */
static uint8_t RTC_Bcd2ToByte(uint8_t Value)
{
  uint32_t tmp = 0U;
  tmp = ((uint8_t)(Value & (uint8_t)0xF0) >> (uint8_t)0x4) * 10U;
  return (tmp + (Value & (uint8_t)0x0F));
}

/**
  * @brief  Updates date when time is 23:59:59.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  DayElapsed: Number of days elapsed from last date update
  * @retval None
  */
static void RTC_DateUpdate(RTC_HandleTypeDef* hrtc, uint32_t DayElapsed)
{
  uint32_t year = 0U, month = 0U, day = 0U;
  uint32_t loop = 0U;

  /* Get the current year*/
  year = hrtc->DateToUpdate.Year;

  /* Get the current month and day */
  month = hrtc->DateToUpdate.Month;
  day = hrtc->DateToUpdate.Date;

  for (loop = 0U; loop < DayElapsed; loop++)
  {
    if((month == 1U) || (month == 3U) || (month == 5U) || (month == 7U) || \
       (month == 8U) || (month == 10U) || (month == 12U))
    {
      if(day < 31U)
      {
        day++;
      }
      /* Date structure member: day = 31 */
      else
      {
        if(month != 12U)
        {
          month++;
          day = 1U;
        }
        /* Date structure member: day = 31 & month =12 */
        else
        {
          month = 1U;
          day = 1U;
          year++;
        }
      }
    }
    else if((month == 4U) || (month == 6U) || (month == 9U) || (month == 11U))
    {
      if(day < 30U)
      {
        day++;
      }
      /* Date structure member: day = 30 */
      else
      {
        month++;
        day = 1U;
      }
    }
    else if(month == 2U)
    {
      if(day < 28U)
      {
        day++;
      }
      else if(day == 28U)
      {
        /* Leap year */
        if(RTC_IsLeapYear(year))
        {
          day++;
        }
        else
        {
          month++;
          day = 1U;
        }
      }
      else if(day == 29U)
      {
        month++;
        day = 1U;
      }
    }
  }

  /* Update year */
  hrtc->DateToUpdate.Year = year;

  /* Update day and month */
  hrtc->DateToUpdate.Month = month;
  hrtc->DateToUpdate.Date = day;

  /* Update day of the week */
  hrtc->DateToUpdate.WeekDay = RTC_WeekDayNum(year, month, day);
}

/**
  * @brief  Check whether the passed year is Leap or not.
  * @param  nYear  year to check
  * @retval 1: leap year
  *         0: not leap year
  */
static uint8_t RTC_IsLeapYear(uint16_t nYear)
{
  if((nYear % 4U) != 0U)
  {
    return 0U;
  }

  if((nYear % 100U) != 0U)
  {
    return 1U;
  }

  if((nYear % 400U) == 0U)
  {
    return 1U;
  }
  else
  {
    return 0U;
  }
}

/**
  * @brief  Determines the week number, the day number and the week day number.
  * @param  nYear   year to check
  * @param  nMonth  Month to check
  * @param  nDay    Day to check
  * @note   Day is calculated with hypothesis that year > 2000
  * @retval Value which can take one of the following parameters:
  *         @arg RTC_WEEKDAY_MONDAY
  *         @arg RTC_WEEKDAY_TUESDAY
  *         @arg RTC_WEEKDAY_WEDNESDAY
  *         @arg RTC_WEEKDAY_THURSDAY
  *         @arg RTC_WEEKDAY_FRIDAY
  *         @arg RTC_WEEKDAY_SATURDAY
  *         @arg RTC_WEEKDAY_SUNDAY
  */
static uint8_t RTC_WeekDayNum(uint32_t nYear, uint8_t nMonth, uint8_t nDay)
{
  uint32_t year = 0U, weekday = 0U;

  year = 2000U + nYear;

  if(nMonth < 3U)
  {
    /*D = { [(23 x month)/9] + day + 4 + year + [(year-1)/4] - [(year-1)/100] + [(year-1)/400] } mod 7*/
    weekday = (((23U * nMonth)/9U) + nDay + 4U + year + ((year-1U)/4U) - ((year-1U)/100U) + ((year-1U)/400U)) % 7U;
  }
  else
  {
    /*D = { [(23 x month)/9] + day + 4 + year + [year/4] - [year/100] + [year/400] - 2 } mod 7*/
    weekday = (((23U * nMonth)/9U) + nDay + 4U + year + (year/4U) - (year/100U) + (year/400U) - 2U ) % 7U;
  }

  return (uint8_t)weekday;
}

/**
  * @}
  */

#endif /* HAL_RTC_MODULE_ENABLED */
/**
  * @}
  */

/**
  * @}
  */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "{{%book}}".
 *
 * @property integer $id
 * @property string $title
 * @property string $description
 * @property integer $author_id
 * @property string $isbn
 * @property integer $rank
 *
 * @property Author $author
 */
class Book extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%book}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'description'], 'required'],
            [['author_id'], 'integer'],
            [['title'], 'string', 'max' => 64],
            [['description'], 'string', 'max' => 1024],
            [['isbn'], 'string', 'max' => 32],
            [['author_id'], 'exist', 'targetClass'=>'\app\models\Author', 'targetAttribute'=>'id', 'message'=>Yii::t('app','This author doesn\'t exist')],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'title' => Yii::t('app', 'Title'),
            'description' => Yii::t('app', 'Description'),
            'author_id' => Yii::t('app', 'Author'),
            'isbn' => Yii::t('app', 'Isbn'),
            'rank' => Yii::t('app', 'Rank'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAuthor()
    {
        return $this->hasOne(Author::className(), ['id' => 'author_id'])->inverseOf('books');
    }

    public function getUsers()
    {
        return $this->hasMany(User::className(), ['id' => 'user_id'])
            ->viaTable('book_user_link', ['book_id' => 'id']);
    }
}


text:
using System;

namespace EntityFramework.MappingAPI.Test.CodeFirst.Domain
{
    public class MeteringPoint : Entity
    {
        public string EIC { get; set; }

        public DateTime CreatedAt { get; set; }
        public DateTime? ModifiedAt { get; set; }
    }
}


text:
package cmurr.spongebshd;

import bsh.EvalError;
import bsh.Interpreter;
import bsh.TargetError;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import org.slf4j.Logger;
import org.spongepowered.api.Game;
import org.spongepowered.api.entity.player.Player;
import org.spongepowered.api.event.Subscribe;
import org.spongepowered.api.event.state.InitializationEvent;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.service.config.ConfigDir;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.util.command.CommandCallable;
import org.spongepowered.api.util.command.CommandResult;
import org.spongepowered.api.util.command.CommandSource;
import org.spongepowered.api.util.command.source.ConsoleSource;

import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@Plugin(id = "spongebshd", name = "SpongeBSHD", version = "1.0")
public class SpongeBSHD {
    public static SpongeBSHD instance;
    @Inject
    public Logger log;
    @Inject
    public Game game;
    @Inject
    @ConfigDir(sharedRoot = false)
    public File configDir;
    public File configFile;
    public ConfigurationNode configRoot;
    public ConfigurationLoader<? extends ConfigurationNode> configLoader;
    // use a separate file. access to the server permission system shouldn't mean complete control of the machine
    public File allowedPlayersFile;
    public Interpreter shell;

    @Subscribe
    public void onInitialization(InitializationEvent event) {
        if (!game.getServer().getOnlineMode()) {
            log.error("For security reasons, the server must be in online-mode to use SpongeBSHD.");
            return;
        }
        if (instance != null) {
            log.error("SpongeBSHD already initialized!");
            return;
        }
        instance = this;
        shell = new Interpreter();
        try {
            shell.set("game", game);
            shell.set("server", game.getServer());
            for (PluginContainer container : game.getPluginManager().getPlugins()) {
                Object plugin = container.getInstance();
                if (plugin == null) {
                    log.info("Not registering null plugin object in container: " + container);
                    continue;
                }
                String[] longName = plugin.getClass().getName().split("\\.");
                log.info("Registering plugin object: " + longName[longName.length - 1]);
                shell.set(longName[longName.length - 1], plugin);
            }
            shell.eval("setAccessibility(true)");
            shell.eval("import org.spongepowered.api.*");
            shell.eval("import org.spongepowered.api.data.*");
            shell.eval("import org.spongepowered.api.data.manipulator.*");
            shell.eval("import org.spongepowered.api.data.types.*");
            shell.eval("import org.spongepowered.api.entity.*");
            shell.eval("import org.spongepowered.api.entity.living.*");
            shell.eval("import org.spongepowered.api.entity.living.animal.*");
            shell.eval("import org.spongepowered.api.entity.living.complex.*");
            shell.eval("import org.spongepowered.api.entity.living.golem.*");
            shell.eval("import org.spongepowered.api.entity.living.monster.*");
            shell.eval("import org.spongepowered.api.entity.player.*");
            shell.eval("import org.spongepowered.api.item.*");
            shell.eval("import org.spongepowered.api.item.inventory.*");
            shell.eval("import org.spongepowered.api.text.*");
            shell.eval("import org.spongepowered.api.world.*");
        } catch (EvalError err) {
            log.warn("Exception during interpreter environment initialization.", err);
        }
        loadConfig();
        registerCommands();
    }

    private void loadConfig() {
        if (!configDir.exists()) {
            configDir.mkdirs();
        }
        allowedPlayersFile = new File(configDir, "allowedPlayers.txt");
        if (!allowedPlayersFile.exists()) {
            log.info("No allowedPlayers.txt found; creating one.");
            try {
                allowedPlayersFile.createNewFile();
            } catch (IOException exc) {
                exc.printStackTrace();
            }
        }
    }

    private void registerCommands() {
        game.getCommandDispatcher().register(this, new CommandCallable(){
            public final Text desc = Texts.of("Executes BeanShell code on the server.");
            public final Text help = Texts.of("Executes BeanShell code on the server. Only usable by players whose UUID's are in allowedPlayers.txt");
            public final Text usage = Texts.of("<code>");

            public Optional<CommandResult> process(CommandSource source, String arg) {
                if (!testPermission(source)) {
                    source.sendMessage(Texts.of("You fail the permission test."));
                    return Optional.of(CommandResult.empty());
                }
                try {
                    shell.set("me", source);
                } catch (EvalError err) {
                    err.printStackTrace();
                }
                try {
                    source.sendMessage(Texts.of(TextColors.BLUE, "Result: ", TextColors.RESET, String.valueOf(shell.eval(arg))));
                    return Optional.of(CommandResult.success());
                } catch (TargetError err) {
                    source.sendMessage(Texts.of(err.getTarget().getMessage()));
                } catch (EvalError err) {
                    source.sendMessage(Texts.of(err.getMessage()));
                } catch (Throwable thr) {
                    StringWriter writer = new StringWriter();
                    thr.printStackTrace(new PrintWriter(writer));
                    source.sendMessage(Texts.of(writer.toString()));
                }
                return Optional.of(CommandResult.empty());
            }

            public boolean testPermission(CommandSource source) {
                return hasPermission(source);
            }

            public List<String> getSuggestions(CommandSource source, String arg) {
                return Collections.emptyList();
            }

            public Optional<Text> getShortDescription(CommandSource source) { return Optional.of(desc); }
            public Optional<Text> getHelp(CommandSource source) { return Optional.of(help); }
            public Text getUsage(CommandSource source) { return usage; }
        }, "bshd");
//        game.getCommandDispatcher().register(this, new CommandCallable(){
//            public final Text desc = Texts.of("View or change your per-player SpongeBSHD options.");
//            public final Text help = Texts.of("View or change your per-player SpongeBSHD options. Only usable by players whose UUID's are in allowedPlayers.txt");
//            public final Text usage = Texts.of("<list|bookin|bookout>");
//
//            public Optional<CommandResult> process(CommandSource source, String arg) {
//                if (!testPermission(source)) {
//                    source.sendMessage(Texts.of("You fail the permission test."));
//                    return Optional.of(CommandResult.empty());
//                }
//
//                return Optional.of(CommandResult.empty());
//            }
//
//            public boolean testPermission(CommandSource source) {
//                return hasPermission(source);
//            }
//
//            public List<String> getSuggestions(CommandSource source, String arg) {
//                return Collections.emptyList();
//            }
//
//            public Optional<Text> getShortDescription(CommandSource source) { return Optional.of(desc); }
//            public Optional<Text> getHelp(CommandSource source) { return Optional.of(help); }
//            public Text getUsage(CommandSource source) { return usage; }
//        }, "bshdopt");
    }

    public boolean hasPermission(CommandSource source) {
        if (source instanceof ConsoleSource) {
            return true;
        }
        if (source instanceof Player) {
            Player player = (Player) source;
            UUID playerId = player.getUniqueId();
            try {
                BufferedReader reader = new BufferedReader(new FileReader(allowedPlayersFile));
                for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                    if (playerId.equals(UUID.fromString(line))) {
                        reader.close();
                        return true;
                    }
                }
                reader.close();
                return false;
            } catch (Throwable thr) {
                thr.printStackTrace();
            }
        }
        // we don't want command blocks or RCON users dynamically running code
        return false;
    }
}


text:
from __future__ import annotations

import json
from unittest import mock
from unittest.mock import MagicMock

import pytest

from airflow.models import Connection
from airflow.providers.slack.operators.slack import (
    SlackAPIFileOperator,
    SlackAPIOperator,
    SlackAPIPostOperator,
)

SLACK_API_TEST_CONNECTION_ID = "test_slack_conn_id"

@pytest.fixture(scope="module", autouse=True)
def slack_api_connections():
    """Create tests connections."""
    connections = [
        Connection(
            conn_id=SLACK_API_TEST_CONNECTION_ID,
            conn_type="slack",
            password="xoxb-1234567890123-09876543210987-AbCdEfGhIjKlMnOpQrStUvWx",
        ),
    ]
    conn_uris = {f"AIRFLOW_CONN_{c.conn_id.upper()}": c.get_uri() for c in connections}

    with mock.patch.dict("os.environ", values=conn_uris):
        yield

class TestSlackAPIOperator:
    @mock.patch("airflow.providers.slack.operators.slack.mask_secret")
    def test_mask_token(self, mock_mask_secret):
        SlackAPIOperator(task_id="test-mask-token", token="super-secret-token")
        mock_mask_secret.assert_called_once_with("super-secret-token")

    @mock.patch("airflow.providers.slack.operators.slack.SlackHook")
    @pytest.mark.parametrize(
        "token,conn_id",
        [
            ("token", SLACK_API_TEST_CONNECTION_ID),
            ("token", None),
            (None, SLACK_API_TEST_CONNECTION_ID),
        ],
    )
    def test_hook(self, mock_slack_hook_cls, token, conn_id):
        mock_slack_hook = mock_slack_hook_cls.return_value
        op = SlackAPIOperator(task_id="test-mask-token", token=token, slack_conn_id=conn_id)
        hook = op.hook
        assert hook == mock_slack_hook
        assert hook is op.hook
        mock_slack_hook_cls.assert_called_once_with(token=token, slack_conn_id=conn_id)

class TestSlackAPIPostOperator:
    def setup_method(self):
        self.test_username = "test_username"
        self.test_channel = "#test_slack_channel"
        self.test_text = "test_text"
        self.test_icon_url = "test_icon_url"
        self.test_attachments = [
            {
                "fallback": "Required plain-text summary of the attachment.",
                "color": "#36a64f",
                "pretext": "Optional text that appears above the attachment block",
                "author_name": "Bobby Tables",
                "author_link": "http://flickr.com/bobby/",
                "author_icon": "http://flickr.com/icons/bobby.jpg",
                "title": "Slack API Documentation",
                "title_link": "https://api.slack.com/",
                "text": "Optional text that appears within the attachment",
                "fields": [{"title": "Priority", "value": "High", "short": "false"}],
                "image_url": "http://my-website.com/path/to/image.jpg",
                "thumb_url": "http://example.com/path/to/thumb.png",
                "footer": "Slack API",
                "footer_icon": "https://platform.slack-edge.com/img/default_application_icon.png",
                "ts": 123456789,
            }
        ]
        self.test_blocks = [
            {
                "type": "section",
                "text": {
                    "text": "A message *with some bold text* and _some italicized text_.",
                    "type": "mrkdwn",
                },
                "fields": [
                    {"type": "mrkdwn", "text": "High"},
                    {"type": "plain_text", "emoji": True, "text": "String"},
                ],
            }
        ]
        self.test_attachments_in_json = json.dumps(self.test_attachments)
        self.test_blocks_in_json = json.dumps(self.test_blocks)
        self.test_api_params = {"key": "value"}

        self.expected_method = "chat.postMessage"
        self.expected_api_params = {
            "channel": self.test_channel,
            "username": self.test_username,
            "text": self.test_text,
            "icon_url": self.test_icon_url,
            "attachments": self.test_attachments_in_json,
            "blocks": self.test_blocks_in_json,
        }

    def __construct_operator(self, test_token, test_slack_conn_id, test_api_params=None):
        return SlackAPIPostOperator(
            task_id="slack",
            username=self.test_username,
            token=test_token,
            slack_conn_id=test_slack_conn_id,
            channel=self.test_channel,
            text=self.test_text,
            icon_url=self.test_icon_url,
            attachments=self.test_attachments,
            blocks=self.test_blocks,
            api_params=test_api_params,
        )

    def test_init_with_valid_params(self):
        test_token = "test_token"

        slack_api_post_operator = self.__construct_operator(test_token, None, self.test_api_params)
        assert slack_api_post_operator.token == test_token
        assert slack_api_post_operator.slack_conn_id is None
        assert slack_api_post_operator.method == self.expected_method
        assert slack_api_post_operator.text == self.test_text
        assert slack_api_post_operator.channel == self.test_channel
        assert slack_api_post_operator.api_params == self.test_api_params
        assert slack_api_post_operator.username == self.test_username
        assert slack_api_post_operator.icon_url == self.test_icon_url
        assert slack_api_post_operator.attachments == self.test_attachments
        assert slack_api_post_operator.blocks == self.test_blocks

        slack_api_post_operator = self.__construct_operator(None, SLACK_API_TEST_CONNECTION_ID)
        assert slack_api_post_operator.token is None
        assert slack_api_post_operator.slack_conn_id == SLACK_API_TEST_CONNECTION_ID

    @mock.patch("airflow.providers.slack.operators.slack.SlackHook")
    def test_api_call_params_with_default_args(self, mock_hook):
        slack_api_post_operator = SlackAPIPostOperator(
            task_id="slack",
            username=self.test_username,
            slack_conn_id=SLACK_API_TEST_CONNECTION_ID,
        )

        slack_api_post_operator.execute(context=MagicMock())

        expected_api_params = {
            "channel": "#general",
            "username": self.test_username,
            "text": "No message has been set.\n"
            "Here is a cat video instead\n"
            "https://www.youtube.com/watch?v=J---aiyznGQ",
            "icon_url": "https://raw.githubusercontent.com/apache/"
            "airflow/main/airflow/www/static/pin_100.png",
            "attachments": "[]",
            "blocks": "[]",
        }
        assert expected_api_params == slack_api_post_operator.api_params

class TestSlackAPIFileOperator:
    def setup_method(self):
        self.test_username = "test_username"
        self.test_channel = "#test_slack_channel"
        self.test_initial_comment = "test text file test_filename.txt"
        self.filename = "test_filename.txt"
        self.test_filetype = "text"
        self.test_content = "This is a test text file!"
        self.test_api_params = {"key": "value"}
        self.expected_method = "files.upload"

    def __construct_operator(self, test_token, test_slack_conn_id, test_api_params=None):
        return SlackAPIFileOperator(
            task_id="slack",
            token=test_token,
            slack_conn_id=test_slack_conn_id,
            channels=self.test_channel,
            initial_comment=self.test_initial_comment,
            filename=self.filename,
            filetype=self.test_filetype,
            content=self.test_content,
            api_params=test_api_params,
        )

    def test_init_with_valid_params(self):
        test_token = "test_token"

        slack_api_post_operator = self.__construct_operator(test_token, None, self.test_api_params)
        assert slack_api_post_operator.token == test_token
        assert slack_api_post_operator.slack_conn_id is None
        assert slack_api_post_operator.method == self.expected_method
        assert slack_api_post_operator.initial_comment == self.test_initial_comment
        assert slack_api_post_operator.channels == self.test_channel
        assert slack_api_post_operator.api_params == self.test_api_params
        assert slack_api_post_operator.filename == self.filename
        assert slack_api_post_operator.filetype == self.test_filetype
        assert slack_api_post_operator.content == self.test_content

        slack_api_post_operator = self.__construct_operator(None, SLACK_API_TEST_CONNECTION_ID)
        assert slack_api_post_operator.token is None
        assert slack_api_post_operator.slack_conn_id == SLACK_API_TEST_CONNECTION_ID

    @mock.patch("airflow.providers.slack.operators.slack.SlackHook.send_file")
    @pytest.mark.parametrize("initial_comment", [None, "foo-bar"])
    @pytest.mark.parametrize("title", [None, "Spam Egg"])
    def test_api_call_params_with_content_args(self, mock_send_file, initial_comment, title):
        SlackAPIFileOperator(
            task_id="slack",
            slack_conn_id=SLACK_API_TEST_CONNECTION_ID,
            content="test-content",
            channels="#test-channel",
            initial_comment=initial_comment,
            title=title,
        ).execute(context=MagicMock())

        mock_send_file.assert_called_once_with(
            channels="#test-channel",
            content="test-content",
            file=None,
            initial_comment=initial_comment,
            title=title,
        )

    @mock.patch("airflow.providers.slack.operators.slack.SlackHook.send_file")
    @pytest.mark.parametrize("initial_comment", [None, "foo-bar"])
    @pytest.mark.parametrize("title", [None, "Spam Egg"])
    def test_api_call_params_with_file_args(self, mock_send_file, initial_comment, title):
        SlackAPIFileOperator(
            task_id="slack",
            slack_conn_id=SLACK_API_TEST_CONNECTION_ID,
            channels="C1234567890",
            filename="/dev/null",
            initial_comment=initial_comment,
            title=title,
        ).execute(context=MagicMock())

        mock_send_file.assert_called_once_with(
            channels="C1234567890",
            content=None,
            file="/dev/null",
            initial_comment=initial_comment,
            title=title,
        )

    def test_channel_deprecated(self):
        warning_message = (
            r"Argument `channel` is deprecated and will removed in a future releases\. "
            r"Please use `channels` instead\."
        )
        with pytest.warns(DeprecationWarning, match=warning_message):
            op = SlackAPIFileOperator(
                task_id="slack",
                slack_conn_id=SLACK_API_TEST_CONNECTION_ID,
                channel="#random",
                channels=None,
            )
        assert op.channels == "#random"

    def test_both_channel_and_channels_set(self):
        error_message = r"Cannot set both arguments: channel=.* and channels=.*\."
        with pytest.raises(ValueError, match=error_message):
            SlackAPIFileOperator(
                task_id="slack",
                slack_conn_id=SLACK_API_TEST_CONNECTION_ID,
                channel="#random",
                channels="#general",
            )