text
stringlengths 2
95.7k
| meta
dict |
|---|---|
/******************************************************************************
* Author: Laurent Kneip *
* Contact: kneip.laurent@gmail.com *
* License: Copyright (c) 2013 Laurent Kneip, ANU. All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* * Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* * Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* * Neither the name of ANU nor the names of its contributors may be *
* used to endorse or promote products derived from this software without *
* specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"*
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *
* ARE DISCLAIMED. IN NO EVENT SHALL ANU OR THE CONTRIBUTORS BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT *
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY *
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF *
* SUCH DAMAGE. *
******************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <limits.h>
#include <Eigen/Eigen>
#include <opengv/relative_pose/methods.hpp>
#include <opengv/relative_pose/NoncentralRelativeMultiAdapter.hpp>
#include <opengv/sac/MultiRansac.hpp>
#include <opengv/sac_problems/relative_pose/MultiNoncentralRelativePoseSacProblem.hpp>
#include <sstream>
#include <fstream>
#include "random_generators.hpp"
#include "experiment_helpers.hpp"
#include "time_measurement.hpp"
using namespace std;
using namespace Eigen;
using namespace opengv;
int main( int argc, char** argv )
{
// initialize random seed
initializeRandomSeed();
//set experiment parameters
double noise = 0.3;
double outlierFraction = 0.1;
size_t pointsPerCam = 25;
int numberCameras = 4;
//generate a random pose for viewpoint 1
translation_t position1 = Eigen::Vector3d::Zero();
rotation_t rotation1 = Eigen::Matrix3d::Identity();
//generate a random pose for viewpoint 2
translation_t position2 = generateRandomTranslation(2.0);
rotation_t rotation2 = generateRandomRotation(0.5);
//create a fake central camera
translations_t camOffsets;
rotations_t camRotations;
generateRandomCameraSystem( numberCameras, camOffsets, camRotations );
//derive correspondences based on random point-cloud
std::vector<std::shared_ptr<bearingVectors_t> > multiBearingVectors1;
std::vector<std::shared_ptr<bearingVectors_t> > multiBearingVectors2;
std::vector<std::shared_ptr<Eigen::MatrixXd> > gt;
generateMulti2D2DCorrespondences(
position1, rotation1, position2, rotation2, camOffsets, camRotations,
pointsPerCam, noise, outlierFraction,
multiBearingVectors1, multiBearingVectors2, gt );
//Extract the relative pose
translation_t position; rotation_t rotation;
extractRelativePose(
position1, position2, rotation1, rotation2, position, rotation, false );
//print experiment characteristics
printExperimentCharacteristics( position, rotation, noise, outlierFraction );
//create a non-central relative multi-adapter
relative_pose::NoncentralRelativeMultiAdapter adapter(
multiBearingVectors1,
multiBearingVectors2,
camOffsets,
camRotations);
//Create a MultiNoncentralRelativePoseSacProblem and Ransac
opengv::sac::MultiRansac<
sac_problems::relative_pose::MultiNoncentralRelativePoseSacProblem> ransac;
std::shared_ptr<
sac_problems::relative_pose::MultiNoncentralRelativePoseSacProblem> relposeproblem_ptr(
new sac_problems::relative_pose::MultiNoncentralRelativePoseSacProblem(
adapter,
sac_problems::relative_pose::MultiNoncentralRelativePoseSacProblem::SIXPT));
ransac.sac_model_ = relposeproblem_ptr;
ransac.threshold_ = 2.0*(1.0 - cos(atan(sqrt(2.0)*0.5/800.0)));
ransac.max_iterations_ = 100;
//Run the experiment
struct timeval tic;
struct timeval toc;
gettimeofday( &tic, 0 );
ransac.computeModel();
gettimeofday( &toc, 0 );
double ransac_time = TIMETODOUBLE(timeval_minus(toc,tic));
//print the results
std::cout << "the ransac threshold is: " << ransac.threshold_ << std::endl;
std::cout << "the ransac results is: " << std::endl;
std::cout << ransac.model_coefficients_ << std::endl << std::endl;
std::cout << "Ransac needed " << ransac.iterations_ << " iterations and ";
std::cout << ransac_time << " seconds" << std::endl << std::endl;
size_t numberInliers = 0;
for(size_t i = 0; i < ransac.inliers_.size(); i++)
numberInliers += ransac.inliers_[i].size();
std::cout << "the number of inliers is: " << numberInliers;
std::cout << std::endl << std::endl;
std::cout << "the found inliers are: " << std::endl;
for(size_t i = 0; i < ransac.inliers_.size(); i++)
{
for(size_t j = 0; j < ransac.inliers_[i].size(); j++)
std::cout << ransac.inliers_[i][j] << " ";
}
std::cout << std::endl << std::endl;
}
|
{
"pile_set_name": "Github"
}
|
---
id: aa7697ea2477d1316795783b
title: Pig Latin
challengeType: 5
forumTopicId: 16039
localeTitle: Pig Latin
---
## Description
<section id='description'>
Переведите предоставленную строку в латинский свиньи. <a href="http://en.wikipedia.org/wiki/Pig_Latin" target="_blank">Pig Latin</a> берет первый согласный (или согласный кластер) английского слова, переводит его в конец слова и суффиксы «ay». Если слово начинается с гласного, вы просто добавляете «путь» до конца. Строки ввода гарантированно являются английскими словами во всех строчных строках. Не забудьте использовать <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. Попробуйте подключить программу. Напишите свой собственный код.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>translatePigLatin("california")</code> should return "aliforniacay".
testString: assert.deepEqual(translatePigLatin("california"), "aliforniacay");
- text: <code>translatePigLatin("paragraphs")</code> should return "aragraphspay".
testString: assert.deepEqual(translatePigLatin("paragraphs"), "aragraphspay");
- text: <code>translatePigLatin("glove")</code> should return "oveglay".
testString: assert.deepEqual(translatePigLatin("glove"), "oveglay");
- text: <code>translatePigLatin("algorithm")</code> should return "algorithmway".
testString: assert.deepEqual(translatePigLatin("algorithm"), "algorithmway");
- text: <code>translatePigLatin("eight")</code> should return "eightway".
testString: assert.deepEqual(translatePigLatin("eight"), "eightway");
- text: Should handle words where the first vowel comes in the middle of the word. <code>translatePigLatin("schwartz")</code> should return "artzschway".
testString: assert.deepEqual(translatePigLatin("schwartz"), "artzschway");
- text: Should handle words without vowels. <code>translatePigLatin("rhythm")</code> should return "rhythmay".
testString: assert.deepEqual(translatePigLatin("rhythm"), "rhythmay");
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function translatePigLatin(str) {
return str;
}
translatePigLatin("consonant");
```
</div>
</section>
## Solution
<section id='solution'>
```js
function translatePigLatin(str) {
if (isVowel(str.charAt(0))) return str + "way";
var front = [];
str = str.split('');
while (str.length && !isVowel(str[0])) {
front.push(str.shift());
}
return [].concat(str, front).join('') + 'ay';
}
function isVowel(c) {
return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1;
}
```
</section>
|
{
"pile_set_name": "Github"
}
|
#!/bin/bash
# ============================================================================== #
# MIT License #
# #
# Copyright (c) 2017 Donato Rimenti #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #
# SOFTWARE. #
# ============================================================================== #
# #
# DESCRIPTION : Sets up the DB for MongoDB University M101J's Week 3 homeworks. #
# AUTHOR : Donato Rimenti #
# COPYRIGHT : Copyright (c) 2017 Donato Rimenti #
# LICENSE : MIT #
# #
# ============================================================================== #
# Restores DB for Homework 3-1.
mongoimport --drop -d school -c students week_3_schema_design.1f26260f0b08/students.json
|
{
"pile_set_name": "Github"
}
|
$
$!
$"
$#
$$
$%
$&
$'
$(
$)
$*
$+
$,
$-
$.
$/
$:
$;
$<
$=
$>
$?
$@
$[
$\
$]
$^
$_
$`
${
$|
$}
$~
|
{
"pile_set_name": "Github"
}
|
#"charset=utf-8"
#created by Denis Yarkovoy (dyarkovoy@aruna.com.ua) 30 January 2008
#Copyright (C) 2005,2008 Potix Corporation
#
# Error #
#
#-=PAGE_NOT_FOUND
1000={0} не знайдена.
#-=PORTLET_PAGE_REQUIRED
1001=Путь до ZUML сторінки має бути вказаний в параметрі zk_page.
#-=PAGE_FAILED
1002={
Неможливо завантажити {0}
Причина: {1}
{2}
}
#-=UPDATE_OBSOLETE_PAGE
1010={
Сторінка або компонент, що викликається, недоступний: {0}.
Це може бути спричинено таймаутом або надто великою кількістю відкритих сторінок.
Перевантажте сторінку та спробуйте знову.
}
#-=RESUME_FAILED
1020=Неможливо продовжити: {0}
#-=ILLEGAL_REQUEST_COMPONENT_REQUIRED
2000=Невірний запит: компонент має бути визначено для {0}
#-=ILLEGAL_REQUEST_WRONG_DATA
2001=Невірний запит: невірні дані {0} для {1}
#-=NOT_FOUND
3000={0} не знайдено.
#-=TOO_MANY_SUSPENDED
3100=Забагато призупинених потоків.
#-=TOO_MANY_REQUESTS
3101=Забагато одночасних запитів.
|
{
"pile_set_name": "Github"
}
|
# Acknowledgements
This application makes use of the following third party libraries:
## SubModule_Use_Bundle
Copyright (c) 2018 summertian4 <coderfish@163.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Generated by CocoaPods - https://cocoapods.org
|
{
"pile_set_name": "Github"
}
|
# The MIT License
#
# Copyright (c) 2018 suren <zxjlwt@126.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
Apply=Zastosuj
|
{
"pile_set_name": "Github"
}
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2019, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Unleashed.LEDs; use Unleashed.LEDs;
procedure Main is
begin
Enable;
loop
for X in reverse 0 .. 100 loop
for Id in LED_Id loop
Set_Brightness (Id, LED_Brightness (Float (X) / 100.0));
end loop;
-- Busy loop
for Cnt in 1 .. 1_000_000 loop
null;
end loop;
end loop;
end loop;
end Main;
|
{
"pile_set_name": "Github"
}
|
# Выпуск №98
11 декабря 2017: Декодинг картинок, анимация и авторизация в браузерах, Webpack или Parcel, устаревший GIF и всё, что вы хотели знать про Smashing Magazine.
- Виталий Фридман
- Вадим Макеев
- Алексей Симоненко
## Содержание
- 00:04:19 События
- 00:23:16 Новинки браузеров
- 00:53:28 Webpack или Parcel
- 01:16:46 GIF устарел
- 01:26:30 Smashing Magazine
Слушайте: [Google Podcasts](https://podcasts.google.com/?feed=aHR0cHM6Ly93ZWItc3RhbmRhcmRzLnJ1L3BvZGNhc3QvZmVlZC8), [Apple Podcasts](https://podcasts.apple.com/podcast/id1080500016), [ВКонтакте](https://vk.com/podcasts-32017543), [Яндекс.Музыка](https://music.yandex.ru/album/6245956), [Spotify](https://open.spotify.com/show/3rzAcADjpBpXt73L0epTjV), [YouTube](https://www.youtube.com/playlist?list=PLMBnwIwFEFHcwuevhsNXkFTcadeX5R1Go), [SoundCloud](https://soundcloud.com/web-standards), [RSS](https://web-standards.ru/podcast/feed/).
Читайте: [Твиттер](https://twitter.com/webstandards_ru), [ВКонтакте](https://vk.com/webstandards_ru), [Фейсбук](https://www.facebook.com/webstandardsru), [Телеграм](https://t.me/webstandards_ru).
Поддержите: [Патреон](https://www.patreon.com/webstandards_ru), [Яндекс.Деньги](https://money.yandex.ru/to/41001119329753), [PayPal](https://www.paypal.me/pepelsbey).
[Обсуждайте в Слаке](http://slack.web-standards.ru/).
## События
- [HolyJS в Москве 10–11 декабря](https://holyjs-moscow.ru)
- [Pitercss_meetup №17 в Питере 20 декабря](https://pitercss.timepad.ru/event/627086/)
- [MinskJS Meetup 3 в Минске 25 января](http://minskjs.by/)
- [WSD в Москве 3 февраля](https://wsd.events/2018/02/03/)
- [Rolling Scopes в Минске 10–11 февраля](https://2018.conf.rollingscopes.com/)
- [Smashing Conf](https://smashingconf.com/)
## Новинки браузеров
- [Safari TP 45](https://webkit.org/blog/8039/release-notes-for-safari-technology-preview-45/)
- [Chrome 63](https://developers.google.com/web/updates/2017/12/nic63)
- [Intent to Ship: image decoding attribute](https://groups.google.com/a/chromium.org/d/msg/Blink-dev/MbXp16hQclY/bQjegyrbAgAJ)
- [Chrome 65 adding Web Animations API implementation](https://twitter.com/dancwilson/status/938138635953692672)
- [Intent to Ship: Web Authentication](https://groups.google.com/d/msg/mozilla.dev.platform/tsevyqfBHLE/lccldWNNBwAJ)
## Webpack или Parcel
- [Webpack 4.0.0-alpha.0](https://github.com/webpack/webpack/issues/6064)
- [Parcel](https://parceljs.org)
## GIF устарел
- [Эволюция `<img>` Gif без формата GIF](https://habr.ru/p/343958/)
- [Debugging Grid Layouts With Firefox Grid Inspector](https://www.smashingmagazine.com/2017/12/grid-inspector/)
## Smashing Magazine
- [Илья Пухальский](https://twitter.com/pukhalski)
- [Виталий Фридман](https://twitter.com/smashingmag)
|
{
"pile_set_name": "Github"
}
|
# The MIT License
#
# Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Reginaldo L. Russinholi, Cleiber Silva
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
Schedule=Agenda
|
{
"pile_set_name": "Github"
}
|
/******************************************************************************
/ wol.h
/
/ Copyright (c) 2014 and later wol
/ http://forum.cockos.com/member.php?u=70153
/ http://github.com/reaper-oss/sws
/
/ Permission is hereby granted, free of charge, to any person obtaining a copy
/ of this software and associated documentation files (the "Software"), to deal
/ in the Software without restriction, including without limitation the rights to
/ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
/ of the Software, and to permit persons to whom the Software is furnished to
/ do so, subject to the following conditions:
/
/ The above copyright notice and this permission notice shall be included in all
/ copies or substantial portions of the Software.
/
/ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
/ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
/ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
/ OTHER DEALINGS IN THE SOFTWARE.
/
******************************************************************************/
#pragma once
int WOL_Init();
|
{
"pile_set_name": "Github"
}
|
coming soon
|
{
"pile_set_name": "Github"
}
|
/*
MIT Copyright Notice
Copyright 2003 M.I.T.
Permission is hereby granted, without written agreement or royalty fee, to use,
copy, modify, and distribute this software and its documentation for any
purpose, provided that the above copyright notice and the following three
paragraphs appear in all copies of this software.
IN NO EVENT SHALL M.I.T. BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE
AND ITS DOCUMENTATION, EVEN IF M.I.T. HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMANGE.
M.I.T. SPECIFICALLY DISCLAIMS ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND M.I.T. HAS NO OBLIGATION TO
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
$Author: tleek $
$Date: 2004/01/05 17:27:41 $
$Header: /mnt/leo2/cvs/sabo/hist-040105/bind/b1/create_msg_file.c,v 1.1.1.1 2004/01/05 17:27:41 tleek Exp $
*/
/*
BIND Copyright Notice
Copyright (C) 2000-2002 Internet Software Consortium.
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM
DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
$Author: tleek $
$Date: 2004/01/05 17:27:41 $
$Header: /mnt/leo2/cvs/sabo/hist-040105/bind/b1/create_msg_file.c,v 1.1.1.1 2004/01/05 17:27:41 tleek Exp $
*/
/*
<source>
*/
#include <stdio.h>
#include <sys/types.h>
#include <arpa/nameser.h>
#include <arpa/nameser_compat.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <resolv.h>
int main(){
FILE *f;
u_char buf[1000];
u_char *p;
char *temp, *temp1;
u_char *comp_dn, *comp_dn2;
char exp_dn[200], exp_dn2[200];
u_char **dnptrs, **lastdnptr, **dnptrs2;
int i,len = 0, comp_size;
u_long now;
dnptrs = (unsigned char **) malloc(2 * sizeof(unsigned char *));
dnptrs2 = (unsigned char **) malloc(2 * sizeof(unsigned char *));
comp_dn = (unsigned char *) malloc(200*sizeof(unsigned char));
comp_dn2 = (unsigned char *) malloc(200*sizeof(unsigned char));
temp1 = (char *) malloc(400*sizeof(char));
temp = temp1;
p = buf;
strcpy(temp, "HEADER JUNK:");
len += strlen(temp);
while (*temp != '\0')
*p++ = *temp++;
strcpy(exp_dn, "lcs.mit.edu");
*dnptrs++ = (u_char *) exp_dn;
*dnptrs-- = NULL;
lastdnptr = NULL;
printf("Calling dn_comp..\n");
comp_size = dn_comp((const char *) exp_dn, comp_dn, 200, dnptrs, lastdnptr);
printf("uncomp_size = %d\n", strlen(exp_dn));
printf("comp_size = %d\n", comp_size);
printf("exp_dn = %s, comp_dn = %s\n", exp_dn, (char *) comp_dn);
for(i=0; i<comp_size; i++)
*p++ = *comp_dn++;
len += comp_size;
PUTSHORT(30, p); /* type = T_NXT = 30 */
p += 2;
PUTSHORT(255, p); /* class = C_ANY = 255*/
p += 2;
PUTLONG(255, p); /* ttl */
p += 4;
PUTSHORT(16, p); /* dlen = len of everything starting with the covered byte
(the length of the entire resource record... we lie about it
*/
p += 2;
len += 10;
strcpy(exp_dn2, "sls.lcs.mit.edu"); /* domain name */
*dnptrs2++ = (u_char *) exp_dn2;
*dnptrs2-- = NULL;
lastdnptr = NULL;
printf("Calling dn_comp..\n");
comp_size = dn_comp((const char *) exp_dn2, comp_dn2, 200, dnptrs2, lastdnptr);
printf("uncomp_size = %d\n", strlen(exp_dn2));
printf("comp_size = %d\n", comp_size);
printf("exp_dn2 = %s, comp_dn2 = %s\n", exp_dn2, (char *) comp_dn2);
len += comp_size;
for(i=0; i<comp_size; i++)
*p++ = *comp_dn2++;
PUTLONG(1 << 24, p); /* bitmap - set NXT type*/
p += 4;
PUTLONG(0, p);
p += 4;
PUTLONG(0, p);
p += 4;
PUTLONG(0, p);
p += 4;
len += 16;
f = fopen("SIGFILE", "w");
p = buf;
printf("len = %d\n", len);
for(i=0; i<len; i++, p++) /* write record into file */
fputc(*p, f);
fclose(f);
return 0;
}
/*
</source>
*/
|
{
"pile_set_name": "Github"
}
|
# The MIT License
#
# Copyright (c) 2004-2010, Sun Microsystems, Inc. Kohsuke Kawaguchi. Knud Poulsen.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
Version=Version
|
{
"pile_set_name": "Github"
}
|
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
{
"pile_set_name": "Github"
}
|
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
{
"pile_set_name": "Github"
}
|
# The MIT License
#
# Copyright (c) 2004-2010, Sun Microsystems, Inc. Kohsuke Kawaguchi. Knud Poulsen.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
ClockDifference.Ahead=foran
ClockDifference.Behind=bagud
ClockDifference.InSync=I Sync
ClockDifference.Failed=Kunne ikke checke
|
{
"pile_set_name": "Github"
}
|
/*
Copyright (C) 2008 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xA0]+/,null,"\t\n\r \u00a0"],["str",/^(?:"(?:[^\"\\]|\\.)*"|'(?:[^\'\\]|\\.)*')/,null,"\"'"]],[["com",/^(?:--[^\r\n]*|\/\*[\s\S]*?(?:\*\/|$))/],["kwd",/^(?:ADD|ALL|ALTER|AND|ANY|APPLY|AS|ASC|AUTHORIZATION|BACKUP|BEGIN|BETWEEN|BREAK|BROWSE|BULK|BY|CASCADE|CASE|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMN|COMMIT|COMPUTE|CONNECT|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURRENT_TIMESTAMP|CURRENT_USER|CURSOR|DATABASE|DBCC|DEALLOCATE|DECLARE|DEFAULT|DELETE|DENY|DESC|DISK|DISTINCT|DISTRIBUTED|DOUBLE|DROP|DUMMY|DUMP|ELSE|END|ERRLVL|ESCAPE|EXCEPT|EXEC|EXECUTE|EXISTS|EXIT|FETCH|FILE|FILLFACTOR|FOLLOWING|FOR|FOREIGN|FREETEXT|FREETEXTTABLE|FROM|FULL|FUNCTION|GOTO|GRANT|GROUP|HAVING|HOLDLOCK|IDENTITY|IDENTITYCOL|IDENTITY_INSERT|IF|IN|INDEX|INNER|INSERT|INTERSECT|INTO|IS|JOIN|KEY|KILL|LEFT|LIKE|LINENO|LOAD|MATCH|MATCHED|MERGE|NATURAL|NATIONAL|NOCHECK|NONCLUSTERED|NOCYCLE|NOT|NULL|NULLIF|OF|OFF|OFFSETS|ON|OPEN|OPENDATASOURCE|OPENQUERY|OPENROWSET|OPENXML|OPTION|OR|ORDER|OUTER|OVER|PARTITION|PERCENT|PIVOT|PLAN|PRECEDING|PRECISION|PRIMARY|PRINT|PROC|PROCEDURE|PUBLIC|RAISERROR|READ|READTEXT|RECONFIGURE|REFERENCES|REPLICATION|RESTORE|RESTRICT|RETURN|REVOKE|RIGHT|ROLLBACK|ROWCOUNT|ROWGUIDCOL|ROWS?|RULE|SAVE|SCHEMA|SELECT|SESSION_USER|SET|SETUSER|SHUTDOWN|SOME|START|STATISTICS|SYSTEM_USER|TABLE|TEXTSIZE|THEN|TO|TOP|TRAN|TRANSACTION|TRIGGER|TRUNCATE|TSEQUAL|UNBOUNDED|UNION|UNIQUE|UNPIVOT|UPDATE|UPDATETEXT|USE|USER|USING|VALUES|VARYING|VIEW|WAITFOR|WHEN|WHERE|WHILE|WITH|WITHIN|WRITETEXT|XML)(?=[^\w-]|$)/i,
null],["lit",/^[+-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i],["pln",/^[a-z_][\w-]*/i],["pun",/^[^\w\t\n\r \xA0\"\'][^\w\t\n\r \xA0+\-\"\']*/]]),["sql"]);
|
{
"pile_set_name": "Github"
}
|
source: https://github.com/intridea/multi_json/blob/v1.13.1/LICENSE.md
Copyright (c) 2010-2013 Michael Bleigh, Josh Kalderimis, Erik Michaels-Ober, Pavel Pravosud
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
{
"pile_set_name": "Github"
}
|
/* Copyright (C) 2005 Jean-Marc Valin */
/**
@file pseudofloat.h
@brief Pseudo-floating point
* This header file provides a lightweight floating point type for
* use on fixed-point platforms when a large dynamic range is
* required. The new type is not compatible with the 32-bit IEEE format,
* it is not even remotely as accurate as 32-bit floats, and is not
* even guaranteed to produce even remotely correct results for code
* other than Speex. It makes all kinds of shortcuts that are acceptable
* for Speex, but may not be acceptable for your application. You're
* quite welcome to reuse this code and improve it, but don't assume
* it works out of the box. Most likely, it doesn't.
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PSEUDOFLOAT_H
#define PSEUDOFLOAT_H
#include "arch.h"
#include "os_support.h"
#include "math_approx.h"
#include <math.h>
#ifdef FIXED_POINT
typedef struct {
spx_int16_t m;
spx_int16_t e;
} spx_float_t;
static const spx_float_t FLOAT_ZERO = {0,0};
static const spx_float_t FLOAT_ONE = {16384,-14};
static const spx_float_t FLOAT_HALF = {16384,-15};
#define MIN(a,b) ((a)<(b)?(a):(b))
static inline spx_float_t PSEUDOFLOAT(spx_int32_t x)
{
int e=0;
int sign=0;
if (x<0)
{
sign = 1;
x = -x;
}
if (x==0)
{
spx_float_t r = {0,0};
return r;
}
e = spx_ilog2(ABS32(x))-14;
x = VSHR32(x, e);
if (sign)
{
spx_float_t r;
r.m = -x;
r.e = e;
return r;
}
else
{
spx_float_t r;
r.m = x;
r.e = e;
return r;
}
}
static inline spx_float_t FLOAT_ADD(spx_float_t a, spx_float_t b)
{
spx_float_t r;
if (a.m==0)
return b;
else if (b.m==0)
return a;
if ((a).e > (b).e)
{
r.m = ((a).m>>1) + ((b).m>>MIN(15,(a).e-(b).e+1));
r.e = (a).e+1;
}
else
{
r.m = ((b).m>>1) + ((a).m>>MIN(15,(b).e-(a).e+1));
r.e = (b).e+1;
}
if (r.m>0)
{
if (r.m<16384)
{
r.m<<=1;
r.e-=1;
}
} else {
if (r.m>-16384)
{
r.m<<=1;
r.e-=1;
}
}
/*printf ("%f + %f = %f\n", REALFLOAT(a), REALFLOAT(b), REALFLOAT(r));*/
return r;
}
static inline spx_float_t FLOAT_SUB(spx_float_t a, spx_float_t b)
{
spx_float_t r;
if (a.m==0)
return b;
else if (b.m==0)
return a;
if ((a).e > (b).e)
{
r.m = ((a).m>>1) - ((b).m>>MIN(15,(a).e-(b).e+1));
r.e = (a).e+1;
}
else
{
r.m = ((a).m>>MIN(15,(b).e-(a).e+1)) - ((b).m>>1);
r.e = (b).e+1;
}
if (r.m>0)
{
if (r.m<16384)
{
r.m<<=1;
r.e-=1;
}
} else {
if (r.m>-16384)
{
r.m<<=1;
r.e-=1;
}
}
/*printf ("%f + %f = %f\n", REALFLOAT(a), REALFLOAT(b), REALFLOAT(r));*/
return r;
}
static inline int FLOAT_LT(spx_float_t a, spx_float_t b)
{
if (a.m==0)
return b.m>0;
else if (b.m==0)
return a.m<0;
if ((a).e > (b).e)
return ((a).m>>1) < ((b).m>>MIN(15,(a).e-(b).e+1));
else
return ((b).m>>1) > ((a).m>>MIN(15,(b).e-(a).e+1));
}
static inline int FLOAT_GT(spx_float_t a, spx_float_t b)
{
return FLOAT_LT(b,a);
}
static inline spx_float_t FLOAT_MULT(spx_float_t a, spx_float_t b)
{
spx_float_t r;
r.m = (spx_int16_t)((spx_int32_t)(a).m*(b).m>>15);
r.e = (a).e+(b).e+15;
if (r.m>0)
{
if (r.m<16384)
{
r.m<<=1;
r.e-=1;
}
} else {
if (r.m>-16384)
{
r.m<<=1;
r.e-=1;
}
}
/*printf ("%f * %f = %f\n", REALFLOAT(a), REALFLOAT(b), REALFLOAT(r));*/
return r;
}
static inline spx_float_t FLOAT_AMULT(spx_float_t a, spx_float_t b)
{
spx_float_t r;
r.m = (spx_int16_t)((spx_int32_t)(a).m*(b).m>>15);
r.e = (a).e+(b).e+15;
return r;
}
static inline spx_float_t FLOAT_SHL(spx_float_t a, int b)
{
spx_float_t r;
r.m = a.m;
r.e = a.e+b;
return r;
}
static inline spx_int16_t FLOAT_EXTRACT16(spx_float_t a)
{
if (a.e<0)
return EXTRACT16((EXTEND32(a.m)+(EXTEND32(1)<<(-a.e-1)))>>-a.e);
else
return a.m<<a.e;
}
static inline spx_int32_t FLOAT_EXTRACT32(spx_float_t a)
{
if (a.e<0)
return (EXTEND32(a.m)+(EXTEND32(1)<<(-a.e-1)))>>-a.e;
else
return EXTEND32(a.m)<<a.e;
}
static inline spx_int32_t FLOAT_MUL32(spx_float_t a, spx_word32_t b)
{
return VSHR32(MULT16_32_Q15(a.m, b),-a.e-15);
}
static inline spx_float_t FLOAT_MUL32U(spx_word32_t a, spx_word32_t b)
{
int e1, e2;
spx_float_t r;
if (a==0 || b==0)
{
return FLOAT_ZERO;
}
e1 = spx_ilog2(ABS32(a));
a = VSHR32(a, e1-14);
e2 = spx_ilog2(ABS32(b));
b = VSHR32(b, e2-14);
r.m = MULT16_16_Q15(a,b);
r.e = e1+e2-13;
return r;
}
/* Do NOT attempt to divide by a negative number */
static inline spx_float_t FLOAT_DIV32_FLOAT(spx_word32_t a, spx_float_t b)
{
int e=0;
spx_float_t r;
if (a==0)
{
return FLOAT_ZERO;
}
e = spx_ilog2(ABS32(a))-spx_ilog2(b.m-1)-15;
a = VSHR32(a, e);
if (ABS32(a)>=SHL32(EXTEND32(b.m-1),15))
{
a >>= 1;
e++;
}
r.m = DIV32_16(a,b.m);
r.e = e-b.e;
return r;
}
/* Do NOT attempt to divide by a negative number */
static inline spx_float_t FLOAT_DIV32(spx_word32_t a, spx_word32_t b)
{
int e0=0,e=0;
spx_float_t r;
if (a==0)
{
return FLOAT_ZERO;
}
if (b>32767)
{
e0 = spx_ilog2(b)-14;
b = VSHR32(b, e0);
e0 = -e0;
}
e = spx_ilog2(ABS32(a))-spx_ilog2(b-1)-15;
a = VSHR32(a, e);
if (ABS32(a)>=SHL32(EXTEND32(b-1),15))
{
a >>= 1;
e++;
}
e += e0;
r.m = DIV32_16(a,b);
r.e = e;
return r;
}
/* Do NOT attempt to divide by a negative number */
static inline spx_float_t FLOAT_DIVU(spx_float_t a, spx_float_t b)
{
int e=0;
spx_int32_t num;
spx_float_t r;
if (b.m<=0)
{
speex_warning_int("Attempted to divide by", b.m);
return FLOAT_ONE;
}
num = a.m;
a.m = ABS16(a.m);
while (a.m >= b.m)
{
e++;
a.m >>= 1;
}
num = num << (15-e);
r.m = DIV32_16(num,b.m);
r.e = a.e-b.e-15+e;
return r;
}
static inline spx_float_t FLOAT_SQRT(spx_float_t a)
{
spx_float_t r;
spx_int32_t m;
m = SHL32(EXTEND32(a.m), 14);
r.e = a.e - 14;
if (r.e & 1)
{
r.e -= 1;
m <<= 1;
}
r.e >>= 1;
r.m = spx_sqrt(m);
return r;
}
#else
#define spx_float_t float
#define FLOAT_ZERO 0.f
#define FLOAT_ONE 1.f
#define FLOAT_HALF 0.5f
#define PSEUDOFLOAT(x) (x)
#define FLOAT_MULT(a,b) ((a)*(b))
#define FLOAT_AMULT(a,b) ((a)*(b))
#define FLOAT_MUL32(a,b) ((a)*(b))
#define FLOAT_DIV32(a,b) ((a)/(b))
#define FLOAT_EXTRACT16(a) (a)
#define FLOAT_EXTRACT32(a) (a)
#define FLOAT_ADD(a,b) ((a)+(b))
#define FLOAT_SUB(a,b) ((a)-(b))
#define REALFLOAT(x) (x)
#define FLOAT_DIV32_FLOAT(a,b) ((a)/(b))
#define FLOAT_MUL32U(a,b) ((a)*(b))
#define FLOAT_SHL(a,b) (a)
#define FLOAT_LT(a,b) ((a)<(b))
#define FLOAT_GT(a,b) ((a)>(b))
#define FLOAT_DIVU(a,b) ((a)/(b))
#define FLOAT_SQRT(a) (spx_sqrt(a))
#endif
#endif
|
{
"pile_set_name": "Github"
}
|
# 序
**灵魂大师的人格魅力,严肃文学的锤片精髓: Mindfuck**
[吕琮霖](https://www.zhihu.com/people/sigmod)
觉大家对锤片的解读大方向错了。不少锤粉想去模仿大师,却只看到了只言片语的皮毛,一种摸不到精髓,只是一种 Cargo cult。肥肠、一个狗、保定、驴、老王、狗熊、嗷、昏古七这些都是不过指纹,魔幻现实主义的叙事、充满节奏感的语言结构,这些也只是一种姿态。你不能用一个人的指纹和姿态去描述一个人,理解一个人。要触及灵魂。锤片的灵魂是什么?大师的文学素养、人生阅历、音乐品味。所谓厚积薄发,”我见到过地狱与天堂的婚礼,战舰在猎户座肩旁熊熊燃烧!”,85 年春晚的罗文,科室里的勾心斗角,全都信手拈来。讲真,深不可测。感觉大师经历过 8、90 年代诗歌狂潮,理想的幻灭与沧桑,青春的荷尔蒙跟录像厅一起埋葬。
大师这种厚重的积淀,继而在他那雄奇的大脑中发酵成了技巧,化成了 mindfuck。最浅层却又最震撼的一个技巧,就是语言的节奏和韵律。方言只是最肤浅易见的一层,可以令人莞尔,但远非锤片的灵魂,莫让浮云遮蔽眼。运用的典范可以在我老公、我丈母娘系列看到。只是一种塑造市井形像,在小品文中为叙事服务的技巧。
非常奇怪,真的,按理说文字不应该是这样的,是被动的,是被你的眼球去扫描,被你的大脑所理解,但大师的文字不一样。一眼扫过去,大脑还没来得及对字符完全解码,就被镇住了。只言片语,几个碎片,老张、驴、叶尼塞河、bobo 树、醉日逐舟、土拔鼠、电子绵羊、六个骑士整齐走过,在青石板路面发出啪啪声、印度人打板球。。。大师的情绪、经历 rou 一下全都往你脑袋里钻,懵了,对灵魂的一记重锤(300 磅)。就像突然被 USB 3.0 接了脑袋,每秒 500 兆字节的信息灌进来,硬盘读写跟不上。大师的文字不是线性的,绝对不是,行与行,词和词之间都有联系,更像一幅画,整一篇在传递着一种(或者几种)情绪。当然这只是初看。再仔细读,隐隐约约感觉到一种韵律。噫!嗬!大师的文字是有节奏的,长短句,定语、修饰语、状语、碎了,化在文字的脉搏中,产生一种酣畅淋漓的阅读体验,信息流往你脑袋里流得慢了,文字开始有意义了,情绪体会到了,意境浮现了。你想去解构,想用晦涩的术语去分析,想把大师的文字肢解,但我做不到,一种无法挣脱的无力。人和人之间的差距太大了。同样是个排球大小的脑袋,差的就是这么几个突触的链接,大师却有了天才的驾驭文字能力,一种摄人心魄的力量。
在语言之上,更触及灵魂的一层是叙事。当然两者也是不能被割裂的。由于叙事之重要,大师曾专门发了一首微博,只有两个字:叙事。普通文学是叙事的,抒情的,记录思绪的,这些叙的事,抒的情大多是我们所能感知的,是基于人类共通的欲望,情感和逻辑。锤片就利用了这一种常规,产生了一种出其不意,一种 mindfuck。
锤片先是营造了一种合理的叙事,老张、科室、数位产品、老公、丈母娘、加利福尼亚老家,引诱你套入自己的逻辑和情感,去期许情节的发展。结果冷不丁蹦出来一个狗熊、野生郭东林、大叫驴,结果你就懵了,逻辑没用了,悲伤、喜悦、骄傲、贪欲种种情感完全套不进去了,只能跟着大师的思绪走。有些锤粉或许会疑惑锤片里的动物是什么意象?我的一个猜想:就是为了mindfuck。人类的大脑是很奇妙的,你看到“阿拉伯半岛狒狒”的时候,脑子里并不止出现这七个字,而是沙漠、椰枣树、红屁股,各种关联。想象一下,当一个动物园出现的时候是什么情况你的思绪被淹没于信息的洪流,灵魂受到一记重锤!总而言之,大师级叙事的关键在于抽离于现实的情感,超脱于世俗的叙事,信息洪流的冲击。感觉佛搂蜜可能还是个法号,不是单纯的 follow me,是一种循循善诱,渡人般若波罗蜜多。而特师早已六欲皆空了,看破世间虚妄了。
而在所有的这些技法和叙事之上,在严肃文学的金字塔的顶端,在锤片皇冠上的明珠,是大师的人格魅力,是他的一种超越中产阶级生活的境界,还有一种和他厚重阅历极不相称却弥足珍贵的童趣。
如果说在 TGFC 的岁月,是大师以数位产品圈子为靶子,将中产阶级肤浅的物欲和虚荣颠覆成一场闹剧,那微博就提供了一个让大师在更广阔的 audience 面前对当代生活翻江倒海的机会。媒介即信息。微博这个平台不仅给了大师一种新的表达形式,也同时给了大师一种新的平台和 context。尤其是大师与段子手们抱团,更是有了一种 context,用浅薄无聊的段子手一众为背景,大师用刻意、生硬的广告和网络乞讨,硬生生地撕开了段子手们的强颜欢笑,将网路上面的物欲与虚荣赤裸裸地暴露出来(当然也可能是大师确实不要脸。
大师的微博最独特的一点是从现实生活的超脱。没错,大师的灵感来自于生活,叙事也关于生活,但你却从来看不到大师的生活。月入 2300,白白胖胖的保定中年男子(或是对老公绝望的家庭主妇是一个很容易竖起的靶子,很容易诱惑你放弃去思考大师的真实生活,但大师又是一个活生生存在的人。你看不到大师的七情六欲,你不知道大师最近经历了什么,你不知道他有没有在生活中受到挫折,你不知道他有没有因为涨粉而欣喜。当段子手们迎合着粉丝时,大师却爱理不理,偶尔骂一句“你妈死了”,率性,牛逼!你看不到他的虚荣,他的沾沾自喜,你看不到他对热门话题表态,你看不到他对网路潮流的附和。大师非常成功地塑造了一个(或者几个灵魂,而不只是一个微博账号。这种对于生活的超脱,常常让微博上的哈哈党,政论狗,各种主义者无所适从,无从下口,给人当头一击,懵了,忘了蜗角虚名,忘了浮生若梦,忘了风花雪月,只感觉到一种渺小,一种茫茫宇宙间,自己那颅内的一点化学反应算得了什么。这时评论狗们就惊诧了,那种触动之下,任何评论都显得苍白,显得俗气。拷问灵魂!灵魂大师名符其实!
这是我对严肃文学的一点管窥蠡测。在此抛砖引玉,希望能看到更多锤粉炸裂、触及灵魂的严肃文学评论。荣耀赐予你们。
附:我最喜爱的锤片:《七月一言以蔽之,思无邪,《出大事儿了,老王开花了》魔幻,寓言,炸裂!《武汉某幸福中产家庭里一个狗,的波澜壮阔大计》画面呼之欲出,节奏直击面门!《生活,就是你逐渐活明白了》催人泪下,白白胖胖微秃的大师跃然纸上!《说一说在我老家,庄稼的种植情况。。。》魔幻现实主义!抽离、割裂、浓得化不开!
吕琮霖
2014.09.24 于知乎
|
{
"pile_set_name": "Github"
}
|
@interface SBAppWindow : NSObject
@end
|
{
"pile_set_name": "Github"
}
|
// /** @file
// Fat Package Localized Strings and Content.
//
// Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// Neither the name of Intel nor the names of its contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Additional terms: In addition to the forgoing, redistribution and use
// of the code is conditioned upon the FAT 32 File System Driver and all
// derivative works thereof being used for and designed only to read
// and/or write to a file system that is directly managed by an
// Extensible Firmware Interface (EFI) implementation or by an emulator
// of an EFI implementation.
//
// **/
#string STR_PROPERTIES_PACKAGE_NAME
#language en-US
"Fat package"
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2002-2004 by The Web Services-Interoperability Organization (WS-I) and
Certain of its Members. All Rights Reserved.
Notice
The material contained herein is not a license, either expressly or impliedly, to any
intellectual property owned or controlled by any of the authors or developers of this
material or WS-I. The material contained herein is provided on an "AS IS" basis and to
the maximum extent permitted by applicable law, this material is provided AS IS AND WITH
ALL FAULTS, and the authors and developers of this material and WS-I hereby disclaim all
other warranties and conditions, either express, implied or statutory, including, but not
limited to, any (if any) implied warranties, duties or conditions of merchantability,
of fitness for a particular purpose, of accuracy or completeness of responses, of results,
of workmanlike effort, of lack of viruses, and of lack of negligence. ALSO, THERE IS NO
WARRANTY OR CONDITION OF TITLE, QUIET ENJOYMENT, QUIET POSSESSION, CORRESPONDENCE TO
DESCRIPTION OR NON-INFRINGEMENT WITH REGARD TO THIS MATERIAL.
IN NO EVENT WILL ANY AUTHOR OR DEVELOPER OF THIS MATERIAL OR WS-I BE LIABLE TO ANY OTHER
PARTY FOR THE COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS OF USE,
LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT, INDIRECT, OR SPECIAL DAMAGES
WHETHER UNDER CONTRACT, TORT, WARRANTY, OR OTHERWISE, ARISING IN ANY WAY OUT OF THIS OR
ANY OTHER AGREEMENT RELATING TO THIS MATERIAL, WHETHER OR NOT SUCH PARTY HAD ADVANCE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
WS-I License Information
Use of this WS-I Material is governed by the WS-I Test License and other licenses. Information on these
licenses are contained in the README.txt and ReleaseNotes.txt files. By downloading this file, you agree
to the terms of these licenses.
How To Provide Feedback
The Web Services-Interoperability Organization (WS-I) would like to receive input,
suggestions and other feedback ("Feedback") on this work from a wide variety of
industry participants to improve its quality over time.
By sending email, or otherwise communicating with WS-I, you (on behalf of yourself if
you are an individual, and your company if you are providing Feedback on behalf of the
company) will be deemed to have granted to WS-I, the members of WS-I, and other parties
that have access to your Feedback, a non-exclusive, non-transferable, worldwide, perpetual,
irrevocable, royalty-free license to use, disclose, copy, license, modify, sublicense or
otherwise distribute and exploit in any manner whatsoever the Feedback you provide regarding
the work. You acknowledge that you have no expectation of confidentiality with respect to
any Feedback you provide. You represent and warrant that you have rights to provide this
Feedback, and if you are providing Feedback on behalf of a company, you represent and warrant
that you have the rights to provide Feedback on behalf of your company. You also acknowledge
that WS-I is not required to review, discuss, use, consider or in any way incorporate your
Feedback into future versions of its work. If WS-I does incorporate some or all of your
Feedback in a future version of the work, it may, but is not obligated to include your name
(or, if you are identified as acting on behalf of your company, the name of your company) on
a list of contributors to the work. If the foregoing is not acceptable to you and any company
on whose behalf you are acting, please do not provide any Feedback.
Feedback on this document should be directed to wsi-test-comments@ws-i.org.
-->
<xsd:schema targetNamespace="http://ws-i.org/profiles/basic/1.1/xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:simpleType name="swaRef">
<xsd:restriction base="xsd:anyURI"/>
</xsd:simpleType>
</xsd:schema>
|
{
"pile_set_name": "Github"
}
|
// The MIT License (MIT)
//
// Copyright (c) 2011-2015 Webcomm Pty Ltd
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
.logo {
display: block;
strong {
display: none;
}
}
|
{
"pile_set_name": "Github"
}
|
[](https://github.com/ellerbrock/open-source-badges/)
[<img align="right" width="150" src="../assets/join-slack-team.png">](https://join.slack.com/t/firstcontributors/shared_invite/enQtNjkxNzQwNzA2MTMwLTVhMWJjNjg2ODRlNWZhNjIzYjgwNDIyZWYwZjhjYTQ4OTBjMWM0MmFhZDUxNzBiYzczMGNiYzcxNjkzZDZlMDM)
[](https://opensource.org/licenses/MIT)
[](https://www.codetriage.com/roshanjossey/first-contributions)
# Първи стъпки
Трудно е. Когато правиш нещо за пръв път винаги е трудно. Още повече, когато се работи съвместно с други хора. Затова решихме да опростим процеса на учене за новобранците в допринасянето към отворен софтуеър.
Четенето на статии и гледането на видео уроци помага, но има ли по-добър учител от практиката в защитена среда? Целта на този проект е да напътства и опрости първите стъпки на новобранците в участието и приноса към отворен софтуеър. Ако искате да направите първата си контрибуция и да станете част от обществото на отворен софтуеър, следвайте стъпките по-долу.
#### *Ако не се чувствате комфортно използвайки command line (терминал), [ето и уроци за използването на програми с графичен интерфейс]( #tutorials-using-other-tools )*
#### *Можете да прочетете тази статия и на [други езици](translations/Translations.md).*
[🇮🇳](translations/README.hi.md)
[🇲🇲](translations/README.mm_unicode.md)
[🇮🇩](translations/README.id.md)
[🇫🇷](translations/README.fr.md)
[🇪🇸](translations/README.es.md)
[<img src="../assets/catalan1.png" width="22">](translations/README.ca.md)
[🇳🇱](translations/README.nl.md)
[🇱🇹](translations/README.lt.md)
[🇷🇺](translations/README.ru.md)
[:slovakia:](translations/README.slk.md)
[🇯🇵](translations/README.ja.md)
[🇻🇳](translations/README.vn.md)
[🇵🇱](translations/README.pl.md)
[🇮🇷](translations/README.fa.md)
[🇮🇷](translations/README.fa.en.md)
[🇰🇷 🇰🇵](translations/README.ko.md)
[🇩🇪](translations/README.de.md)
[🇩🇰](translations/README.da.md)
[🇨🇳](translations/README.chs.md)
[🇹🇼](translations/README.cht.md)
[🇬🇷](translations/README.gr.md)
[🇪🇬](translations/README.eg.md)
[🇸🇦](translations/README.ar.md)
[🇺🇦](translations/README.ua.md)
[🇧🇷](translations/README.pt_br.md)
[🇵🇹](translations/README.pt-pt.md)
[🇮🇹](translations/README.it.md)
[🇹🇭](translations/README.th.md)
[🏴](translations/README.gl.md)
[🇵🇰](translations/README.ur.md)
[:bangladesh:](translations/README.bn.md)
[🇲🇩 🇷🇴](translations/README.ro.md)
[🇹🇷](translations/README.tr.md)
[🇸🇪](translations/README.se.md)
[:slovenia:](translations/README.sl.md)
[🇮🇱](translations/README.hb.md)
[🇨🇿](translations/README.cs.md)
[<img src="../assets/pirate.png" width="22">](translations/README.en-pirate.md)
[🇲🇽](translations/README.mx.md)
<img align="right" width="300" src="../assets/fork.png" alt="fork this repository" />
Ако нямате git на вашия компютър, [инсталирайте го]( https://help.github.com/articles/set-up-git/).
## Направете Разклонение (Fork) на това хранилище (repository)
Направете разклонение на хранилището като натиснете бутона "Fork" в горната част на тази страница.
Това ще направи копие на това хранилище във вашия GitHub профил.
## Клонирайте това хранилище
<img align="right" width="300" src="../assets/clone.png" alt="clone this repository" />
Сега клонирайте локално на вашия компютър разклоненото хранилище. Отидете във вашия GitHub профил, отворете разклоненото хранилище,
кликнете на бутона 'Clone' и копирайте линка или натиснете иконката 'copy to clipboard' (копирай в клипборда).
Отворете терминал и въведете следната команда
```
git clone "линка който току-що копирахте"
```
като на мястото на "URL-а който току-що копирахте" (без кавичките) поставете линка към това хранилище (Вашето Разклонение на този проект). Вижте
предните стъпки за това как да се сдобиете с линка.
<img align="right" width="300" src="../assets/copy-to-clipboard.png" alt="copy URL to clipboard" />
Например:
```
git clone https://github.com/this-is-you/first-contributions.git
```
Като на мястото на `this-is-you` се намира вашето потребителско име. В тази стъпка вие направихте копие на съдържанието на GitHub хванилището на 'first contributions' във вашия компютър.
## Създайте клон (branch)
Стигнете до местоположението във вашия компютър, където копирахте хранилището (ако вече не се намирате там):
```
cd first-contributions
```
Сега създайте клон използвайки командата `git checkout`:
```
git checkout -b <add-your-new-branch-name>
```
Например:
```
git checkout -b add-alonzo-church
```
(Името на клона не е задължително да съдържа думата *add*, но е препоръчително, защото целта на този клон е да добавите името си към списък.)
## Направете нужните промени и ги commit-нете
Сега отворете файла `Contributors.md` в текстов редактор и добавете името си вн его. Не го добавяйте в началото или края на файла. Поставете го някъде посредата. Сега запазете промените.
<img align="right" width="450" src="../assets/git-status.png" alt="git status" />
Ако навигирате през терминала до директорията на проекта и въведете командата `git status`, ще видите че има променени файлове.
ДОбавете тези промени към клона, който създадохте, използвайки командата `git add`:
```
git add Contributors.md
```
Сега commit-нете тези промени с командата `git commit`:
```
git commit -m "Add <your-name> to Contributors list"
```
като смените `<your-name>` с вашето име.
## Качете (Push) промените в GitHub
Качете вашите промени като въведете командата `git push`:
```
git push origin <add-your-branch-name>
```
сменяйки `<add-your-branch-name>` с името на клона, който създадохте по-рано.
## Предайте вашите промени за рецензия
Ако отидете във вашето хранилище в GitHub, ще видите бутона `Compare & pull request`. Натиснете го.
<img style="float: right;" src="../assets/compare-and-pull.png" alt="create a pull request" />
Сега предайте вашите промени за рецензия.
<img style="float: right;" src="../assets/submit-pull-request.png" alt="submit pull request" />
Скоро аз ще слея (merge) всички ваши промени в главния клон (мастер branch) на този проект. Вие ще бъдете уведомени по електронната поща когато това се случи.
## От тук накъде?
Поздравления! Вие току що изпълнихте стандарните _fork -> clone -> edit -> PR_ операции, които ще срещнете като сътрудник!
Отпразнувайте вашия принос и го споделете с приятели и последователи като посетите [уеб приложението](https://roshanjossey.github.io/first-contributions/#social-share).
Можете да се присъедините към нашия slack team в случай, че имате допълнителни въпроси или нужда от помощ [Присъединете се към slack team](https://join.slack.com/t/firstcontributors/shared_invite/enQtMzE1MTYwNzI3ODQ0LTZiMDA2OGI2NTYyNjM1MTFiNTc4YTRhZTg4OWZjMzA0ZWZmY2UxYzVkMzI1ZmVmOWI4ODdkZWQwNTM2NDVmNjY).
Време да започнете да допринасяте и към други приекти. Ние сме съставили списък с проекти съдържащи лесни проблеми, които са лесни за начало. Проверете [списъка от приекти в уеб приложението](https://roshanjossey.github.io/first-contributions/#project-list).
### [Допълнителни материали](../additional-material/git_workflow_scenarios/additional-material.md)
## Уроци за иползването на други приложения
|<a href="../github-desktop-tutorial.md"><img alt="GitHub Desktop" src="https://desktop.github.com/images/desktop-icon.svg" width="100"></a>|<a href="../github-windows-vs2017-tutorial.md"><img alt="Visual Studio 2017" src="https://upload.wikimedia.org/wikipedia/commons/c/cd/Visual_Studio_2017_Logo.svg" width="100"></a>|<a href="../gitkraken-tutorial.md"><img alt="GitKraken" src="../assets/gk-icon.png" width="100"></a>|<a href="../github-windows-vs-code-tutorial.md"><img alt="VS Code" src="https://upload.wikimedia.org/wikipedia/commons/2/2d/Visual_Studio_Code_1.18_icon.svg" width=100></a>|
|---|---|---|---|
|[GitHub Desktop](../github-desktop-tutorial.md)|[Visual Studio 2017](../github-windows-vs2017-tutorial.md)|[GitKraken](../gitkraken-tutorial.md)|[Visual Studio Code](../github-windows-vs-code-tutorial.md)|
|
{
"pile_set_name": "Github"
}
|
every once in a while you see a film that is so effective in delivering the goods that it is easy to forget , and forgive , its glaring imperfections .
such is the case with ? good will hunting ? , a subtle character study about a socially inept mathematics genius who struggles to find his path in life .
despite some serious character problems , this is still a very good film .
you probably know about the plot so i ? ll make it quick .
will hunting ( damon ) is a janitor at m . i . t . , he ? s really smarter than einstein but nobody knows it .
he likes to go out with his friend chuckie ( affleck ) and their other working-class buddies and drink beer .
he ? s good-looking , charismatic , and witty but has a terrible time with authority and stiff college folk .
after getting into a tiff with the law , a distinguished professor ( skarsg ? rd ) discovers will ? s genius and offers him a chance to clean up his record and avoid jail time , at a price : he must attend weekly sessions with a therapist and work on various mathematical problems ( that have stumped the academic elite ) with the professor .
after outsmarting and scaring the hell out of a couple of different psychologists he meets his match when hooked up with a once-promising therapist named sean maguire ( williams ) who has his own problems .
in the meantime will meets a british medical school student ( driver ) and they begin to fall in love .
the story starts out well enough and is a pretty original basis for a film .
even though we ? ve seen movies about misunderstood , erratic prodigies before ( ? shine ? ring a bell ? ) , the script here creates a complex narrative that doesn ? t just focus solely on one character .
alas though , this is not a perfect film , as much as you feel like it could ? ve been while watching it .
the one real problem i had with it is the unrealistic nature of the main character .
is it possible for a lowly janitor to be this intelligent ?
of course .
is it possible for him to be estranged from any deep , human relationships ?
usually , yes .
but , is it possible for him to also be so handsome , funny , quick with the tongue , and city-street tough ?
not very likely .
come on , usually these guys are total nerds who can ? t even buy their own shirts , much less talk down a harvard student in a hip pub while picking up phone numbers from pretty med . -school
girls .
will is just a little too perfect , and in order to accept the character your disbelief suspension needs to be in excellent working condition .
the heavy-handed , anti-war statement made by will at a government job interview late in the film is also boorish , overlong , pompous , and completely unnecessary .
all this sounds pretty bad , but the film somehow makes up for it in other ways .
damon ? s acting overshadows the fact that the character is slightly unbelievable , his performance is truly extraordinary .
which leads me to the really good part of the review .
the strength of this movie can be summed up in one single word : acting .
i can ? t recall seeing a film recently that was so well-acted from top to bottom .
from minnie driver ? s frustrated lover to ben affleck ? s laid-back best friend , and all the small roles in between , the performances are magnificent .
robin williams ? skill is a given as a bereaved psychologist who could ? ve had a legendary career but was knocked off the path somewhere down the line .
the real gem though is stellan skarsg ? rd ? s turn as professor lambeau , an award-winning mathematician who feels reduced in comparison to a younger , smarter will hunting .
the scenes between williams and skarsg ? rd , as two old college pals who ? ve been brought back together by this enigmatic kid , display some of the best acting i ? ve ever seen .
when i say delivering the goods , this is what i ? m talking about .
watching these two work is what going to see movies is all about .
gus van sant ? s ( to die for , drugstore cowboy ) cold , urban direction is right on , as well as danny elfman ? s sauntering musical score .
i highly recommend ? good will hunting ? .
despite its faults , it is still an intriguing and fascinating film and you are not likely to see a better acted one this year .
|
{
"pile_set_name": "Github"
}
|
/*
FreeRTOS V8.0.0 - Copyright (C) 2014 Real Time Engineers Ltd.
All rights reserved
VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
***************************************************************************
* *
* FreeRTOS provides completely free yet professionally developed, *
* robust, strictly quality controlled, supported, and cross *
* platform software that has become a de facto standard. *
* *
* Help yourself get started quickly and support the FreeRTOS *
* project by purchasing a FreeRTOS tutorial book, reference *
* manual, or both from: http://www.FreeRTOS.org/Documentation *
* *
* Thank you! *
* *
***************************************************************************
This file is part of the FreeRTOS distribution.
FreeRTOS is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License (version 2) as published by the
Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
>>! NOTE: The modification to the GPL is included to allow you to distribute
>>! a combined work that includes FreeRTOS without being obliged to provide
>>! the source code for proprietary components outside of the FreeRTOS
>>! kernel.
FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. Full license text is available from the following
link: http://www.freertos.org/a00114.html
1 tab == 4 spaces!
***************************************************************************
* *
* Having a problem? Start by reading the FAQ "My application does *
* not run, what could be wrong?" *
* *
* http://www.FreeRTOS.org/FAQHelp.html *
* *
***************************************************************************
http://www.FreeRTOS.org - Documentation, books, training, latest versions,
license and Real Time Engineers Ltd. contact details.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool, a DOS
compatible FAT file system, and our tiny thread aware UDP/IP stack.
http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High
Integrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOS
licenses offer ticketed support, indemnification and middleware.
http://www.SafeRTOS.com - High Integrity Systems also provide a safety
engineered and independently SIL3 certified version for use in safety and
mission critical applications that require provable dependability.
1 tab == 4 spaces!
*/
#ifndef INC_FREERTOS_H
#define INC_FREERTOS_H
/*
* Include the generic headers required for the FreeRTOS port being used.
*/
#include <stddef.h>
/*
* If stdint.h cannot be located then:
* + If using GCC ensure the -nostdint options is *not* being used.
* + Ensure the project's include path includes the directory in which your
* compiler stores stdint.h.
* + Set any compiler options necessary for it to support C99, as technically
* stdint.h is only mandatory with C99 (FreeRTOS does not require C99 in any
* other way).
* + The FreeRTOS download includes a simple stdint.h definition that can be
* used in cases where none is provided by the compiler. The files only
* contains the typedefs required to build FreeRTOS. Read the instructions
* in FreeRTOS/source/stdint.readme for more information.
*/
#include "FreeRTOSConfig.h" /* << EST */
#if configGENERATE_STATIC_SOURCES || configPEX_KINETIS_SDK /* << EST */
#include <stdint.h> /* READ COMMENT ABOVE. */
#else
#include "PE_Types.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* Basic FreeRTOS definitions. */
#include "projdefs.h"
/* Application specific configuration options. */
#include "FreeRTOSConfig.h"
/* configUSE_PORT_OPTIMISED_TASK_SELECTION must be defined before portable.h
is included as it is used by the port layer. */
#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION
#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0
#endif
/* Definitions specific to the port being used. */
#include "portable.h"
#include "task.h" /* << EST: for taskENTER_CRITICAL() and taskEXIT_CRITICAL() */
/*
* Check all the required application specific macros have been defined.
* These macros are application specific and (as downloaded) are defined
* within FreeRTOSConfig.h.
*/
#ifndef configMINIMAL_STACK_SIZE
#error Missing definition: configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h. configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task. Refer to the demo project provided for your port for a suitable value.
#endif
#ifndef configMAX_PRIORITIES
#error Missing definition: configMAX_PRIORITIES must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details.
#endif
#ifndef configUSE_PREEMPTION
#error Missing definition: configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.
#endif
#ifndef configUSE_IDLE_HOOK
#error Missing definition: configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.
#endif
#ifndef configUSE_TICK_HOOK
#error Missing definition: configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.
#endif
#ifndef configUSE_CO_ROUTINES
#error Missing definition: configUSE_CO_ROUTINES must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.
#endif
#ifndef INCLUDE_vTaskPrioritySet
#error Missing definition: INCLUDE_vTaskPrioritySet must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.
#endif
#ifndef INCLUDE_uxTaskPriorityGet
#error Missing definition: INCLUDE_uxTaskPriorityGet must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.
#endif
#ifndef INCLUDE_vTaskDelete
#error Missing definition: INCLUDE_vTaskDelete must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.
#endif
#ifndef INCLUDE_vTaskSuspend
#error Missing definition: INCLUDE_vTaskSuspend must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.
#endif
#ifndef INCLUDE_vTaskDelayUntil
#error Missing definition: INCLUDE_vTaskDelayUntil must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.
#endif
#ifndef INCLUDE_vTaskDelay
#error Missing definition: INCLUDE_vTaskDelay must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.
#endif
#ifndef configUSE_16_BIT_TICKS
#error Missing definition: configUSE_16_BIT_TICKS must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.
#endif
#if configUSE_CO_ROUTINES != 0
#ifndef configMAX_CO_ROUTINE_PRIORITIES
#error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1.
#endif
#endif
#ifndef configMAX_PRIORITIES
#error configMAX_PRIORITIES must be defined to be greater than or equal to 1.
#endif
#ifndef INCLUDE_xTaskGetIdleTaskHandle
#define INCLUDE_xTaskGetIdleTaskHandle 0
#endif
#ifndef INCLUDE_xTimerGetTimerDaemonTaskHandle
#define INCLUDE_xTimerGetTimerDaemonTaskHandle 0
#endif
#ifndef INCLUDE_xQueueGetMutexHolder
#define INCLUDE_xQueueGetMutexHolder 0
#endif
#ifndef INCLUDE_xSemaphoreGetMutexHolder
#define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder
#endif
#ifndef INCLUDE_pcTaskGetTaskName
#define INCLUDE_pcTaskGetTaskName 0
#endif
#ifndef configUSE_APPLICATION_TASK_TAG
#define configUSE_APPLICATION_TASK_TAG 0
#endif
#ifndef INCLUDE_uxTaskGetStackHighWaterMark
#define INCLUDE_uxTaskGetStackHighWaterMark 0
#endif
#ifndef INCLUDE_eTaskGetState
#define INCLUDE_eTaskGetState 0
#endif
#ifndef configUSE_RECURSIVE_MUTEXES
#define configUSE_RECURSIVE_MUTEXES 0
#endif
#ifndef configUSE_MUTEXES
#define configUSE_MUTEXES 0
#endif
#ifndef configUSE_TIMERS
#define configUSE_TIMERS 0
#endif
#ifndef configUSE_COUNTING_SEMAPHORES
#define configUSE_COUNTING_SEMAPHORES 0
#endif
#ifndef configUSE_ALTERNATIVE_API
#define configUSE_ALTERNATIVE_API 0
#endif
#ifndef portCRITICAL_NESTING_IN_TCB
#define portCRITICAL_NESTING_IN_TCB 0
#endif
#ifndef configMAX_TASK_NAME_LEN
#define configMAX_TASK_NAME_LEN 16
#endif
#ifndef configIDLE_SHOULD_YIELD
#define configIDLE_SHOULD_YIELD 1
#endif
#if configMAX_TASK_NAME_LEN < 1
#error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h
#endif
#ifndef INCLUDE_xTaskResumeFromISR
#define INCLUDE_xTaskResumeFromISR 1
#endif
#ifndef INCLUDE_xEventGroupSetBitFromISR
#define INCLUDE_xEventGroupSetBitFromISR 0
#endif
#ifndef INCLUDE_xTimerPendFunctionCall
#define INCLUDE_xTimerPendFunctionCall 0
#endif
#ifndef configASSERT
#define configASSERT( x )
#define configASSERT_DEFINED 0
#else
#define configASSERT_DEFINED 1
#endif
/* The timers module relies on xTaskGetSchedulerState(). */
#if configUSE_TIMERS == 1
#ifndef configTIMER_TASK_PRIORITY
#error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined.
#endif /* configTIMER_TASK_PRIORITY */
#ifndef configTIMER_QUEUE_LENGTH
#error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined.
#endif /* configTIMER_QUEUE_LENGTH */
#ifndef configTIMER_TASK_STACK_DEPTH
#error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined.
#endif /* configTIMER_TASK_STACK_DEPTH */
#endif /* configUSE_TIMERS */
#ifndef INCLUDE_xTaskGetSchedulerState
#define INCLUDE_xTaskGetSchedulerState 0
#endif
#ifndef INCLUDE_xTaskGetCurrentTaskHandle
#define INCLUDE_xTaskGetCurrentTaskHandle 0
#endif
#ifndef portSET_INTERRUPT_MASK_FROM_ISR
#define portSET_INTERRUPT_MASK_FROM_ISR() 0
#endif
#ifndef portCLEAR_INTERRUPT_MASK_FROM_ISR
#define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue
#endif
#ifndef portCLEAN_UP_TCB
#define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB
#endif
#ifndef portPRE_TASK_DELETE_HOOK
#define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending )
#endif
#ifndef portSETUP_TCB
#define portSETUP_TCB( pxTCB ) ( void ) pxTCB
#endif
#ifndef configQUEUE_REGISTRY_SIZE
#define configQUEUE_REGISTRY_SIZE 0U
#endif
#if ( configQUEUE_REGISTRY_SIZE < 1 )
#define vQueueAddToRegistry( xQueue, pcName )
#define vQueueUnregisterQueue( xQueue )
#endif
#ifndef portPOINTER_SIZE_TYPE
#define portPOINTER_SIZE_TYPE uint32_t
#endif
/* Remove any unused trace macros. */
#ifndef traceSTART
/* Used to perform any necessary initialisation - for example, open a file
into which trace is to be written. */
#define traceSTART()
#endif
#ifndef traceEND
/* Use to close a trace, for example close a file into which trace has been
written. */
#define traceEND()
#endif
#ifndef traceTASK_SWITCHED_IN
/* Called after a task has been selected to run. pxCurrentTCB holds a pointer
to the task control block of the selected task. */
#define traceTASK_SWITCHED_IN()
#endif
#ifndef traceINCREASE_TICK_COUNT
/* Called before stepping the tick count after waking from tickless idle
sleep. */
#define traceINCREASE_TICK_COUNT( x )
#endif
#ifndef traceLOW_POWER_IDLE_BEGIN
/* Called immediately before entering tickless idle. */
#define traceLOW_POWER_IDLE_BEGIN()
#endif
#ifndef traceLOW_POWER_IDLE_END
/* Called when returning to the Idle task after a tickless idle. */
#define traceLOW_POWER_IDLE_END()
#endif
#ifndef traceTASK_SWITCHED_OUT
/* Called before a task has been selected to run. pxCurrentTCB holds a pointer
to the task control block of the task being switched out. */
#define traceTASK_SWITCHED_OUT()
#endif
#ifndef traceTASK_PRIORITY_INHERIT
/* Called when a task attempts to take a mutex that is already held by a
lower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task
that holds the mutex. uxInheritedPriority is the priority the mutex holder
will inherit (the priority of the task that is attempting to obtain the
muted. */
#define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority )
#endif
#ifndef traceTASK_PRIORITY_DISINHERIT
/* Called when a task releases a mutex, the holding of which had resulted in
the task inheriting the priority of a higher priority task.
pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the
mutex. uxOriginalPriority is the task's configured (base) priority. */
#define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority )
#endif
#ifndef traceBLOCKING_ON_QUEUE_RECEIVE
/* Task is about to block because it cannot read from a
queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore
upon which the read was attempted. pxCurrentTCB points to the TCB of the
task that attempted the read. */
#define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue )
#endif
#ifndef traceBLOCKING_ON_QUEUE_SEND
/* Task is about to block because it cannot write to a
queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore
upon which the write was attempted. pxCurrentTCB points to the TCB of the
task that attempted the write. */
#define traceBLOCKING_ON_QUEUE_SEND( pxQueue )
#endif
#ifndef configCHECK_FOR_STACK_OVERFLOW
#define configCHECK_FOR_STACK_OVERFLOW 0
#endif
/* The following event macros are embedded in the kernel API calls. */
#ifndef traceMOVED_TASK_TO_READY_STATE
#define traceMOVED_TASK_TO_READY_STATE( pxTCB )
#endif
#ifndef traceQUEUE_CREATE
#define traceQUEUE_CREATE( pxNewQueue )
#endif
#ifndef traceQUEUE_CREATE_FAILED
#define traceQUEUE_CREATE_FAILED( ucQueueType )
#endif
#ifndef traceCREATE_MUTEX
#define traceCREATE_MUTEX( pxNewQueue )
#endif
#ifndef traceCREATE_MUTEX_FAILED
#define traceCREATE_MUTEX_FAILED()
#endif
#ifndef traceGIVE_MUTEX_RECURSIVE
#define traceGIVE_MUTEX_RECURSIVE( pxMutex )
#endif
#ifndef traceGIVE_MUTEX_RECURSIVE_FAILED
#define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex )
#endif
#ifndef traceTAKE_MUTEX_RECURSIVE
#define traceTAKE_MUTEX_RECURSIVE( pxMutex )
#endif
#ifndef traceTAKE_MUTEX_RECURSIVE_FAILED
#define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex )
#endif
#ifndef traceCREATE_COUNTING_SEMAPHORE
#define traceCREATE_COUNTING_SEMAPHORE()
#endif
#ifndef traceCREATE_COUNTING_SEMAPHORE_FAILED
#define traceCREATE_COUNTING_SEMAPHORE_FAILED()
#endif
#ifndef traceQUEUE_SEND
#define traceQUEUE_SEND( pxQueue )
#endif
#ifndef traceQUEUE_SEND_FAILED
#define traceQUEUE_SEND_FAILED( pxQueue )
#endif
#ifndef traceQUEUE_RECEIVE
#define traceQUEUE_RECEIVE( pxQueue )
#endif
#ifndef traceQUEUE_PEEK
#define traceQUEUE_PEEK( pxQueue )
#endif
#ifndef traceQUEUE_PEEK_FROM_ISR
#define traceQUEUE_PEEK_FROM_ISR( pxQueue )
#endif
#ifndef traceQUEUE_RECEIVE_FAILED
#define traceQUEUE_RECEIVE_FAILED( pxQueue )
#endif
#ifndef traceQUEUE_SEND_FROM_ISR
#define traceQUEUE_SEND_FROM_ISR( pxQueue )
#endif
#ifndef traceQUEUE_SEND_FROM_ISR_FAILED
#define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue )
#endif
#ifndef traceQUEUE_RECEIVE_FROM_ISR
#define traceQUEUE_RECEIVE_FROM_ISR( pxQueue )
#endif
#ifndef traceQUEUE_RECEIVE_FROM_ISR_FAILED
#define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue )
#endif
#ifndef traceQUEUE_PEEK_FROM_ISR_FAILED
#define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue )
#endif
#ifndef traceQUEUE_DELETE
#define traceQUEUE_DELETE( pxQueue )
#endif
#ifndef traceTASK_CREATE
#define traceTASK_CREATE( pxNewTCB )
#endif
#ifndef traceTASK_CREATE_FAILED
#define traceTASK_CREATE_FAILED()
#endif
#ifndef traceTASK_DELETE
#define traceTASK_DELETE( pxTaskToDelete )
#endif
#ifndef traceTASK_DELAY_UNTIL
#define traceTASK_DELAY_UNTIL()
#endif
#ifndef traceTASK_DELAY
#define traceTASK_DELAY()
#endif
#ifndef traceTASK_PRIORITY_SET
#define traceTASK_PRIORITY_SET( pxTask, uxNewPriority )
#endif
#ifndef traceTASK_SUSPEND
#define traceTASK_SUSPEND( pxTaskToSuspend )
#endif
#ifndef traceTASK_RESUME
#define traceTASK_RESUME( pxTaskToResume )
#endif
#ifndef traceTASK_RESUME_FROM_ISR
#define traceTASK_RESUME_FROM_ISR( pxTaskToResume )
#endif
#ifndef traceTASK_INCREMENT_TICK
#define traceTASK_INCREMENT_TICK( xTickCount )
#endif
#ifndef traceTIMER_CREATE
#define traceTIMER_CREATE( pxNewTimer )
#endif
#ifndef traceTIMER_CREATE_FAILED
#define traceTIMER_CREATE_FAILED()
#endif
#ifndef traceTIMER_COMMAND_SEND
#define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn )
#endif
#ifndef traceTIMER_EXPIRED
#define traceTIMER_EXPIRED( pxTimer )
#endif
#ifndef traceTIMER_COMMAND_RECEIVED
#define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue )
#endif
#ifndef traceMALLOC
#define traceMALLOC( pvAddress, uiSize )
#endif
#ifndef traceFREE
#define traceFREE( pvAddress, uiSize )
#endif
#ifndef traceEVENT_GROUP_CREATE
#define traceEVENT_GROUP_CREATE( xEventGroup )
#endif
#ifndef traceEVENT_GROUP_CREATE_FAILED
#define traceEVENT_GROUP_CREATE_FAILED()
#endif
#ifndef traceEVENT_GROUP_SYNC_BLOCK
#define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor )
#endif
#ifndef traceEVENT_GROUP_SYNC_END
#define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred
#endif
#ifndef traceEVENT_GROUP_WAIT_BITS_BLOCK
#define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor )
#endif
#ifndef traceEVENT_GROUP_WAIT_BITS_END
#define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred
#endif
#ifndef traceEVENT_GROUP_CLEAR_BITS
#define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear )
#endif
#ifndef traceEVENT_GROUP_CLEAR_BITS_FROM_ISR
#define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear )
#endif
#ifndef traceEVENT_GROUP_SET_BITS
#define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet )
#endif
#ifndef traceEVENT_GROUP_SET_BITS_FROM_ISR
#define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet )
#endif
#ifndef traceEVENT_GROUP_DELETE
#define traceEVENT_GROUP_DELETE( xEventGroup )
#endif
#ifndef tracePEND_FUNC_CALL
#define tracePEND_FUNC_CALL(xFunctionToPend, pvParameter1, ulParameter2, ret)
#endif
#ifndef tracePEND_FUNC_CALL_FROM_ISR
#define tracePEND_FUNC_CALL_FROM_ISR(xFunctionToPend, pvParameter1, ulParameter2, ret)
#endif
#ifndef traceQUEUE_REGISTRY_ADD
#define traceQUEUE_REGISTRY_ADD(xQueue, pcQueueName)
#endif
#ifndef configGENERATE_RUN_TIME_STATS
#define configGENERATE_RUN_TIME_STATS 0
#endif
#if ( configGENERATE_RUN_TIME_STATS == 1 )
#ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS
#error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base.
#endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */
#ifndef portGET_RUN_TIME_COUNTER_VALUE
#ifndef portALT_GET_RUN_TIME_COUNTER_VALUE
#error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information.
#endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */
#endif /* portGET_RUN_TIME_COUNTER_VALUE */
#endif /* configGENERATE_RUN_TIME_STATS */
#ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS
#define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS()
#endif
#ifndef configUSE_MALLOC_FAILED_HOOK
#define configUSE_MALLOC_FAILED_HOOK 0
#endif
#ifndef portPRIVILEGE_BIT
#define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 )
#endif
#ifndef portYIELD_WITHIN_API
#define portYIELD_WITHIN_API portYIELD
#endif
#ifndef pvPortMallocAligned
#define pvPortMallocAligned( x, puxStackBuffer ) ( ( ( puxStackBuffer ) == NULL ) ? ( pvPortMalloc( ( x ) ) ) : ( puxStackBuffer ) )
#endif
#ifndef vPortFreeAligned
#define vPortFreeAligned( pvBlockToFree ) vPortFree( pvBlockToFree )
#endif
#ifndef portSUPPRESS_TICKS_AND_SLEEP
#define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime )
#endif
#ifndef configEXPECTED_IDLE_TIME_BEFORE_SLEEP
#define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2
#endif
#if configEXPECTED_IDLE_TIME_BEFORE_SLEEP < 2
#error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2
#endif
#ifndef configUSE_TICKLESS_IDLE
#define configUSE_TICKLESS_IDLE 0
#endif
#ifndef configPRE_SLEEP_PROCESSING
#define configPRE_SLEEP_PROCESSING( x )
#endif
#ifndef configPOST_SLEEP_PROCESSING
#define configPOST_SLEEP_PROCESSING( x )
#endif
#ifndef configUSE_QUEUE_SETS
#define configUSE_QUEUE_SETS 0
#endif
#ifndef portTASK_USES_FLOATING_POINT
#define portTASK_USES_FLOATING_POINT()
#endif
#ifndef configUSE_TIME_SLICING
#define configUSE_TIME_SLICING 1
#endif
#ifndef configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS
#define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0
#endif
#ifndef configUSE_NEWLIB_REENTRANT
#define configUSE_NEWLIB_REENTRANT 0
#endif
#ifndef configUSE_STATS_FORMATTING_FUNCTIONS
#define configUSE_STATS_FORMATTING_FUNCTIONS 0
#endif
#ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID
#define portASSERT_IF_INTERRUPT_PRIORITY_INVALID()
#endif
#ifndef configUSE_TRACE_FACILITY
#define configUSE_TRACE_FACILITY 0
#endif
#ifndef mtCOVERAGE_TEST_MARKER
#define mtCOVERAGE_TEST_MARKER()
#endif
/* Definitions to allow backward compatibility with FreeRTOS versions prior to
V8 if desired. */
#ifndef configENABLE_BACKWARD_COMPATIBILITY
#define configENABLE_BACKWARD_COMPATIBILITY 1
#endif
#if configENABLE_BACKWARD_COMPATIBILITY == 1
#define eTaskStateGet eTaskGetState
#define portTickType TickType_t
#define xTaskHandle TaskHandle_t
#define xQueueHandle QueueHandle_t
#define xSemaphoreHandle SemaphoreHandle_t
#define xQueueSetHandle QueueSetHandle_t
#define xQueueSetMemberHandle QueueSetMemberHandle_t
#define xTimeOutType TimeOut_t
#define xMemoryRegion MemoryRegion_t
#define xTaskParameters TaskParameters_t
#define xTaskStatusType TaskStatus_t
#define xTimerHandle TimerHandle_t
#define xCoRoutineHandle CoRoutineHandle_t
#define pdTASK_HOOK_CODE TaskHookFunction_t
#define portTICK_RATE_MS portTICK_PERIOD_MS
/* Backward compatibility within the scheduler code only - these definitions
are not really required but are included for completeness. */
#define tmrTIMER_CALLBACK TimerCallbackFunction_t
#define pdTASK_CODE TaskFunction_t
#define xListItem ListItem_t
#define xList List_t
#endif /* configENABLE_BACKWARD_COMPATIBILITY */
#ifdef __cplusplus
}
#endif
#endif /* INC_FREERTOS_H */
|
{
"pile_set_name": "Github"
}
|
# The MIT License
#
# Copyright (c) 2004-2010, Sun Microsystems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
Description=Opis
|
{
"pile_set_name": "Github"
}
|
@comment $OpenBSD: PLIST,v$
@bin bin/f18
|
{
"pile_set_name": "Github"
}
|
@ignore
Feature:
Scenario:
|
{
"pile_set_name": "Github"
}
|
Copyright (c) 2013 Braveg1rl
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
{
"pile_set_name": "Github"
}
|
Copyright (c) 2013 Braveg1rl
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
{
"pile_set_name": "Github"
}
|
archive:
ref: events-change-input
---
# Изменение: change, input, cut, copy, paste
На элементах формы происходят события клавиатуры и мыши, но есть и несколько других, особенных событий.
## Событие change
Событие [change](http://www.w3.org/TR/html5/forms.html#event-input-change) происходит по окончании изменения значения элемента формы, когда это изменение зафиксировано.
Для текстовых элементов это означает, что событие произойдёт не при каждом вводе, а при потере фокуса.
Например, пока вы набираете что-то в текстовом поле ниже -- события нет. Но как только вы уведёте фокус на другой элемент, например, нажмёте кнопку -- произойдёт событие `onchange`.
```html autorun height=40
<input type="text" onchange="alert(this.value)">
<input type="button" value="Кнопка">
```
Для остальных же элементов: `select`, `input type=checkbox/radio` оно срабатывает сразу при выборе значения.
```warn header="Поздний `onchange` в IE8-"
В IE8- `checkbox/radio` при изменении мышью не инициируют событие сразу, а ждут потери фокуса.
Для того, чтобы видеть изменения `checkbox/radio` тут же -- в IE8- нужно повесить обработчик на событие `click` (оно произойдёт и при изменении значения с клавиатуры) или воспользоваться событием `propertychange`, описанным далее.
```
## Событие input
Событие `input` срабатывает *тут же* при изменении значения текстового элемента и поддерживается всеми браузерами, кроме IE8-.
В IE9 оно поддерживается частично, а именно -- *не возникает при удалении символов* (как и `onpropertychange`).
Пример использования (не работает в IE8-):
```html autorun height=40
<input type="text"> oninput: <span id="result"></span>
<script>
var input = document.body.children[0];
input.oninput = function() {
document.getElementById('result').innerHTML = input.value;
};
</script>
```
В современных браузерах `oninput` -- самое главное событие для работы с элементом формы. Именно его, а не `keydown/keypress` следует использовать.
Если бы ещё не проблемы со старыми IE... Впрочем, их можно решить при помощи события `propertychange`.
## IE10-, событие propertychange
Это событие происходит только в IE10-, при любом изменении свойства. Оно позволяет отлавливать изменение тут же. Оно нестандартное, и его основная область использования -- исправление недочётов обработки событий в старых IE.
Если поставить его на `checkbox` в IE8-, то получится "правильное" событие `change`:
```html autorun height=40
<input type="checkbox"> Чекбокс с "onchange", работающим везде одинаково
<script>
var checkbox = document.body.children[0];
if ("onpropertychange" in checkbox) {
// старый IE
*!*
checkbox.onpropertychange = function() {
// проверим имя изменённого свойства
if (event.propertyName == "checked") {
alert( checkbox.checked );
}
};
*/!*
} else {
// остальные браузеры
checkbox.onchange = function() {
alert( checkbox.checked );
};
}
</script>
```
Это событие также срабатывает при изменении значения текстового элемента. Поэтому его можно использовать в старых IE вместо `oninput`.
К сожалению, в IE9 у него недочёт: оно не срабатывает при удалении символов. Поэтому сочетания `onpropertychange` + `oninput` недостаточно, чтобы поймать любое изменение поля в старых IE. Далее мы рассмотрим пример, как это можно сделать иначе.
## События cut, copy, paste
Эти события используются редко. Они происходят при вырезании/вставке/копировании значения.
К сожалению, кросс-браузерного способа получить данные, которые вставляются/копируются, не существует, поэтому их основное применение -- это отмена соответствующей операции.
Например, вот так:
```html autorun height=40
<input type="text" id="input"> event: <span id="result"></span>
<script>
input.oncut = input.oncopy = input.onpaste = function(event) {
result.innerHTML = event.type + ' ' + input.value;
return false;
};
</script>
```
## Пример: поле с контролем СМС
Как видим, событий несколько и они взаимно дополняют друг друга.
Посмотрим, как их использовать, на примере.
Сделаем поле для СМС, рядом с которым должно показываться число символов, обновляющееся при каждом изменении поля.
Как такое реализовать?
Событие `input` идеально решит задачу во всех браузерах, кроме IE9-. Собственно, если IE9- нам не нужен, то на этом можно и остановиться.
### IE9-
В IE8- событие `input` не поддерживается, но, как мы видели ранее, есть `onpropertychange`, которое может заменить его.
Что же касается IE9 -- там поддерживаются и `input` и `onpropertychange`, но они оба не работают при удалении символов. Поэтому мы будем отслеживать удаление при помощи `keyup` на `key:Delete` и `key:BackSpace` . А вот удаление командой "вырезать" из меню -- сможет отловить лишь `oncut`.
Получается вот такая комбинация:
```html autorun run height=60
<input type="text" id="sms"> символов: <span id="result"></span>
<script>
function showCount() {
result.innerHTML = sms.value.length;
}
sms.onkeyup = sms.oninput = showCount;
sms.onpropertychange = function() {
if (event.propertyName == "value") showCount();
}
sms.oncut = function() {
setTimeout(showCount, 0); // на момент oncut значение ещё старое
};
</script>
```
Здесь мы добавили вызов `showCount` на все события, которые могут приводить к изменению значения. Да, иногда изменение будет обрабатываться несколько раз, но зато с гарантией. А лишние вызовы легко убрать, например, при помощи `throttle`-декоратора, описанного в задаче <info:task/throttle>.
**Есть и совсем другой простой, но действенный вариант: через `setInterval` регулярно проверять значение и, если оно слишком длинное, обрезать его.**
Чтобы сэкономить ресурсы браузера, мы можем начинать отслеживание по `onfocus`, а прекращать -- по `onblur`, вот так:
```html autorun height=60
<input type="text" id="sms"> символов: <span id="result"></span>
<script>
var timerId;
sms.onfocus = function() {
var lastValue = sms.value;
timerId = setInterval(function() {
if (sms.value != lastValue) {
showCount();
lastValue = sms.value;
}
}, 20);
};
sms.onblur = function() {
clearInterval(timerId);
};
function showCount() {
result.innerHTML = sms.value.length;
}
</script>
```
Обратим внимание -- весь этот "танец с бубном" нужен только для поддержки IE8-, в которых не поддерживается `oninput` и IE9, где `oninput` не работает при удалении.
## Итого
События изменения данных:
| Событие | Описание | Особенности |
|---------|----------|-------------|
| `change`| Изменение значения любого элемента формы. Для текстовых элементов срабатывает при потере фокуса. | В IE8- на чекбоксах ждёт потери фокуса, поэтому для мгновенной реакции ставят также <code>onclick</code>-обработчик или <code>onpropertychange</code>. |
| `input` | Событие срабатывает только на текстовых элементах. Оно не ждёт потери фокуса, в отличие от <code>change</code>. | В IE8- не поддерживается, в IE9 не работает при удалении символов. |
| `propertychange` | Только для IE10-. Универсальное событие для отслеживания изменения свойств элементов. Имя изменённого свойства содержится в `event.propertyName`. Используют для мгновенной реакции на изменение значения в старых IE. | В IE9 не срабатывает при удалении символов. |
| `cut/copy/paste` | Срабатывают при вставке/копировании/удалении текста. Если в их обработчиках отменить действие браузера, то вставки/копирования/удаления не произойдёт. | Вставляемое значение получить нельзя: на момент срабатывания события в элементе всё ещё *старое* значение, а новое недоступно. |
Ещё особенность: в IE8- события `change`, `propertychange`, `cut` и аналогичные не всплывают. То есть, обработчики нужно назначать на сам элемент, без делегирования.
|
{
"pile_set_name": "Github"
}
|
/* -----------------------------------------------------------------------
ffi.c - Copyright (c) 2013 Tensilica, Inc.
XTENSA Foreign Function Interface
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
#include <ffi.h>
#include <ffi_common.h>
/*
|----------------------------------------|
| |
on entry to ffi_call ----> |----------------------------------------|
| caller stack frame for registers a0-a3 |
|----------------------------------------|
| |
| additional arguments |
entry of the function ---> |----------------------------------------|
| copy of function arguments a2-a7 |
| - - - - - - - - - - - - - |
| |
The area below the entry line becomes the new stack frame for the function.
*/
#define FFI_TYPE_STRUCT_REGS FFI_TYPE_LAST
extern void ffi_call_SYSV(void *rvalue, unsigned rsize, unsigned flags,
void(*fn)(void), unsigned nbytes, extended_cif*);
extern void ffi_closure_SYSV(void) FFI_HIDDEN;
ffi_status ffi_prep_cif_machdep(ffi_cif *cif)
{
switch(cif->rtype->type) {
case FFI_TYPE_SINT8:
case FFI_TYPE_UINT8:
case FFI_TYPE_SINT16:
case FFI_TYPE_UINT16:
cif->flags = cif->rtype->type;
break;
case FFI_TYPE_VOID:
case FFI_TYPE_FLOAT:
cif->flags = FFI_TYPE_UINT32;
break;
case FFI_TYPE_DOUBLE:
case FFI_TYPE_UINT64:
case FFI_TYPE_SINT64:
cif->flags = FFI_TYPE_UINT64; // cif->rtype->type;
break;
case FFI_TYPE_STRUCT:
cif->flags = FFI_TYPE_STRUCT; //_REGS;
/* Up to 16 bytes are returned in registers */
if (cif->rtype->size > 4 * 4) {
/* returned structure is referenced by a register; use 8 bytes
(including 4 bytes for potential additional alignment) */
cif->flags = FFI_TYPE_STRUCT;
cif->bytes += 8;
}
break;
default:
cif->flags = FFI_TYPE_UINT32;
break;
}
/* Round the stack up to a full 4 register frame, just in case
(we use this size in movsp). This way, it's also a multiple of
8 bytes for 64-bit arguments. */
cif->bytes = ALIGN(cif->bytes, 16);
return FFI_OK;
}
void ffi_prep_args(extended_cif *ecif, unsigned char* stack)
{
unsigned int i;
unsigned long *addr;
ffi_type **ptr;
union {
void **v;
char **c;
signed char **sc;
unsigned char **uc;
signed short **ss;
unsigned short **us;
unsigned int **i;
long long **ll;
float **f;
double **d;
} p_argv;
/* Verify that everything is aligned up properly */
FFI_ASSERT (((unsigned long) stack & 0x7) == 0);
p_argv.v = ecif->avalue;
addr = (unsigned long*)stack;
/* structures with a size greater than 16 bytes are passed in memory */
if (ecif->cif->rtype->type == FFI_TYPE_STRUCT && ecif->cif->rtype->size > 16)
{
*addr++ = (unsigned long)ecif->rvalue;
}
for (i = ecif->cif->nargs, ptr = ecif->cif->arg_types;
i > 0;
i--, ptr++, p_argv.v++)
{
switch ((*ptr)->type)
{
case FFI_TYPE_SINT8:
*addr++ = **p_argv.sc;
break;
case FFI_TYPE_UINT8:
*addr++ = **p_argv.uc;
break;
case FFI_TYPE_SINT16:
*addr++ = **p_argv.ss;
break;
case FFI_TYPE_UINT16:
*addr++ = **p_argv.us;
break;
case FFI_TYPE_FLOAT:
case FFI_TYPE_INT:
case FFI_TYPE_UINT32:
case FFI_TYPE_SINT32:
case FFI_TYPE_POINTER:
*addr++ = **p_argv.i;
break;
case FFI_TYPE_DOUBLE:
case FFI_TYPE_UINT64:
case FFI_TYPE_SINT64:
if (((unsigned long)addr & 4) != 0)
addr++;
*(unsigned long long*)addr = **p_argv.ll;
addr += sizeof(unsigned long long) / sizeof (addr);
break;
case FFI_TYPE_STRUCT:
{
unsigned long offs;
unsigned long size;
if (((unsigned long)addr & 4) != 0 && (*ptr)->alignment > 4)
addr++;
offs = (unsigned long) addr - (unsigned long) stack;
size = (*ptr)->size;
/* Entire structure must fit the argument registers or referenced */
if (offs < FFI_REGISTER_NARGS * 4
&& offs + size > FFI_REGISTER_NARGS * 4)
addr = (unsigned long*) (stack + FFI_REGISTER_NARGS * 4);
memcpy((char*) addr, *p_argv.c, size);
addr += (size + 3) / 4;
break;
}
default:
FFI_ASSERT(0);
}
}
}
void ffi_call(ffi_cif* cif, void(*fn)(void), void *rvalue, void **avalue)
{
extended_cif ecif;
unsigned long rsize = cif->rtype->size;
int flags = cif->flags;
void *alloc = NULL;
ecif.cif = cif;
ecif.avalue = avalue;
/* Note that for structures that are returned in registers (size <= 16 bytes)
we allocate a temporary buffer and use memcpy to copy it to the final
destination. The reason is that the target address might be misaligned or
the length not a multiple of 4 bytes. Handling all those cases would be
very complex. */
if (flags == FFI_TYPE_STRUCT && (rsize <= 16 || rvalue == NULL))
{
alloc = alloca(ALIGN(rsize, 4));
ecif.rvalue = alloc;
}
else
{
ecif.rvalue = rvalue;
}
if (cif->abi != FFI_SYSV)
FFI_ASSERT(0);
ffi_call_SYSV (ecif.rvalue, rsize, cif->flags, fn, cif->bytes, &ecif);
if (alloc != NULL && rvalue != NULL)
memcpy(rvalue, alloc, rsize);
}
extern void ffi_trampoline();
extern void ffi_cacheflush(void* start, void* end);
ffi_status
ffi_prep_closure_loc (ffi_closure* closure,
ffi_cif* cif,
void (*fun)(ffi_cif*, void*, void**, void*),
void *user_data,
void *codeloc)
{
/* copye trampoline to stack and patch 'ffi_closure_SYSV' pointer */
memcpy(closure->tramp, ffi_trampoline, FFI_TRAMPOLINE_SIZE);
*(unsigned int*)(&closure->tramp[8]) = (unsigned int)ffi_closure_SYSV;
// Do we have this function?
// __builtin___clear_cache(closer->tramp, closer->tramp + FFI_TRAMPOLINE_SIZE)
ffi_cacheflush(closure->tramp, closure->tramp + FFI_TRAMPOLINE_SIZE);
closure->cif = cif;
closure->fun = fun;
closure->user_data = user_data;
return FFI_OK;
}
long FFI_HIDDEN
ffi_closure_SYSV_inner(ffi_closure *closure, void **values, void *rvalue)
{
ffi_cif *cif;
ffi_type **arg_types;
void **avalue;
int i, areg;
cif = closure->cif;
if (cif->abi != FFI_SYSV)
return FFI_BAD_ABI;
areg = 0;
int rtype = cif->rtype->type;
if (rtype == FFI_TYPE_STRUCT && cif->rtype->size > 4 * 4)
{
rvalue = *values;
areg++;
}
cif = closure->cif;
arg_types = cif->arg_types;
avalue = alloca(cif->nargs * sizeof(void *));
for (i = 0; i < cif->nargs; i++)
{
if (arg_types[i]->alignment == 8 && (areg & 1) != 0)
areg++;
// skip the entry 16,a1 framework, add 16 bytes (4 registers)
if (areg == FFI_REGISTER_NARGS)
areg += 4;
if (arg_types[i]->type == FFI_TYPE_STRUCT)
{
int numregs = ((arg_types[i]->size + 3) & ~3) / 4;
if (areg < FFI_REGISTER_NARGS && areg + numregs > FFI_REGISTER_NARGS)
areg = FFI_REGISTER_NARGS + 4;
}
avalue[i] = &values[areg];
areg += (arg_types[i]->size + 3) / 4;
}
(closure->fun)(cif, rvalue, avalue, closure->user_data);
return rtype;
}
|
{
"pile_set_name": "Github"
}
|
Issuer services help companies from around the world to join the London equity market in order to gain access to capital.
The LSE allows companies to raise money, increase their profile and obtain a market valuation through a variety of routes, thus following the firms throughout the whole IPO process.
The London Stock Exchange runs several markets for listing, giving an opportunity for different sized companies to list.
International companies can list a number of products in London including shares, depositary receipts and debt, offering different and cost-effective ways to raise capital.
In 2004 the Exchange opened a Hong Kong office and has attracted more than 200 companies from the Asia-Pacific region.
For the biggest companies exists the Premium Listed Main Market.
This operates a Super Equivalence method where conditions of both the UK Listing Authority as well as London Stock Exchange’s own criteria have to be met.
The largest IPO on the Exchange was completed in May 2011 by Glencore International plc.
The company raised $10 billion at admission, making it one of the largest IPOs ever.
|
{
"pile_set_name": "Github"
}
|
///////////////////////////////////////////////////////////////////////////////
// FILE: CSUXHub.h
// PROJECT: Micro-Manager
// SUBSYSTEM: DeviceAdapters
//-----------------------------------------------------------------------------
// DESCRIPTION: CSUX hub module. Required for operation of all
// CSUX devices
//
// COPYRIGHT: University of California, San Francisco, 2006
// All rights reserved
//
// LICENSE: This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation.
//
// You should have received a copy of the GNU Lesser General Public
// License along with the source distribution; if not, write to
// the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
// Boston, MA 02111-1307 USA
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// AUTHOR: Nico Stuurman, nico@cmp.ucsf.edu, 02/02/2007
//
// Based on NikonTE2000 controller adapter by Nenad Amodaj
//
//
#ifndef _CSUXHUB_H_
#define _CSUXHUB_H_
#include <string>
#include <deque>
#include <map>
#include "../../MMDevice/MMDevice.h"
/////////////////////////////////////////////////////////////////////////
// Error codes
//
#define ERR_NOT_CONNECTED 10002
#define ERR_COMMAND_CANNOT_EXECUTE 10003
#define ERR_NEGATIVE_RESPONSE 10004
enum CommandMode
{
Sync = 0,
Async
};
class CSUXHub
{
public:
CSUXHub();
~CSUXHub();
void SetPort(const char* port) {port_ = port;}
bool IsBusy();
void SetChannel(int channel) {ch_ = channel;};
void GetChannel(int& channel) {channel = ch_;};
int SetFilterWheelPosition(MM::Device& device, MM::Core& core, long wheelNr, long pos);
int GetFilterWheelPosition(MM::Device& device, MM::Core& core, long wheelNr, long& pos);
int SetFilterWheelSpeed(MM::Device& device, MM::Core& core, long wheelNr, long speed);
int GetFilterWheelSpeed(MM::Device& device, MM::Core& core, long wheelNr, long& speed);
int SetDichroicPosition(MM::Device& device, MM::Core& core, long dichroic);
int GetDichroicPosition(MM::Device& device, MM::Core& core, long &dichroic);
int SetShutterPosition(MM::Device& device, MM::Core& core, int pos);
int GetShutterPosition(MM::Device& device, MM::Core& core, int& pos);
int SetDriveSpeed(MM::Device& device, MM::Core& core, int pos);
int GetDriveSpeed(MM::Device& device, MM::Core& core, long& pos);
int GetMaxDriveSpeed(MM::Device& device, MM::Core& core, long& pos);
int SetAutoAdjustDriveSpeed(MM::Device& device, MM::Core& core, double exposureMs);
int RunDisk(MM::Device& device, MM::Core& core, bool run);
int SetBrightFieldPort(MM::Device& device, MM::Core& core, int pos);
int GetBrightFieldPort(MM::Device& device, MM::Core& core, int& pos);
private:
int ExecuteCommand(MM::Device& device, MM::Core& core, const char* command);
int GetAcknowledgment(MM::Device& device, MM::Core& core);
int Acknowledge();
int ParseResponse(const char* cmdId, std::string& value);
void FetchSerialData(MM::Device& device, MM::Core& core);
static const int RCV_BUF_LENGTH = 1024;
char rcvBuf_[RCV_BUF_LENGTH];
char asynchRcvBuf_[RCV_BUF_LENGTH];
void ClearRcvBuf();
void ClearAllRcvBuf(MM::Device& device, MM::Core& core);
int ch_;
std::string port_;
std::vector<char> answerBuf_;
std::multimap<std::string, long> waitingCommands_;
std::string commandMode_;
bool driveSpeedBusy_;
};
#endif // _CSUXHUB_H_
|
{
"pile_set_name": "Github"
}
|
# The MIT License
#
# Italian localization plugin for Jenkins
# Copyright © 2020 Alessandro Menti
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
blurb=Questa vista visualizza automaticamente tutti i processi a cui \
l''utente corrente ha accesso.
|
{
"pile_set_name": "Github"
}
|
# The MIT License
#
# Copyright (c) 2004-2010, Sun Microsystems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
Delete\ this\ build=Odstr\u00E1ni\u0165 beh
|
{
"pile_set_name": "Github"
}
|
---
description: Ведите Changelog
title: Ведите Changelog
language: ru
version: 0.3.0
---
:markdown
# Ведите CHANGELOG
## Не позволяйте друзьям сливать логи гита в CHANGELOG™
Version **#{current_page.metadata[:page][:version]}**
### Что такое лог изменений?
Лог изменений – это файл, который содержит поддерживаемый, упорядоченный в
хронологическом порядке список значимых изменений для каждой версии проекта с
открытым исходным кодом.
<pre class="changelog">#{File.read("CHANGELOG.md")}</pre>
### Для чего нужен лог изменений?
Чтобы пользователи и контрибьюторы могли с меньшими усилиями точно
определить, какие значимые изменения были сделаны в каждом релизе (или
версии) проекта.
### Почему я вообще должен думать об этом?
Потому, что инструменты программирования делаются для людей. Если вам пофигу,
зачем вы вообще занимаетесь программным обеспечением с открытым исходным
кодом? У вас обязательно в голове должен быть центр «не пофигу» :)
Я [беседовал с Адамом Стаковиаком и с Джеродом Санто в подкасте The
Changelog][thechangelog] (в тему название, правда?) о том почему авторам
программного обеспечения с открытым исходным кодом и их коллегам должно быть
не пофигу, и о моих мотивах в создании этого проекта. Послушайте, если у вас
есть время (1:06).
### Что должно быть в хорошем логе изменений?
Я рад, что вы спросили.
Хороший лог изменений придерживается этих приниципов:
- Он сделан для людей, а не машин, так что понятность имеет решающее
значение.
- Легко сослаться на любой раздел (поэтому Markdown лучше обычного текста).
- Один подраздел на каждую версию.
- Релизы перечислены в обратном хронологическом порядке (самые новые –
сверху).
- Пишите все даты в формате `YYYY-MM-DD`. (Например: `2012-06-02` для даты `2
июня 2012`.) Он международный, [рациональный](https://xkcd.com/1179/), и
независим от языка.
- Ясно указывает, использует ли проект [Семантическое
Версионирование][semver].
- Каждая версия должна:
- Показывать дату релиза в формате, упомянутом выше.
- Группировать изменения согласно их влиянию на проект следующим образом:
- `Added` для новых функций.
- `Changed` для изменений в существующей функциональности.
- `Deprecated` для функциональности, которая будет удалена в следующих
версиях.
- `Removed` для функциональности, которая удалена в этой версии.
- `Fixed` для любых исправлений.
- `Security` для обновлений безопасности.
### Как минимизировать время, необходимое для ведения лога изменений?
Всегда ведите секцию `Unreleased` в начале файла, чтобы держать в ней не
выпущенные изменения.
Это нужно для двух вещей:
- Люди смогут видеть, какие изменения ожидаются в ближайших релизах
- В момент релиза вам нужно всего лишь заменить секцию `Unreleased` на номер
версии и добавить новую секцию `Unreleased` в начале файла.
### Что заставляет плакать единорогов?
Хорошо… давайте разберёмся.
- **Выгрузка изменений лога коммитов.** Просто не делайте так, это никому не
принесёт пользы.
- **Отсутствие отметок планируемой к удалению функциональности.** Когда люди
обновляются от одной версии к другой, им должно быть очевидно до боли, что
сломается.
- **Даты в местном формате.** В Соединённых Штатах, люди сначала пишут месяц
(«06-02-2012» для даты 2 июня 2012, что не имеет *никакого* смысла), хотя
много людей в остальном мире пишет роботоподобное «2 июня 2012», всё ещё
произнося это по-другому. «2012-06-02» логично работает от самого большого
к самому маленькому, не пересекается с другими форматами дат, и является
[стандартом ISO](http://www.iso.org/iso/home/standards/iso8601.htm). Таким
образом, этот формат является рекомендуемым для логов изменений.
Существуют и другие. Помогите мне собрать слёзы единорогов,
[открыв тикет][issues] или пулл-реквест.
### Существует стандарт формата лога изменений?
К сожалению, нет. Спокойней. Я знаю, что вы яростно бросились на поиски
ссылки на GNU-руководства по стилю лога изменений, или на поиски файла
«guideline» с парой параграфов в GNU NEWS. GNU-руководство по стилю неплохо
для начала, но оно наивно. В наивности нет ничего плохого, но когда людям
нужно руководство, она редко бывает полезна. Особенно, когда приходиться
сталкиваться со множеством краевых случаев.
Этот проект [содержит информацию, которая, я надеюсь, станет соглашением
получше о ведении файлов CHANGELOG][CHANGELOG] для всех проектов с открытым
исходным кодом. Может ли сообщество учиться на своих ошибках, а не просто
действовать согласно десяти записям, которые были написаны много лет назал,
и, якобы, без одной ошибки? Хорошо. Поэтому, пожалуйста, посмотрите вокруг, и
помните, что [обсуждения и предложения по улучшению приветствуются][issues]!
### Как можно назвать файл лога изменений?
Ну, если вы не не можете ответить на этот вопрос, глядя на пример выше,
`CHANGELOG.md` пока наилучший вариант.
Некоторые проекты используют `HISTORY.txt`, `HISTORY.md`, `History.md`,
`NEWS.txt`, `NEWS.md`, `News.txt`, `RELEASES.txt`, `RELEASE.md`,
`releases.md`, и так далее.
Это непорядок. Все эти имена только усложняют поиск нужного файла.
### Почему люди не могут использовать просто дифф команды `git log`?
Потому, что диффы логов по своей природе содержат слишком много «шума». С их
помощью невозможно сделать подходящий лог изменений даже в гипотетическом
проекте, который делается идеальными программистами, которые никогда не
делают опечаток, никогда не забывают коммитить новые файлы, никогда не
пропускают ни одну часть рефакторинга. Назначение коммита в том, чтобы
задокументировать один атомарный шаг в процессе развития кода от одного
состояния к другому. Назначение лога изменений – документировать значимые
различия между этими состояниями.
Как отличаются хорошие комментарии к коду и сам код, также отличаются друг от
друга и лог изменений с логом коммитов: первые отвечают на вопрос
*почему*, а вторые на вопрос как.
### Могут ли логи изменений быть автоматически распарсены?
Это сложно из-за того, что люди следуют сильно отличающимся форматам и
соглашениям о именах файлов.
Гем для Руби [Vandamme][vandamme], который создали в команде
[Gemnasium][gemnasium], парсит многие (но не все) логи изменений проектов с
открытым исходным кодом.
### Почему вы пишите то «CHANGELOG», то «лог изменений»?
«CHANGELOG» – это имя файла. Оно несколько крикливо, но это историческое
соглашение, которому следуют многие проекты с открытым исходным кодом. В
качестве примеров подобных файлов можно привести [`README`][README],
[`LICENSE`][LICENSE], и [`CONTRIBUTING`][CONTRIBUTING].
Верхний регистр в имени файла (который в старых операционных системах
заставляет эти файлы находиться наверху списков) используется для привлечения
внимания. Так как в этих файлах содержится важная метаинформация о проекте,
они могут быть полезны любому использующему или дорабатывющему проект, также
как [бейджи проектов с открытым исходным кодом][shields].
Когда я упоминаю «лог изменений», я говорою о назначении этого файла: об
учёте изменений.
### Как насчёт yanked-релизов?
Yanked-релизы – это версии, которые изымаются из обращения из-за серьёзного
бага или проблемы безопасности в них. Часто такие версии даже не упоминаются
в логах изменений. А должны. И вот как вам следует их упоминать:
`## [0.0.5] - 2014-12-13 [YANKED]`
Тег `[YANKED]` такой «громкий» не просто так. Очень важно, чтобы люди его
заметили. А из-за того, что он окружён скобками, его легче определить
программно.
### Стоит ли переписывать лог изменений?
Конечно. Всегда есть причины для улучшения лога изменений. Я регулярно
открываю пулл-реквесты в проекты с открытым исходным кодом с
неподдерживаемыми логами изменений для добавления недостающих релизов.
Также вы можете обнаружить что вы забыли адресовать критичное изменение в
описании версии. В этом случае очевидно, что нужно обновить лог
изменений.
### Как я могу помочь?
Этот документ **не истина в последней инстанции**; это моё тщательно
сформулированное мнение вместе с информацией и примерами, которые я собрал.
Хотя я предоставил настоящий [CHANGELOG][] из [GitHub-репозитария][gh], я
специально избегал цели создать *стандарт* или чёткий список правил (как это
делает, например, [SemVer.org][semver]).
Я сделал это потому, что хочу, чтобы наше сообщество достигло консенсуса. Я
верю, что дискуссия также важна, как и её результат.
Так что, пожалуйста, [**участвуйте**][gh].
[CHANGELOG]: https://github.com/olivierlacan/keep-a-changelog/blob/master/CHANGELOG.md
[CONTRIBUTING]: https://github.com/olivierlacan/keep-a-changelog/blob/master/CONTRIBUTING.md
[LICENSE]: https://github.com/olivierlacan/keep-a-changelog/blob/master/LICENSE
[README]: https://github.com/olivierlacan/keep-a-changelog/blob/master/README.md
[gemnasium]: https://gemnasium.com/
[gh]: https://github.com/olivierlacan/keep-a-changelog
[issues]: https://github.com/olivierlacan/keep-a-changelog/issues
[semver]: https://semver.org/
[shields]: https://shields.io/
[thechangelog]: https://changelog.com/podcast/127
[vandamme]: https://github.com/tech-angels/vandamme/
|
{
"pile_set_name": "Github"
}
|
# The MIT License
#
# Copyright (c) 2004-2010, Sun Microsystems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
Console\ Output=Sortida de la consola
|
{
"pile_set_name": "Github"
}
|
# 왜 공부 해야하나요? (for/if만 알아도 되는데)
> 아래 글은 [제 브런치에 올렸던 글](https://brunch.co.kr/@jojoldu/16)을 기록 차원에서 블로그로 옮긴 글입니다.

```
"정기씨 아까 제가 꽃을 버려서 슬펐나요?
그건 신발이 진창에 빠졌을때 만큼 슬펐나요,
아니면 가까운 이가 아플때만큼 슬펐나요?
어떤 슬픔은 어렴풋한 슬픔이고, 어떤 슬픔은 처절한 슬픔이죠.
소소한 슬픔도,
아련한 슬픔도,
잊혀가는 슬픔도,
문득 기억이 떠올라 때때로 가슴이 아파지는 슬픔까지,
같은 슬픔조차도 사실은 전부 달라요.
책을 읽고 풍부한 단어를 알게 된다는건 슬픔의 저 끝에서부터, 기쁨의 저 끝까지.
자신이 가지고 있는 수많은 감정들의 결을 하나하나 구분해내는거에요.
정확히 그만큼의 감정을
정확히 그만큼의 단어로 집어내서
자신의 마음을 선명하게 들여다 보는거죠
내가 얼만큼 슬픈지, 얼만큼 기쁜지.
내가 무엇에 행복하고, 무엇에 불행한지.
자신의 마음이 자신을 위한 목적을 결정하도록.
자신의 마음을 타인에게 정확히 전달하도록.
나무도 바위도 없이 숨을 곳 하나없는 산 한복판에서 매에게 쫓기는 까투리의 마음이,
망망대해 한가운데 배에 곡식 가득 싣고
노도 잃고,
닻도 잃고,
돛줄도 끊어지고,
돛대도 꺾어지고,
바람에 물결치고,
안개는 자욱이 뒤섞이며,
사방은 어두워지고,
풍알 일 노을 뜨는데,
해적을 만난 사공의 마음이
엊그제 임을 잃은 제 마음에 비할수 있을까요.
같은 단어를 안다면 감정의 의미를 공유할 수 있고,
같은 문장을 이해할 수 있다면 감정의 흐름을 공유할 수 있어요.
그리고 그건 서로를 온전히 이해할 수 있게 만들죠."
```
[가담항설 90화에서](https://comic.naver.com/webtoon/detail.nhn?titleId=670144&no=93&weekday=thu)
프로그래밍은 for, if만 알면 된다 라고 얘기하며 공부하지 않는 사람들을 볼때마다 어떻게 표현해야 와닿을수 있을까 종종 생각했었다.
물론 유지보수성, 확장성 등등 변화에 쉽게 대응하기 위해서 라고 대답했지만, 교과서적인 이야기로 받아들이길래 더이상 해줄 수 있는 말은 없었다.
그러다가 웹툰을 보고 "와 이거구나" 라고 생각이 들었다.
내가 얼마만큼 힘든지 타인이 공감하려면 그만큼 단어로, 문장으로 잘 표현할 수 있어야 한다.
아는 단어와 문장이 부족하다면 결국 좋다/싫다/힘들다 외에는 표현할 방법이 없다.
마찬가지로 프로그래밍에서도 좁게는 제네릭, Enum, 예외처리부터 넓게는 자료구조, 객체지향, 디자인패턴까지, 공부를 하면 할수록 **내 의도를, 내 목표를 명확하게 표현할 수 있다**.
확장해서 쓰게 하고 싶었던 곳은 어디인지,
다른 사람이 못쓰게 막고 싶었던 방식은 무엇인지,
무시해도 될 것은 무엇인지 등등
이 코드에서 내가 하고자 하는 이야기가 무엇인지를 명확히 표현할 수 있게 된다.
내가 짠 코드를 다른 사람이 오해하지 않고,
타인의 코드를 보고 얼마만큼 고민했는지 이해하게 되고,
그 사람과 내가 같은 생각을 공유할 수 있다는 것은 너무 즐거운 일 아닐까?
for/if만 알면 된다는건, 내 감정을 좋다/싫다로만 표현하겠다는 것과 같다고 생각한다.
그게 과연 좋을까?
좀 더 자신이 표현할 수 있는 코드의 표현이 다양해지길 바라며.
|
{
"pile_set_name": "Github"
}
|
/*
Работа с GUI.
*/
#pragma once
namespace Gui
{
/*
Инициализация.
*/
void init(void);
/*
Деинициализация.
*/
void uninit(void);
/*
Кээлбэк для _enumWindows().
IN window - окно.
IN param - параметр.
Return - true - продолжить поиск,
false - прервать поиск.
*/
typedef bool (ENUMWINDOWSPROC)(HWND window, void *param);
/*
Перечисление дочерных окон.
IN owner - родитель, может быть NULL.
IN topToDown - true - перечислять с верху вниз, false - снизу вверх.
IN proc - кэлбэк.
IN param - параметр для кэлбэка.
*/
void _enumWindows(HWND owner, bool topToDown, ENUMWINDOWSPROC proc, void *param);
/*
Данная функция является обреткой для WindowFromPoint(), которая пропускает HTTRANSPARENT.
Способ реализации доволно наивен, но мне не удалсоь найти более нормального способа.
IN point - координаты для поиска окна.
IN timeout - таймаут для WM_NCHITTEST.
OUT hitTest - HitTest окна. Может быть NULL.
Return - хэндл окна, или NULL.
*/
HWND _windowFromPoint(POINT point, DWORD timeout, DWORD *hitTest);
/*
Проверяет имеет ли стиль окна бордюры с изменением размера.
IN style - стиль окна.
Return - true - стиль имеед бордюры,
false - не имеет.
*/
bool _styleHaveSizeBorders(DWORD style);
/*
Загрузка иконки как shared (не трубует удаления).
IN module - моудль.
IN id - ID.
*/
HICON _loadSharedIcon(HMODULE module, const LPWSTR id);
/*
Получение текста окна с выделением памяти.
IN window - окно.
OUT size - размер строки без нулевого соимвола. Может быть NULL.
Return - текст окна (нужно освободить через NULL), или NULL в случаи ошибки.
*/
LPWSTR _getWindowText(HWND window, LPDWORD size);
/*
Загрузка курсора как shared (не трубует удаления).
IN module - моудль.
IN id - ID.
*/
HCURSOR _loadSharedCursor(HMODULE module, const LPWSTR id);
/*
Создание шрифта FONT_DIALOG.
IN pointSize - размер шрифта в поинтах, рекомендуется значение 8.
Return - хэндл шрифта, или NULL в случаи ошибки.
*/
HFONT _createDialogFont(BYTE pointSize);
/*
Запуск диалога выбора файла.
IN owner - хэндл родителя
IN initialDir - директория отностиельно который открывается диалог. Может быть NULL.
IN OUT fileBuffer - на входе - инициализационный путь/файл,
на выходе - выбранный файл.
Return - true - в случаи успеха,
false - в случаи провала.
*/
bool _browseForFile(HWND owner, LPWSTR initialDir, LPWSTR fileBuffer);
/*
Запуск диалога сохранения файла.
IN owner - хэндл родителя
IN initialDir - директория отностиельно который открывается диалог. Может быть NULL.
IN OUT fileBuffer - на входе - инициализационный путь/файл,
на выходе - выбранный файл.
IN defaultExtension - расширение по умолчанию (без точки). Может быть NULL.
IN filter - фильтр. См. OPENFILENAME.lpstrFilter.
IN filterIndex - выделеный индекс элемента в filter.
Return - true - в случаи успеха,
false - в случаи провала.
*/
bool _browseForSaveFile(HWND owner, LPWSTR initialDir, LPWSTR fileBuffer, LPWSTR defaultExtension, LPWSTR filter, DWORD filterIndex);
/*
Инициализация общих контролев (надстройка для InitCommonControlsEx()).
IN classes - ICC_*.
Return - true - в случаи успеха,
false - в случаи ошибки.
*/
bool _loadCommonControl(DWORD classes);
};
|
{
"pile_set_name": "Github"
}
|
# The MIT License
#
# Copyright (c) 2004-2010, Sun Microsystems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
Last\ Successful\ Artifacts=Senaste lyckade artefakter
Recent\ Changes=Senaste f\u00F6r\u00E4ndringar
Workspace=Arbetsyta
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head><title>Package Overview</title>
<!--
Copyright (c) 2007 Henri Sivonen
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
-->
</head>
<body bgcolor="white">
<p>This package provides common interfaces and enumerations.</p>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
*
* https://www.gz-yami.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.bean.vo;
import lombok.Data;
@Data
public class SysUserVO {
/**
* 用户id
*/
private String userId;
/**
* 用户名
*/
private String username;
}
|
{
"pile_set_name": "Github"
}
|
//
// AppDelegate.h
// Obj-C SDK
//
// Copyright © 2015 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
{
"pile_set_name": "Github"
}
|
/*
* _______ _ _ _____ ____
* |__ __| | | | |/ ____| _ \
* | | ___ ___ _ __ _ _| | | | (___ | |_) |
* | |/ _ \/ _ \ '_ \| | | | | | |\___ \| _ <
* | | __/ __/ | | | |_| | |__| |____) | |_) |
* |_|\___|\___|_| |_|\__, |\____/|_____/|____/
* __/ |
* |___/
*
* TeenyUSB - light weight usb stack for STM32 micro controllers
*
* Copyright (c) 2019 XToolBox - admin@xtoolbox.org
* www.tusb.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef __TEENY_USB_HOST_H__
#define __TEENY_USB_HOST_H__
#include "teeny_usb.h"
#endif
|
{
"pile_set_name": "Github"
}
|
/*
Copyright (c) 2013 Khaled Mammou - Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once
#ifndef O3DGC_INDEXED_FACE_SET_H
#define O3DGC_INDEXED_FACE_SET_H
#include "o3dgcCommon.h"
namespace o3dgc
{
template<class T>
class IndexedFaceSet
{
public:
//! Constructor.
IndexedFaceSet(void)
{
memset(this, 0, sizeof(IndexedFaceSet));
m_ccw = true;
m_solid = true;
m_convex = true;
m_isTriangularMesh = true;
m_creaseAngle = 30;
};
//! Destructor.
~IndexedFaceSet(void) {};
unsigned long GetNCoordIndex() const { return m_nCoordIndex ;}
// only coordIndex is supported
unsigned long GetNCoord() const { return m_nCoord ;}
unsigned long GetNNormal() const { return m_nNormal ;}
unsigned long GetNFloatAttribute(unsigned long a) const
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
return m_nFloatAttribute[a];
}
unsigned long GetNIntAttribute(unsigned long a) const
{
assert(a < O3DGC_SC3DMC_MAX_NUM_INT_ATTRIBUTES);
return m_nIntAttribute[a];
}
unsigned long GetNumFloatAttributes() const { return m_numFloatAttributes;}
unsigned long GetNumIntAttributes() const { return m_numIntAttributes ;}
const Real * GetCoordMin () const { return m_coordMin;}
const Real * GetCoordMax () const { return m_coordMax;}
const Real * GetNormalMin () const { return m_normalMin;}
const Real * GetNormalMax () const { return m_normalMax;}
Real GetCoordMin (int j) const { return m_coordMin[j] ;}
Real GetCoordMax (int j) const { return m_coordMax[j] ;}
Real GetNormalMin (int j) const { return m_normalMin[j] ;}
Real GetNormalMax (int j) const { return m_normalMax[j] ;}
O3DGCIFSFloatAttributeType GetFloatAttributeType(unsigned long a) const
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
return m_typeFloatAttribute[a];
}
O3DGCIFSIntAttributeType GetIntAttributeType(unsigned long a) const
{
assert(a < O3DGC_SC3DMC_MAX_NUM_INT_ATTRIBUTES);
return m_typeIntAttribute[a];
}
unsigned long GetFloatAttributeDim(unsigned long a) const
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
return m_dimFloatAttribute[a];
}
unsigned long GetIntAttributeDim(unsigned long a) const
{
assert(a < O3DGC_SC3DMC_MAX_NUM_INT_ATTRIBUTES);
return m_dimIntAttribute[a];
}
const Real * GetFloatAttributeMin(unsigned long a) const
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
return &(m_minFloatAttribute[a * O3DGC_SC3DMC_MAX_DIM_ATTRIBUTES]);
}
const Real * GetFloatAttributeMax(unsigned long a) const
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
return &(m_maxFloatAttribute[a * O3DGC_SC3DMC_MAX_DIM_ATTRIBUTES]);
}
Real GetFloatAttributeMin(unsigned long a, unsigned long dim) const
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
assert(dim < O3DGC_SC3DMC_MAX_DIM_ATTRIBUTES);
return m_minFloatAttribute[a * O3DGC_SC3DMC_MAX_DIM_ATTRIBUTES + dim];
}
Real GetFloatAttributeMax(unsigned long a, unsigned long dim) const
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
assert(dim < O3DGC_SC3DMC_MAX_DIM_ATTRIBUTES);
return m_maxFloatAttribute[a * O3DGC_SC3DMC_MAX_DIM_ATTRIBUTES + dim];
}
Real GetCreaseAngle() const { return m_creaseAngle ;}
bool GetCCW() const { return m_ccw ;}
bool GetSolid() const { return m_solid ;}
bool GetConvex() const { return m_convex ;}
bool GetIsTriangularMesh() const { return m_isTriangularMesh;}
const unsigned long * GetIndexBufferID() const { return m_indexBufferID ;}
const T * GetCoordIndex() const { return m_coordIndex;}
T * GetCoordIndex() { return m_coordIndex;}
Real * GetCoord() const { return m_coord ;}
Real * GetNormal() const { return m_normal ;}
Real * GetFloatAttribute(unsigned long a) const
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
return m_floatAttribute[a];
}
long * GetIntAttribute(unsigned long a) const
{
assert(a < O3DGC_SC3DMC_MAX_NUM_INT_ATTRIBUTES);
return m_intAttribute[a] ;
}
// only coordIndex is supported
void SetNNormalIndex(unsigned long) {}
void SetNTexCoordIndex(unsigned long) {}
void SetNFloatAttributeIndex(int, unsigned long) {}
void SetNIntAttributeIndex (int, unsigned long) {}
// per triangle attributes not supported
void SetNormalPerVertex(bool) {}
void SetColorPerVertex(bool) {}
void SetFloatAttributePerVertex(int, bool){}
void SetIntAttributePerVertex (int, bool){}
void SetNCoordIndex (unsigned long nCoordIndex) { m_nCoordIndex = nCoordIndex;}
void SetNCoord (unsigned long nCoord) { m_nCoord = nCoord ;}
void SetNNormal (unsigned long nNormal) { m_nNormal = nNormal ;}
void SetNumFloatAttributes(unsigned long numFloatAttributes)
{
assert(numFloatAttributes < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
m_numFloatAttributes = numFloatAttributes;
}
void SetNumIntAttributes (unsigned long numIntAttributes)
{
assert(numIntAttributes < O3DGC_SC3DMC_MAX_NUM_INT_ATTRIBUTES);
m_numIntAttributes = numIntAttributes;
}
void SetCreaseAngle (Real creaseAngle) { m_creaseAngle = creaseAngle ;}
void SetCCW (bool ccw) { m_ccw = ccw ;}
void SetSolid (bool solid) { m_solid = solid ;}
void SetConvex (bool convex) { m_convex = convex ;}
void SetIsTriangularMesh (bool isTriangularMesh) { m_isTriangularMesh = isTriangularMesh;}
void SetCoordMin (int j, Real min) { m_coordMin[j] = min;}
void SetCoordMax (int j, Real max) { m_coordMax[j] = max;}
void SetNormalMin (int j, Real min) { m_normalMin[j] = min;}
void SetNormalMax (int j, Real max) { m_normalMax[j] = max;}
void SetNFloatAttribute(unsigned long a, unsigned long nFloatAttribute)
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
m_nFloatAttribute[a] = nFloatAttribute;
}
void SetNIntAttribute(unsigned long a, unsigned long nIntAttribute)
{
assert(a < O3DGC_SC3DMC_MAX_NUM_INT_ATTRIBUTES);
m_nIntAttribute[a] = nIntAttribute;
}
void SetFloatAttributeDim(unsigned long a, unsigned long d)
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
m_dimFloatAttribute[a] = d;
}
void SetIntAttributeDim(unsigned long a, unsigned long d)
{
assert(a < O3DGC_SC3DMC_MAX_NUM_INT_ATTRIBUTES);
m_dimIntAttribute[a] = d;
}
void SetFloatAttributeType(unsigned long a, O3DGCIFSFloatAttributeType t)
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
m_typeFloatAttribute[a] = t;
}
void SetIntAttributeType(unsigned long a, O3DGCIFSIntAttributeType t)
{
assert(a < O3DGC_SC3DMC_MAX_NUM_INT_ATTRIBUTES);
m_typeIntAttribute[a] = t;
}
void SetFloatAttributeMin(unsigned long a, unsigned long dim, Real min)
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
assert(dim < O3DGC_SC3DMC_MAX_DIM_ATTRIBUTES);
m_minFloatAttribute[a * O3DGC_SC3DMC_MAX_DIM_ATTRIBUTES + dim] = min;
}
void SetFloatAttributeMax(unsigned long a, unsigned long dim, Real max)
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
assert(dim < O3DGC_SC3DMC_MAX_DIM_ATTRIBUTES);
m_maxFloatAttribute[a * O3DGC_SC3DMC_MAX_DIM_ATTRIBUTES + dim] = max;
}
void SetIndexBufferID (unsigned long * const indexBufferID) { m_indexBufferID = indexBufferID;}
void SetCoordIndex (T * const coordIndex) { m_coordIndex = coordIndex;}
void SetCoord (Real * const coord ) { m_coord = coord ;}
void SetNormal (Real * const normal ) { m_normal = normal ;}
void SetFloatAttribute (unsigned long a, Real * const floatAttribute)
{
assert(a < O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES);
m_floatAttribute[a] = floatAttribute;
}
void SetIntAttribute (unsigned long a, long * const intAttribute)
{
assert(a < O3DGC_SC3DMC_MAX_NUM_INT_ATTRIBUTES);
m_intAttribute[a] = intAttribute ;
}
void ComputeMinMax(O3DGCSC3DMCQuantizationMode quantMode);
private:
// triangles list
unsigned long m_nCoordIndex;
T * m_coordIndex;
unsigned long * m_indexBufferID;
// coord, normals, texcoord and color
unsigned long m_nCoord;
unsigned long m_nNormal;
Real m_coordMin [3];
Real m_coordMax [3];
Real m_normalMin [3];
Real m_normalMax [3];
Real * m_coord;
Real * m_normal;
// other attributes
unsigned long m_numFloatAttributes;
unsigned long m_numIntAttributes;
O3DGCIFSFloatAttributeType m_typeFloatAttribute [O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES];
O3DGCIFSIntAttributeType m_typeIntAttribute [O3DGC_SC3DMC_MAX_NUM_INT_ATTRIBUTES ];
unsigned long m_nFloatAttribute [O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES];
unsigned long m_nIntAttribute [O3DGC_SC3DMC_MAX_NUM_INT_ATTRIBUTES ];
unsigned long m_dimFloatAttribute [O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES];
unsigned long m_dimIntAttribute [O3DGC_SC3DMC_MAX_NUM_INT_ATTRIBUTES ];
Real m_minFloatAttribute [O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES * O3DGC_SC3DMC_MAX_DIM_ATTRIBUTES];
Real m_maxFloatAttribute [O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES * O3DGC_SC3DMC_MAX_DIM_ATTRIBUTES];
Real * m_floatAttribute [O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES];
long * m_intAttribute [O3DGC_SC3DMC_MAX_NUM_FLOAT_ATTRIBUTES];
// mesh info
Real m_creaseAngle;
bool m_ccw;
bool m_solid;
bool m_convex;
bool m_isTriangularMesh;
};
}
#include "o3dgcIndexedFaceSet.inl" // template implementation
#endif // O3DGC_INDEXED_FACE_SET_H
|
{
"pile_set_name": "Github"
}
|
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
public class CC1004 {
public int x;
public void M() {
x = 5;
Contract.Ensures(x > 5); // not warned about because we skip Model extraction in rewriter
}
}
|
{
"pile_set_name": "Github"
}
|
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
|
{
"pile_set_name": "Github"
}
|
@bracketMatching
@matchBrackets
@MatchResult
|
{
"pile_set_name": "Github"
}
|
//
// Luminosity.swift
// RandomColorSwift
//
// Copyright (c) 2016 Wei Wang (http://onevcat.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public enum Luminosity: Int {
case bright, light, dark
case random
}
|
{
"pile_set_name": "Github"
}
|
/**
******************************************************************************
* @file startup_stm32f410rx.s
* @author MCD Application Team
* @brief STM32F410Rx Devices vector table for GCC based toolchains.
* This module performs:
* - Set the initial SP
* - Set the initial PC == Reset_Handler,
* - Set the vector table entries with the exceptions ISR address
* - Branches to main in the C library (which eventually
* calls main()).
* After Reset the Cortex-M4 processor is in Thread mode,
* priority is Privileged, and the Stack is set to Main.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
.syntax unified
.cpu cortex-m4
.fpu softvfp
.thumb
.global g_pfnVectors
.global Default_Handler
/* start address for the initialization values of the .data section.
defined in linker script */
.word _sidata
/* start address for the .data section. defined in linker script */
.word _sdata
/* end address for the .data section. defined in linker script */
.word _edata
/* start address for the .bss section. defined in linker script */
.word _sbss
/* end address for the .bss section. defined in linker script */
.word _ebss
/* stack used for SystemInit_ExtMemCtl; always internal RAM used */
/**
* @brief This is the code that gets called when the processor first
* starts execution following a reset event. Only the absolutely
* necessary set is performed, after which the application
* supplied main() routine is called.
* @param None
* @retval : None
*/
.section .text.Reset_Handler
.weak Reset_Handler
.type Reset_Handler, %function
Reset_Handler:
ldr sp, =_estack /* set stack pointer */
/* Copy the data segment initializers from flash to SRAM */
movs r1, #0
b LoopCopyDataInit
CopyDataInit:
ldr r3, =_sidata
ldr r3, [r3, r1]
str r3, [r0, r1]
adds r1, r1, #4
LoopCopyDataInit:
ldr r0, =_sdata
ldr r3, =_edata
adds r2, r0, r1
cmp r2, r3
bcc CopyDataInit
ldr r2, =_sbss
b LoopFillZerobss
/* Zero fill the bss segment. */
FillZerobss:
movs r3, #0
str r3, [r2], #4
LoopFillZerobss:
ldr r3, = _ebss
cmp r2, r3
bcc FillZerobss
/* Call the clock system intitialization function.*/
bl SystemInit
/* Call static constructors */
bl __libc_init_array
/* Call the application's entry point.*/
bl main
bx lr
.size Reset_Handler, .-Reset_Handler
/**
* @brief This is the code that gets called when the processor receives an
* unexpected interrupt. This simply enters an infinite loop, preserving
* the system state for examination by a debugger.
* @param None
* @retval None
*/
.section .text.Default_Handler,"ax",%progbits
Default_Handler:
Infinite_Loop:
b Infinite_Loop
.size Default_Handler, .-Default_Handler
/******************************************************************************
*
* The minimal vector table for a Cortex M3. Note that the proper constructs
* must be placed on this to ensure that it ends up at physical address
* 0x0000.0000.
*
*******************************************************************************/
.section .isr_vector,"a",%progbits
.type g_pfnVectors, %object
.size g_pfnVectors, .-g_pfnVectors
g_pfnVectors:
.word _estack
.word Reset_Handler
.word NMI_Handler
.word HardFault_Handler
.word MemManage_Handler
.word BusFault_Handler
.word UsageFault_Handler
.word 0
.word 0
.word 0
.word 0
.word SVC_Handler
.word DebugMon_Handler
.word 0
.word PendSV_Handler
.word SysTick_Handler
/* External Interrupts */
.word WWDG_IRQHandler /* Window WatchDog */
.word PVD_IRQHandler /* PVD through EXTI Line detection */
.word TAMP_STAMP_IRQHandler /* Tamper and TimeStamps through the EXTI line */
.word RTC_WKUP_IRQHandler /* RTC Wakeup through the EXTI line */
.word FLASH_IRQHandler /* FLASH */
.word RCC_IRQHandler /* RCC */
.word EXTI0_IRQHandler /* EXTI Line0 */
.word EXTI1_IRQHandler /* EXTI Line1 */
.word EXTI2_IRQHandler /* EXTI Line2 */
.word EXTI3_IRQHandler /* EXTI Line3 */
.word EXTI4_IRQHandler /* EXTI Line4 */
.word DMA1_Stream0_IRQHandler /* DMA1 Stream 0 */
.word DMA1_Stream1_IRQHandler /* DMA1 Stream 1 */
.word DMA1_Stream2_IRQHandler /* DMA1 Stream 2 */
.word DMA1_Stream3_IRQHandler /* DMA1 Stream 3 */
.word DMA1_Stream4_IRQHandler /* DMA1 Stream 4 */
.word DMA1_Stream5_IRQHandler /* DMA1 Stream 5 */
.word DMA1_Stream6_IRQHandler /* DMA1 Stream 6 */
.word ADC_IRQHandler /* ADC1, ADC2 and ADC3s */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word EXTI9_5_IRQHandler /* External Line[9:5]s */
.word TIM1_BRK_TIM9_IRQHandler /* TIM1 Break and TIM9 */
.word TIM1_UP_IRQHandler /* TIM1 Update */
.word TIM1_TRG_COM_TIM11_IRQHandler /* TIM1 Trigger and Commutation and TIM11 */
.word TIM1_CC_IRQHandler /* TIM1 Capture Compare */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word I2C1_EV_IRQHandler /* I2C1 Event */
.word I2C1_ER_IRQHandler /* I2C1 Error */
.word I2C2_EV_IRQHandler /* I2C2 Event */
.word I2C2_ER_IRQHandler /* I2C2 Error */
.word SPI1_IRQHandler /* SPI1 */
.word SPI2_IRQHandler /* SPI2 */
.word USART1_IRQHandler /* USART1 */
.word USART2_IRQHandler /* USART2 */
.word 0 /* Reserved */
.word EXTI15_10_IRQHandler /* External Line[15:10]s */
.word RTC_Alarm_IRQHandler /* RTC Alarm (A and B) through EXTI Line */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word DMA1_Stream7_IRQHandler /* DMA1 Stream7 */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word TIM5_IRQHandler /* TIM5 */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word TIM6_DAC_IRQHandler /* TIM6 and DAC */
.word 0 /* Reserved */
.word DMA2_Stream0_IRQHandler /* DMA2 Stream 0 */
.word DMA2_Stream1_IRQHandler /* DMA2 Stream 1 */
.word DMA2_Stream2_IRQHandler /* DMA2 Stream 2 */
.word DMA2_Stream3_IRQHandler /* DMA2 Stream 3 */
.word DMA2_Stream4_IRQHandler /* DMA2 Stream 4 */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word DMA2_Stream5_IRQHandler /* DMA2 Stream 5 */
.word DMA2_Stream6_IRQHandler /* DMA2 Stream 6 */
.word DMA2_Stream7_IRQHandler /* DMA2 Stream 7 */
.word USART6_IRQHandler /* USART6 */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word RNG_IRQHandler /* RNG */
.word FPU_IRQHandler /* FPU */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word SPI5_IRQHandler /* SPI5 */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word FMPI2C1_EV_IRQHandler /* FMPI2C1 Event */
.word FMPI2C1_ER_IRQHandler /* FMPI2C1 Error */
.word LPTIM1_IRQHandler /* LP TIM1 */
/*******************************************************************************
*
* Provide weak aliases for each Exception handler to the Default_Handler.
* As they are weak aliases, any function with the same name will override
* this definition.
*
*******************************************************************************/
.weak NMI_Handler
.thumb_set NMI_Handler,Default_Handler
.weak HardFault_Handler
.thumb_set HardFault_Handler,Default_Handler
.weak MemManage_Handler
.thumb_set MemManage_Handler,Default_Handler
.weak BusFault_Handler
.thumb_set BusFault_Handler,Default_Handler
.weak UsageFault_Handler
.thumb_set UsageFault_Handler,Default_Handler
.weak SVC_Handler
.thumb_set SVC_Handler,Default_Handler
.weak DebugMon_Handler
.thumb_set DebugMon_Handler,Default_Handler
.weak PendSV_Handler
.thumb_set PendSV_Handler,Default_Handler
.weak SysTick_Handler
.thumb_set SysTick_Handler,Default_Handler
.weak WWDG_IRQHandler
.thumb_set WWDG_IRQHandler,Default_Handler
.weak PVD_IRQHandler
.thumb_set PVD_IRQHandler,Default_Handler
.weak TAMP_STAMP_IRQHandler
.thumb_set TAMP_STAMP_IRQHandler,Default_Handler
.weak RTC_WKUP_IRQHandler
.thumb_set RTC_WKUP_IRQHandler,Default_Handler
.weak FLASH_IRQHandler
.thumb_set FLASH_IRQHandler,Default_Handler
.weak RCC_IRQHandler
.thumb_set RCC_IRQHandler,Default_Handler
.weak EXTI0_IRQHandler
.thumb_set EXTI0_IRQHandler,Default_Handler
.weak EXTI1_IRQHandler
.thumb_set EXTI1_IRQHandler,Default_Handler
.weak EXTI2_IRQHandler
.thumb_set EXTI2_IRQHandler,Default_Handler
.weak EXTI3_IRQHandler
.thumb_set EXTI3_IRQHandler,Default_Handler
.weak EXTI4_IRQHandler
.thumb_set EXTI4_IRQHandler,Default_Handler
.weak DMA1_Stream0_IRQHandler
.thumb_set DMA1_Stream0_IRQHandler,Default_Handler
.weak DMA1_Stream1_IRQHandler
.thumb_set DMA1_Stream1_IRQHandler,Default_Handler
.weak DMA1_Stream2_IRQHandler
.thumb_set DMA1_Stream2_IRQHandler,Default_Handler
.weak DMA1_Stream3_IRQHandler
.thumb_set DMA1_Stream3_IRQHandler,Default_Handler
.weak DMA1_Stream4_IRQHandler
.thumb_set DMA1_Stream4_IRQHandler,Default_Handler
.weak DMA1_Stream5_IRQHandler
.thumb_set DMA1_Stream5_IRQHandler,Default_Handler
.weak DMA1_Stream6_IRQHandler
.thumb_set DMA1_Stream6_IRQHandler,Default_Handler
.weak ADC_IRQHandler
.thumb_set ADC_IRQHandler,Default_Handler
.weak EXTI9_5_IRQHandler
.thumb_set EXTI9_5_IRQHandler,Default_Handler
.weak TIM1_BRK_TIM9_IRQHandler
.thumb_set TIM1_BRK_TIM9_IRQHandler,Default_Handler
.weak TIM1_UP_IRQHandler
.thumb_set TIM1_UP_IRQHandler,Default_Handler
.weak TIM1_TRG_COM_TIM11_IRQHandler
.thumb_set TIM1_TRG_COM_TIM11_IRQHandler,Default_Handler
.weak TIM1_CC_IRQHandler
.thumb_set TIM1_CC_IRQHandler,Default_Handler
.weak I2C1_EV_IRQHandler
.thumb_set I2C1_EV_IRQHandler,Default_Handler
.weak I2C1_ER_IRQHandler
.thumb_set I2C1_ER_IRQHandler,Default_Handler
.weak I2C2_EV_IRQHandler
.thumb_set I2C2_EV_IRQHandler,Default_Handler
.weak I2C2_ER_IRQHandler
.thumb_set I2C2_ER_IRQHandler,Default_Handler
.weak SPI1_IRQHandler
.thumb_set SPI1_IRQHandler,Default_Handler
.weak SPI2_IRQHandler
.thumb_set SPI2_IRQHandler,Default_Handler
.weak USART1_IRQHandler
.thumb_set USART1_IRQHandler,Default_Handler
.weak USART2_IRQHandler
.thumb_set USART2_IRQHandler,Default_Handler
.weak EXTI15_10_IRQHandler
.thumb_set EXTI15_10_IRQHandler,Default_Handler
.weak RTC_Alarm_IRQHandler
.thumb_set RTC_Alarm_IRQHandler,Default_Handler
.weak DMA1_Stream7_IRQHandler
.thumb_set DMA1_Stream7_IRQHandler,Default_Handler
.weak TIM5_IRQHandler
.thumb_set TIM5_IRQHandler,Default_Handler
.weak TIM6_DAC_IRQHandler
.thumb_set TIM6_DAC_IRQHandler,Default_Handler
.weak DMA2_Stream0_IRQHandler
.thumb_set DMA2_Stream0_IRQHandler,Default_Handler
.weak DMA2_Stream1_IRQHandler
.thumb_set DMA2_Stream1_IRQHandler,Default_Handler
.weak DMA2_Stream2_IRQHandler
.thumb_set DMA2_Stream2_IRQHandler,Default_Handler
.weak DMA2_Stream3_IRQHandler
.thumb_set DMA2_Stream3_IRQHandler,Default_Handler
.weak DMA2_Stream4_IRQHandler
.thumb_set DMA2_Stream4_IRQHandler,Default_Handler
.weak DMA2_Stream5_IRQHandler
.thumb_set DMA2_Stream5_IRQHandler,Default_Handler
.weak DMA2_Stream6_IRQHandler
.thumb_set DMA2_Stream6_IRQHandler,Default_Handler
.weak DMA2_Stream7_IRQHandler
.thumb_set DMA2_Stream7_IRQHandler,Default_Handler
.weak USART6_IRQHandler
.thumb_set USART6_IRQHandler,Default_Handler
.weak RNG_IRQHandler
.thumb_set RNG_IRQHandler,Default_Handler
.weak FPU_IRQHandler
.thumb_set FPU_IRQHandler,Default_Handler
.weak SPI5_IRQHandler
.thumb_set SPI5_IRQHandler,Default_Handler
.weak FMPI2C1_EV_IRQHandler
.thumb_set FMPI2C1_EV_IRQHandler,Default_Handler
.weak FMPI2C1_ER_IRQHandler
.thumb_set FMPI2C1_ER_IRQHandler,Default_Handler
.weak LPTIM1_IRQHandler
.thumb_set LPTIM1_IRQHandler,Default_Handler
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2017 WillowTree, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@import UIKit;
@interface HYPOverlayDebuggingViewController : UIViewController
@end
|
{
"pile_set_name": "Github"
}
|
# The MIT License
#
# Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Eric Lefevre-Ardant, Seiji Sogabe
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
Hudson\ is\ going\ to\ shut\ down=Hudson va s''\u00E9teindre
|
{
"pile_set_name": "Github"
}
|
/*
* The MIT License
*
* Copyright (c) 2017, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
pipeline {
agent none
stages {
stage("foo") {
matrix {
stages {
stage("first") {
agent {
label "first-agent"
}
steps {
echo "First stage, ${WHICH_AGENT}"
}
}
stage("second") {
stages {
stage("inner-first") {
agent {
label "second-agent"
}
tools {
maven "apache-maven-3.0.1"
}
steps {
echo "Second stage, ${WHICH_AGENT}"
script {
if (isUnix()) {
sh 'mvn --version'
} else {
bat 'mvn --version'
}
}
}
}
stage("inner-second") {
when {
expression {
return false
}
}
steps {
echo "WE SHOULD NEVER GET HERE"
}
}
}
}
}
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Mupen64plus - cheat.c *
* Mupen64Plus homepage: https://mupen64plus.org/ *
* Copyright (C) 2009 Richard Goedeken *
* Copyright (C) 2008 Okaygo *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* gameshark and xploder64 reference: http://doc.kodewerx.net/hacking_n64.html */
#include <SDL.h>
#include <SDL_thread.h>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cheat.h"
#include "eventloop.h"
#include "list.h"
#include "api/callbacks.h"
#include "api/m64p_types.h"
#include "device/r4300/r4300_core.h"
#include "device/rdram/rdram.h"
#include "osal/preproc.h"
/* local definitions */
#define CHEAT_CODE_MAGIC_VALUE UINT32_C(0xDEAD0000)
typedef struct cheat_code {
uint32_t address;
uint32_t value;
uint32_t old_value;
struct list_head list;
} cheat_code_t;
typedef struct cheat {
char *name;
int enabled;
int was_enabled;
struct list_head cheat_codes;
struct list_head list;
} cheat_t;
/* private functions */
static uint16_t read_address_16bit(struct r4300_core* r4300, uint32_t address)
{
return *(uint16_t*)(((unsigned char*)r4300->rdram->dram + ((address & 0xFFFFFF)^S16)));
}
static uint8_t read_address_8bit(struct r4300_core* r4300, uint32_t address)
{
return *(uint8_t*)(((unsigned char*)r4300->rdram->dram + ((address & 0xFFFFFF)^S8)));
}
static void update_address_16bit(struct r4300_core* r4300, uint32_t address, uint16_t new_value)
{
*(uint16_t*)(((unsigned char*)r4300->rdram->dram + ((address & 0xFFFFFF)^S16))) = new_value;
/* mask out bit 24 which is used by GS codes to specify 8/16 bits */
address &= 0xfeffffff;
invalidate_r4300_cached_code(r4300, address, 2);
}
static void update_address_8bit(struct r4300_core* r4300, uint32_t address, uint8_t new_value)
{
*(uint8_t*)(((unsigned char*)r4300->rdram->dram + ((address & 0xFFFFFF)^S8))) = new_value;
invalidate_r4300_cached_code(r4300, address, 1);
}
static int address_equal_to_8bit(struct r4300_core* r4300, uint32_t address, uint8_t value)
{
uint8_t value_read;
value_read = *(uint8_t*)(((unsigned char*)r4300->rdram->dram + ((address & 0xFFFFFF)^S8)));
return value_read == value;
}
static int address_equal_to_16bit(struct r4300_core* r4300, uint32_t address, uint16_t value)
{
uint16_t value_read;
value_read = *(unsigned short *)(((unsigned char*)r4300->rdram->dram + ((address & 0xFFFFFF)^S16)));
return value_read == value;
}
/* individual application - returns 0 if we are supposed to skip the next cheat
* (only really used on conditional codes)
*/
static int execute_cheat(struct r4300_core* r4300, uint32_t address, uint32_t value, uint32_t* old_value)
{
switch (address & 0xFF000000)
{
case 0x80000000:
case 0x88000000:
case 0xA0000000:
case 0xA8000000:
case 0xF0000000:
/* if pointer to old value is valid and uninitialized, write current value to it */
if (old_value && (*old_value == CHEAT_CODE_MAGIC_VALUE)) {
*old_value = read_address_8bit(r4300, address);
}
update_address_8bit(r4300, address, (uint8_t)value);
return 1;
case 0x81000000:
case 0x89000000:
case 0xA1000000:
case 0xA9000000:
case 0xF1000000:
/* if pointer to old value is valid and uninitialized, write current value to it */
if (old_value && (*old_value == CHEAT_CODE_MAGIC_VALUE)) {
*old_value = read_address_16bit(r4300, address);
}
update_address_16bit(r4300, address, (uint16_t)value);
return 1;
case 0xD0000000:
case 0xD8000000:
return address_equal_to_8bit(r4300, address, (uint8_t)value);
case 0xD1000000:
case 0xD9000000:
return address_equal_to_16bit(r4300, address, (uint16_t)value);
case 0xD2000000:
case 0xDB000000:
return !(address_equal_to_8bit(r4300, address, (uint8_t)value));
case 0xD3000000:
case 0xDA000000:
return !(address_equal_to_16bit(r4300, address, (uint16_t)value));
case 0xEE000000:
/* most likely, this doesnt do anything. */
execute_cheat(r4300, 0xF1000318, 0x0040, NULL);
execute_cheat(r4300, 0xF100031A, 0x0000, NULL);
return 1;
default:
return 1;
}
}
static cheat_t *find_or_create_cheat(struct cheat_ctx* ctx, const char *name)
{
cheat_t *cheat;
int found = 0;
list_for_each_entry_t(cheat, &ctx->active_cheats, cheat_t, list) {
if (strcmp(cheat->name, name) == 0) {
found = 1;
break;
}
}
if (found)
{
/* delete any pre-existing cheat codes */
cheat_code_t *code, *safe;
list_for_each_entry_safe_t(code, safe, &cheat->cheat_codes, cheat_code_t, list) {
list_del(&code->list);
free(code);
}
cheat->enabled = 0;
cheat->was_enabled = 0;
}
else
{
cheat = malloc(sizeof(*cheat));
cheat->name = strdup(name);
cheat->enabled = 0;
cheat->was_enabled = 0;
INIT_LIST_HEAD(&cheat->cheat_codes);
list_add_tail(&cheat->list, &ctx->active_cheats);
}
return cheat;
}
/* public functions */
void cheat_init(struct cheat_ctx* ctx)
{
ctx->mutex = SDL_CreateMutex();
INIT_LIST_HEAD(&ctx->active_cheats);
}
void cheat_uninit(struct cheat_ctx* ctx)
{
if (ctx->mutex != NULL) {
SDL_DestroyMutex(ctx->mutex);
}
ctx->mutex = NULL;
}
void cheat_apply_cheats(struct cheat_ctx* ctx, struct r4300_core* r4300, int entry)
{
cheat_t *cheat;
cheat_code_t *code;
int cond_failed;
if (list_empty(&ctx->active_cheats))
return;
if (ctx->mutex == NULL || SDL_LockMutex(ctx->mutex) != 0)
{
DebugMessage(M64MSG_ERROR, "Internal error: failed to lock mutex in cheat_apply_cheats()");
return;
}
list_for_each_entry_t(cheat, &ctx->active_cheats, cheat_t, list) {
if (cheat->enabled)
{
cheat->was_enabled = 1;
switch(entry)
{
case ENTRY_BOOT:
list_for_each_entry_t(code, &cheat->cheat_codes, cheat_code_t, list) {
/* code should only be written once at boot time */
if ((code->address & 0xF0000000) == 0xF0000000) {
execute_cheat(r4300, code->address, code->value, &code->old_value);
}
}
break;
case ENTRY_VI:
/* a cheat starts without failed preconditions */
cond_failed = 0;
list_for_each_entry_t(code, &cheat->cheat_codes, cheat_code_t, list) {
/* conditional cheat codes */
if ((code->address & 0xF0000000) == 0xD0000000)
{
/* if code needs GS button pressed and it's not, skip it */
if (((code->address & 0xFF000000) == 0xD8000000 ||
(code->address & 0xFF000000) == 0xD9000000 ||
(code->address & 0xFF000000) == 0xDA000000 ||
(code->address & 0xFF000000) == 0xDB000000) &&
!event_gameshark_active()) {
/* if condition false, skip next code non-test code */
cond_failed = 1;
}
/* if condition false, skip next code non-test code */
if (!execute_cheat(r4300, code->address, code->value, NULL)) {
cond_failed = 1;
}
}
else {
/* preconditions were false for this non-test code
* reset the condition state and skip the cheat
*/
if (cond_failed) {
cond_failed = 0;
continue;
}
switch (code->address & 0xFF000000) {
/* GS button triggers cheat code */
case 0x88000000:
case 0x89000000:
case 0xA8000000:
case 0xA9000000:
if (event_gameshark_active()) {
execute_cheat(r4300, code->address, code->value, NULL);
}
break;
/* normal cheat code */
default:
/* exclude boot-time cheat codes */
if ((code->address & 0xF0000000) != 0xF0000000) {
execute_cheat(r4300, code->address, code->value, &code->old_value);
}
break;
}
}
}
break;
default:
break;
}
}
/* if cheat was enabled, but is now disabled, restore old memory values */
else if (cheat->was_enabled)
{
cheat->was_enabled = 0;
switch(entry)
{
case ENTRY_VI:
list_for_each_entry_t(code, &cheat->cheat_codes, cheat_code_t, list) {
/* set memory back to old value and clear saved copy of old value */
if(code->old_value != CHEAT_CODE_MAGIC_VALUE)
{
execute_cheat(r4300, code->address, code->old_value, NULL);
code->old_value = CHEAT_CODE_MAGIC_VALUE;
}
}
break;
default:
break;
}
}
}
SDL_UnlockMutex(ctx->mutex);
}
void cheat_delete_all(struct cheat_ctx* ctx)
{
cheat_t *cheat, *safe_cheat;
cheat_code_t *code, *safe_code;
if (list_empty(&ctx->active_cheats))
return;
if (ctx->mutex == NULL || SDL_LockMutex(ctx->mutex) != 0)
{
DebugMessage(M64MSG_ERROR, "Internal error: failed to lock mutex in cheat_delete_all()");
return;
}
list_for_each_entry_safe_t(cheat, safe_cheat, &ctx->active_cheats, cheat_t, list) {
free(cheat->name);
list_for_each_entry_safe_t(code, safe_code, &cheat->cheat_codes, cheat_code_t, list) {
list_del(&code->list);
free(code);
}
list_del(&cheat->list);
free(cheat);
}
SDL_UnlockMutex(ctx->mutex);
}
int cheat_set_enabled(struct cheat_ctx* ctx, const char* name, int enabled)
{
cheat_t *cheat = NULL;
if (list_empty(&ctx->active_cheats))
return 0;
if (ctx->mutex == NULL || SDL_LockMutex(ctx->mutex) != 0)
{
DebugMessage(M64MSG_ERROR, "Internal error: failed to lock mutex in cheat_set_enabled()");
return 0;
}
list_for_each_entry_t(cheat, &ctx->active_cheats, cheat_t, list) {
if (strcmp(name, cheat->name) == 0)
{
cheat->enabled = enabled;
SDL_UnlockMutex(ctx->mutex);
return 1;
}
}
SDL_UnlockMutex(ctx->mutex);
return 0;
}
int cheat_add_new(struct cheat_ctx* ctx, const char* name, m64p_cheat_code* code_list, int num_codes)
{
cheat_t *cheat;
int i, j;
if (ctx->mutex == NULL || SDL_LockMutex(ctx->mutex) != 0)
{
DebugMessage(M64MSG_ERROR, "Internal error: failed to lock mutex in cheat_add_new()");
return 0;
}
/* create a new cheat function or erase the codes in an existing cheat function */
cheat = find_or_create_cheat(ctx, name);
if (cheat == NULL)
{
SDL_UnlockMutex(ctx->mutex);
return 0;
}
/* default for new cheats is enabled */
cheat->enabled = 1;
for (i = 0; i < num_codes; i++)
{
/* if this is a 'patch' code, convert it and dump out all of the individual codes */
if ((code_list[i].address & 0xFFFF0000) == 0x50000000 && i < num_codes - 1)
{
int code_count = ((code_list[i].address & 0xFF00) >> 8);
int incr_addr = code_list[i].address & 0xFF;
int incr_value = code_list[i].value;
int cur_addr = code_list[i+1].address;
int cur_value = code_list[i+1].value;
i += 1;
for (j = 0; j < code_count; j++)
{
cheat_code_t *code = malloc(sizeof(*code));
code->address = cur_addr;
code->value = cur_value;
code->old_value = CHEAT_CODE_MAGIC_VALUE;
list_add_tail(&code->list, &cheat->cheat_codes);
cur_addr += incr_addr;
cur_value += incr_value;
}
}
else
{
/* just a normal code */
cheat_code_t *code = malloc(sizeof(*code));
code->address = code_list[i].address;
code->value = code_list[i].value;
code->old_value = CHEAT_CODE_MAGIC_VALUE;
list_add_tail(&code->list, &cheat->cheat_codes);
}
}
SDL_UnlockMutex(ctx->mutex);
return 1;
}
static char *strtok_compat(char *str, const char *delim, char **saveptr)
{
char *p;
if (str == NULL)
str = *saveptr;
if (str == NULL)
return NULL;
str += strspn(str, delim);
if ((p = strpbrk(str, delim)) != NULL) {
*saveptr = p + 1;
*p = '\0';
} else {
*saveptr = NULL;
}
return str;
}
static int cheat_parse_hacks_code(char *code, m64p_cheat_code **hack)
{
char *saveptr = NULL;
char *input, *token;
int num_codes;
m64p_cheat_code *hackbuf;
int ret;
*hack = NULL;
/* count number of possible cheatcodes */
input = code;
num_codes = 0;
while ((strchr(input, ','))) {
input++;
num_codes++;
}
num_codes++;
/* allocate buffer */
hackbuf = malloc(sizeof(*hackbuf) * num_codes);
if (!hackbuf)
return 0;
/* parse cheatcodes */
input = code;
num_codes = 0;
while ((token = strtok_compat(input, ",", &saveptr))) {
input = NULL;
ret = sscanf(token, "%08" SCNx32 " %04X", &hackbuf[num_codes].address,
(unsigned int*)&hackbuf[num_codes].value);
if (ret == 2)
num_codes++;
}
if (num_codes == 0)
free(hackbuf);
else
*hack = hackbuf;
return num_codes;
}
int cheat_add_hacks(struct cheat_ctx* ctx, const char* rom_cheats)
{
char *cheat_raw = NULL;
char *saveptr = NULL;
char *input, *token;
unsigned int i = 0;
int num_codes;
char cheatname[32];
m64p_cheat_code *hack;
if (!rom_cheats)
return 0;
/* copy ini entry for tokenizing */
cheat_raw = strdup(rom_cheats);
if (!cheat_raw)
goto out;
/* split into cheats for the cheat engine */
input = cheat_raw;
while ((token = strtok_compat(input, ";", &saveptr))) {
input = NULL;
snprintf(cheatname, sizeof(cheatname), "HACK%u", i);
cheatname[sizeof(cheatname) - 1] = '\0';
/* parse and add cheat */
num_codes = cheat_parse_hacks_code(token, &hack);
if (num_codes <= 0)
continue;
cheat_add_new(ctx, cheatname, hack, num_codes);
free(hack);
i++;
}
out:
free(cheat_raw);
return 0;
}
|
{
"pile_set_name": "Github"
}
|
<!--
- The MIT License
-
- Copyright (c) 2011, Jeff Blaisdell
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
-->
<div>
The maximum number of tags to display in the dropdown. Any non-number value
will default to all.
</div>
|
{
"pile_set_name": "Github"
}
|
@mingw32-make
@pause
|
{
"pile_set_name": "Github"
}
|
#--
# Copyright (c) 2006 Philip Ross
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#++
module TZInfo
# Represents a timezone defined in a data module.
class TimezoneInfo #:nodoc:
# The timezone identifier.
attr_reader :identifier
# Constructs a new TimezoneInfo with an identifier.
def initialize(identifier)
@identifier = identifier
end
# Returns internal object state as a programmer-readable string.
def inspect
"#<#{self.class}: #@identifier>"
end
end
end
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Facebook.
*
* As with any software that integrates with the Facebook platform, your use of
* this software is subject to the Facebook Developer Principles and Policies
* [http://developers.facebook.com/policy/]. This copyright notice shall be
* included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Facebook.Unity
{
internal interface IInternalResult : IResult
{
/// <summary>
/// Gets the callback identifier.
/// </summary>
/// <value>A unique ID for this callback. This value should only be used internally.</value>
string CallbackId { get; }
}
}
|
{
"pile_set_name": "Github"
}
|
<p>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:</p>
<p>The above copyright notice and this permission notice shall be included in all copies of the Software and
its documentation and acknowledgment shall be given in the documentation and software packages that
this Software was used.</p>
<p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.</p>
|
{
"pile_set_name": "Github"
}
|
true
Byte
true
Short
true
Char
true
Int
true
Long
true
Float
true
Double
true
Boolean
true
Unit
true
Any
true
AnyVal
true
Object
true
Object
true
Null
true
Nothing
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0"?>
<!--
The MIT License
Copyright (c) 2014-2016 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<!--
Source = https://github.com/checkstyle/checkstyle/tree/master/src/main/resources
Checkstyle configurartion that checks the Google coding conventions from:
- Google Java Style
https://google-styleguide.googlecode.com/svn-history/r130/trunk/javaguide.html
Checkstyle is very configurable. Be sure to read the documentation at
http://checkstyle.sf.net (or in your downloaded distribution).
Most Checks are configurable, be sure to consult the documentation.
To completely disable a check, just comment it out or delete it from the file.
Authors: Max Vetrenko, Ruslan Diachenko, Roman Ivanov.
-->
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="fileExtensions" value="java, xml, properties"/>
<property name="severity" value="error"/>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="TreeWalker">
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format"
value="\\u00(08|09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message" value="Avoid using corresponding octal or Unicode escape."/>
</module>
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowByTailComment" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module>
<module name="LineLength">
<property name="max" value="120"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>
<module name="OneTopLevelClass"/>
<module name="NoLineWrap"/>
<module name="EmptyBlock">
<property name="option" value="TEXT"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
</module>
<module name="NeedBraces"/>
<module name="LeftCurly"/>
<module name="RightCurly"/>
<module name="RightCurly">
<property name="option" value="alone"/>
<property name="tokens"
value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, STATIC_INIT, INSTANCE_INIT"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLoops" value="true"/>
<message key="ws.notFollowed"
value="WhitespaceAround: ''{0}'' is not followed by whitespace."/>
<message key="ws.notPreceded"
value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
</module>
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="ArrayTypeStyle"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<module name="SeparatorWrap">
<property name="tokens" value="DOT"/>
<property name="option" value="nl"/>
</module>
<module name="SeparatorWrap">
<property name="tokens" value="COMMA"/>
<property name="option" value="EOL"/>
</module>
<!-- Checks for Naming Conventions. -->
<!-- See http://checkstyle.sf.net/config_naming.html -->
<module name="ConstantName"/>
<module name="LocalFinalVariableName"/>
<module name="LocalVariableName"/>
<module name="MemberName"/>
<module name="MethodName"/>
<module name="PackageName"/>
<module name="ParameterName"/>
<module name="StaticVariableName"/>
<module name="TypeName"/>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.followed"
value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded"
value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow"
value="GenericWhitespace ''{0}'' should followed by whitespace."/>
<message key="ws.notPreceded"
value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
</module>
<module name="Indentation">
<property name="basicOffset" value="2"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="2"/>
<property name="throwsIndent" value="4"/>
<property name="lineWrappingIndentation" value="4"/>
<property name="arrayInitIndent" value="2"/>
</module>
<module name="AbbreviationAsWordInName">
<property name="ignoreFinal" value="false"/>
<property name="allowedAbbreviationLength" value="1"/>
</module>
<module name="OverloadMethodsDeclarationOrder"/>
<module name="MethodParamPad"/>
<module name="OperatorWrap">
<property name="option" value="NL"/>
<property name="tokens"
value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR "/>
</module>
<module name="AnnotationLocation">
<property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
</module>
<module name="AnnotationLocation">
<property name="tokens" value="VARIABLE_DEF"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
<module name="NonEmptyAtclauseDescription"/>
<module name="JavadocTagContinuationIndentation"/>
<module name="AtclauseOrder">
<property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
<property name="target" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
</module>
<module name="JavadocMethod">
<property name="scope" value="public"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="minLineCount" value="2"/>
<property name="allowedAnnotations" value="Override, Test, Before, After, Parameters, Given, When, BeforeClass, AfterClass, Parameterized, ParameterizedTest, BeforeAll, BeforeEach"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
</module>
<module name="JavadocType">
<property name="scope" value="public"/>
<property name="allowUnknownTags" value="true"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
<message key="name.invalidPattern"
value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="SingleLineJavadoc"/>
</module>
</module>
|
{
"pile_set_name": "Github"
}
|
И вот вы по ту сторону стены. С ног до головы в расплавленном зефире.
Вы слышите нарастающий гул. Надвигается рой гигантских пчел.
Каждая величиной с ладонь.
Как вы будете спасаться от них?
[Притворитесь, что вы тоже пчела и начнете жужжать.](bee-too/bee-too.md)
[Посмотрите в зеркало](mirror/i-am-the-bee.md)
[Слепите из зефира меч в попытке защититься](sword/making-sword.md)
|
{
"pile_set_name": "Github"
}
|
Ace
Alaska
Anchor
Ant
Anthem
Apron
Armor
Army
Ash
Astronaut
Attic
Avalanche
Axe
Baby
Bacon
Balloon
Banana
Barbecue
Bass
Bath
Battle
Battleship
Bay
Beam
Bean
Beard
Bee
Beer
Bench
Bicycle
Big Bang
Big Ben
Bikini
Biscuit
Blacksmith
Blade
Blind
Blizzard
Blues
Boil
Bonsai
Book
Boss
Bowl
Bowler
Boxer
Brain
Brass
Brazil
Bread
Break
Brick
Bride
Brother
Bubble
Bucket
Bulb
Bunk
Butter
Butterfly
Cable
Caesar
Cake
Camp
Cane
Captain
Castle
Cave
Chain
Chalk
Cheese
Cherry
Chip
Christmas
Cleopatra
Clock
Cloud
Coach
Coast
Coffee
Collar
Columbus
Comb
Comet
Computer
Cone
Country
Cow
Cowboy
Crab
Craft
Crow
Crusader
Crystal
Cuckoo
Curry
Dash
Delta
Dentist
Desk
Director
Disk
Doll
Dollar
Door
Drawing
Dream
Dressing
Driver
Drone
Drum
Dryer
Dust
Dwarf
Ear
Earth
Earthquake
Easter
Eden
Egg
Einstein
Elephant
Farm
Fever
Fiddle
Flag
Flat
Flood
Floor
Foam
Fog
Frog
Frost
Fuel
Gangster
Garden
Gear
Genie
Glacier
Glasses
Goat
Goldilocks
Golf
Governor
Greenhouse
Groom
Guitar
Gum
Gymnast
Hair
Halloween
Hamburger
Hammer
Hawaii
Helmet
Hercules
Hide
Hit
Homer
Hose
House
Ice Age
Iceland
Igloo
Ink
Jail
Jellyfish
Jeweler
Joan of Arc
Jockey
Joker
Judge
Jumper
Kick
Kilt
King Arthur
Kiss
Kitchen
Knot
Kung Fu
Lace
Ladder
Laundry
Leaf
Leather
Lemonade
Letter
Lightning
Lip
Locust
Love
Lumberjack
Lunch
Magazine
Magician
Makeup
Manicure
Map
Maracas
Marathon
Mark
Medic
Memory
Mess
Meter
Microwave
Mile
Milk
Mill
Minotaur
Minute
Mirror
Miss
Mohawk
Mona Lisa
Monkey
Moses
Mosquito
Mother
Mountie
Mud
Mummy
Musketeer
Mustard
Napoleon
Nerve
Newton
Noah
Nose
Notre Dame
Nylon
Oasis
Onion
Pacific
Pad
Paddle
Page
Paint
Parade
Parrot
Patient
Pea
Peach
Peanut
Pearl
Pen
Penny
Pentagon
Pepper
Pew
Pig
Pillow
Pine
Pitcher
Pizza
Pocket
Polish
Polo
Pop
Popcorn
Potato
Potter
Powder
Puppet
Purse
Quack
Quarter
Radio
Rail
Rainbow
Ram
Ranch
Rat
Razor
Record
Reindeer
Rice
Rifle
Rip
River
Road
Rodeo
Roll
Rope
Rubber
Russia
Rust
Sack
Saddle
Sahara
Sail
Salad
Saloon
Salsa
Salt
Sand
Santa
Saw
Scarecrow
Scratch
Scroll
Second
Shampoo
Shed
Sheet
Shell
Sherlock
Sherwood
Shoot
Shorts
Shoulder
Shower
Sign
Silk
Sister
Skates
Ski
Skull
Sled
Sleep
Sling
Slipper
Sloth
Smell
Smoke
Smoothie
Snake
Snap
Soap
Soup
Sphinx
Spirit
Spoon
Spray
Spurs
Squash
Squirrel
St.Patrick
Stable
Stamp
Steam
Steel
Step
Stethoscope
Sticker
Storm
Story
Street
Sugar
Sumo
Sun
Swamp
Sweat
Sword
Tank
Taste
Tattoo
Tea
Team
Tear
Texas
Thunder
Tiger
Tin
Tip
Tipi
Toast
Tornado
Trick
Troll
Tunnel
Turtle
Tutu
Tuxedo
Univerity
Valentine
Vampire
Venus
Viking
Violet
Virus
Volcano
Volume
Wagon
Waitress
Walrus
Wedding
Werewolf
Wheel
Wheelchair
Whistle
Window
Wing
Wish
Wizard
Wonderland
Wood
Wool
Yellowstone
Zombie
|
{
"pile_set_name": "Github"
}
|
>Mycoplasma_agalactiae_5632_FP671138_gi|290752859|emb|CBH40834.1|
MSGKLLVPKIRFKEFTNAWEQEKLGNFGTSTGGSSIENFFNNNGKYKVISIGSFSEDNTYNDQGLRIDYS
PFIKDKILKKDNIVMILNDKSSEAKILGKALLIEKDDEFVYNQRVQKIDINKDRFLSKFIFTLLNSNSRE
KITLLAQGNTQIYVNWSSISSIEYLIPNLEEQSQISSLFSHLDSLITLHQRKLSSLKNLKNRLLDKMFCD
EKSQFPSIRFKEFTNAWEQWKARGILLPYRQKNDKNLTLISYSVSNKEGFVDQKEFFDEGGKAVYADKKN
SLIISFDTFAYNPSRINVGSIALFKNTINGLVSPIYEVFKVSANSNPDFIYLWFKSECFNKIVANNSNKS
VRDTLNLKQFEDNLLNLPVLQEQNKIAKLFSSLDSLITLHQRKLNSLKNIKNTLLEKMFV
|
{
"pile_set_name": "Github"
}
|
<html dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Цветовые палитры</title>
</head>
<style>
@import "manual.css";
</style>
<body>
<h3>Цветовые палитры</h3>
<p><strong><em>Обратите внимание: эта глава посвящена не управлению цветом, а изменению и управлению цветными <a href="WwFill.html">заливками</a>. Управление цветом описано в <a href="cms.html">отдельной главе</a>.</em></strong>
<p>В Scribus есть несколько методов для создания, импортирования и изменения сплошных цветов и цветовых наборов. Более того, в Scribus имеется хорошо развитый инструмент — <a href="colorwheel.html">модуль цветового круга</a>, — который помогает создавать и даже тестировать цветовые сочетания для людей с дальтонизмом.</p>
<h3>Почему наборы цветов?</h3>
<p>Ответ на вопрос в заголовке тесно связан с ответом на более простой вопрос, а именно: «Что такое цвет?» Правда в том, что на этот вопрос нет простого ответа, поскольку «цвет» может быть описан сотнями способов, например, как комбинация длин волн, как комбинация значений цвета в рамках определённой «цветовой модели», как категория в структуре, основанной на эстетических правилах, и так далее. В результате с течением времени было разработано много различных так называемых «цветовых моделей», многие из которых стали частью дисциплины под названием «цветоведение» — науки, которая сама по себе является «метанаукой», поскольку требует вклада со стороны многих различных дисциплин, включая физику, нейронауку, биологию, математику, технику и даже искусство, ремесло или литературу. На самом деле, понятие «цвета» относится к одним из немногих случаев, когда художники, такие как Иоганн Вольфганг фон Гёте или Альберт Генри Манселл, внесли значительный вклад в научный прогресс.</p>
<p>Пользователи графических программ, таких как Scribus, не обязаны изучать все тонкости науки о цвете, хотя кое-какие знания теории не помешают. На начальном уровне, однако, некоторое представление о проблемах, упомянутых выше, сильно помогает при работе с цветами, а карикатура ниже может быть первым шагом к пониманию того, о чём идёт речь:</p>
<p><img src="images/colrs-caricature.png" title="Названия цветов – Любезно предоставлено сайтом http://www.thedoghousediaries.com" alt="Названия цветов – Любезно предоставлено сайтом http://www.thedoghousediaries.com" hspace="20"></p>
<p>Как и в любой хорошей карикатуре, здесь есть доля истины, а именно — в том, что существуют различные уровни дифференциации и категоризации цветов, которые часто бывают крайне субъективны. Представьте себе двух человек, мужчину и женщину, обсуждающих по телефону выбор цвета для проекта — это будет практически невозможной задачей, поскольку и названия (субъективные) цветов, и восприятие цвета у них совершенно разные. Таким образом, заранее определённые наборы цветов на самом деле являются способом <b><i>взаимодействия</i></b> при работе с цветами, при этом исключается и обращение к субъективной цветовой модели, и сложная наука о цвете, а использование осмысленных названий для цветов в рамках данного набора цветов может ещё сильнее облегчить общение на тему цветов.</p>
<p>Создание наборов цветов также помогает поставщикам или проектам задавать ограниченный набор цветов, разрешённых для использования, что помогает поддерживать визуальное единообразие публикаций.</p>
<p>На практике цвета, доступные в цветовой палитре, или те, которые вы создаёте сами (и, таким образом, добавляете к существующей палитре), являются единственными, которые можно использовать в качестве цветов текста, заливки, линии или градиента.</p>
<h4>Цвета в цветовых палитрах Scribus</h4>
<p>Scribus поставляется с огромной коллекцией, содержащей более чем 150 полезных цветовых наборов, также называемых «палитрами» или «образчиками» (что может слегка вводить в заблуждение). Эти палитры служат для разных целей, каждая из которых будет описана в <a href="color3.html">отдельном документе</a>. Существуют палитры различных размеров, начиная от «Scribus Basic», коллекции основных цветов RGB и CMYK, до, например, «X11», которая включает в себя огромное количество цветов (RGB).</p>
<p>Цветовые палитры в Scribus могут содержать четыре различных типа цветов, каждый из которых использует различные визуальные индикаторы в диалоговых окнах цвета Scribus:</p>
<table width="80%" align="center" border="0" cellpadding="8" cellspacing="0">
<col width="2*">
<col width="2*">
<col width="auto">
<tbody>
<tr valign="top">
<td><img src="images/rgb.png"></td>
<td><p><b>Цвета RGB</b>: эти цвета определены в цветовой модели RGB. Каждый цвет описывается тремя основными цветами: красным, зелёным и синим.</p></td>
</tr>
<tr valign="top">
<td><img src="images/cmyk.png" align="top"></td>
<td><p><b>Цвета CMYK</b>: эти цвета описаны в цветовой модели CMYK. Каждый цвет описывается четырьмя цветами чернил, используемых в цветной печати: голубой, пурпурный, жёлтый и ключевой (=чёрный).</p></td>
</tr>
<tr valign="top">
<td><img src="images/spot.png"></td>
<td><p><b>Плашечные цвета</b>: они также называются «именованными цветами», но, поскольку другие цвета (RGB/CMYK) также могут иметь названия, термин «плашечный цвет» должен быть предпочтительным для однозначности. Хотя плашечный цвет может быть определён в цветовой модели RGB или CMYK, его основная цель — сохранение его <i>названия</i> в файле PDF или PostScript (отсюда и термин — «именованный цвет»). Название ссылается на реальный цвет, а полиграфическая компания может смешивать или покупать специальные чернила, которые будут соответствовать цвету в точности так, как определено ссылкой. Для каждого плашечного цвета требуется отдельная печатная форма, поэтому использовать плашечные цвета необходимо осторожно, ведь их использование делает процесс печати более дорогим. Типичными случаями использования плашечных цветов являются крайне специфичные оттенки корпоративных логотипов. Красная точка рядом со значком цветовой модели (RGB или CMYK) означает, что соответствующий цвет является плашечным.</p></td>
</tr>
<tr valign="top">
<td><img src="images/register.png"></td>
<td><p><b>Цвет совмещения</b>: это особый «цвет», используемый для меток приводки. Последние используются принтерами для определения успешности выполнения четырехцветной печати. Отображаемый как цвет CMYK, он фактически будет состоять из стольких цветов, сколько существует цветовых разграничений для одной или всех печатных форм. Каждая палитра может иметь только один цвет совмещения, обозначаемый значком мишени.</p></td>
</tr>
<tr valign="top">
<td><img src="images/alert.png"></td>
<td><p>Если вы работаете со всключенным <a href="cms.html">управлением цветом</a>, некоторые или даже все цвета в палитре могут находиться «вне гаммы», то есть, в зависимости от выбранного профиля ICC, цвет не может быть «переведён» из одной цветовой модели в другую, и может произойти сдвиг цвета. В таком случае вы увидите предупреждающий знак, расположенный рядом с цветом в списке.</p></td>
</tr>
</tbody>
</table>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
/**
******************************************************************************
* @file startup_stm32f446xx.s
* @author MCD Application Team
* @brief STM32F446xx Devices vector table for GCC toolchain.
* This module performs:
* - Set the initial SP
* - Set the initial PC == Reset_Handler,
* - Set the vector table entries with the exceptions ISR address
* - Branches to main in the C library (which eventually
* calls main()).
* After Reset the Cortex-M4 processor is in Thread mode,
* priority is Privileged, and the Stack is set to Main.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
.syntax unified
.cpu cortex-m4
.fpu softvfp
.thumb
.global g_pfnVectors
.global Default_Handler
/* start address for the initialization values of the .data section.
defined in linker script */
.word _sidata
/* start address for the .data section. defined in linker script */
.word _sdata
/* end address for the .data section. defined in linker script */
.word _edata
/* start address for the .bss section. defined in linker script */
.word _sbss
/* end address for the .bss section. defined in linker script */
.word _ebss
/* stack used for SystemInit_ExtMemCtl; always internal RAM used */
/**
* @brief This is the code that gets called when the processor first
* starts execution following a reset event. Only the absolutely
* necessary set is performed, after which the application
* supplied main() routine is called.
* @param None
* @retval : None
*/
.section .text.Reset_Handler
.weak Reset_Handler
.type Reset_Handler, %function
Reset_Handler:
ldr sp, =_estack /* set stack pointer */
/* Copy the data segment initializers from flash to SRAM */
movs r1, #0
b LoopCopyDataInit
CopyDataInit:
ldr r3, =_sidata
ldr r3, [r3, r1]
str r3, [r0, r1]
adds r1, r1, #4
LoopCopyDataInit:
ldr r0, =_sdata
ldr r3, =_edata
adds r2, r0, r1
cmp r2, r3
bcc CopyDataInit
ldr r2, =_sbss
b LoopFillZerobss
/* Zero fill the bss segment. */
FillZerobss:
movs r3, #0
str r3, [r2], #4
LoopFillZerobss:
ldr r3, = _ebss
cmp r2, r3
bcc FillZerobss
/* Call the clock system intitialization function.*/
bl SystemInit
/* Call static constructors */
bl __libc_init_array
/* Call the application's entry point.*/
bl main
bx lr
.size Reset_Handler, .-Reset_Handler
/**
* @brief This is the code that gets called when the processor receives an
* unexpected interrupt. This simply enters an infinite loop, preserving
* the system state for examination by a debugger.
* @param None
* @retval None
*/
.section .text.Default_Handler,"ax",%progbits
Default_Handler:
Infinite_Loop:
b Infinite_Loop
.size Default_Handler, .-Default_Handler
/******************************************************************************
*
* The minimal vector table for a Cortex M3. Note that the proper constructs
* must be placed on this to ensure that it ends up at physical address
* 0x0000.0000.
*
*******************************************************************************/
.section .isr_vector,"a",%progbits
.type g_pfnVectors, %object
.size g_pfnVectors, .-g_pfnVectors
g_pfnVectors:
.word _estack
.word Reset_Handler
.word NMI_Handler
.word HardFault_Handler
.word MemManage_Handler
.word BusFault_Handler
.word UsageFault_Handler
.word 0
.word 0
.word 0
.word 0
.word SVC_Handler
.word DebugMon_Handler
.word 0
.word PendSV_Handler
.word SysTick_Handler
/* External Interrupts */
.word WWDG_IRQHandler /* Window WatchDog */
.word PVD_IRQHandler /* PVD through EXTI Line detection */
.word TAMP_STAMP_IRQHandler /* Tamper and TimeStamps through the EXTI line */
.word RTC_WKUP_IRQHandler /* RTC Wakeup through the EXTI line */
.word FLASH_IRQHandler /* FLASH */
.word RCC_IRQHandler /* RCC */
.word EXTI0_IRQHandler /* EXTI Line0 */
.word EXTI1_IRQHandler /* EXTI Line1 */
.word EXTI2_IRQHandler /* EXTI Line2 */
.word EXTI3_IRQHandler /* EXTI Line3 */
.word EXTI4_IRQHandler /* EXTI Line4 */
.word DMA1_Stream0_IRQHandler /* DMA1 Stream 0 */
.word DMA1_Stream1_IRQHandler /* DMA1 Stream 1 */
.word DMA1_Stream2_IRQHandler /* DMA1 Stream 2 */
.word DMA1_Stream3_IRQHandler /* DMA1 Stream 3 */
.word DMA1_Stream4_IRQHandler /* DMA1 Stream 4 */
.word DMA1_Stream5_IRQHandler /* DMA1 Stream 5 */
.word DMA1_Stream6_IRQHandler /* DMA1 Stream 6 */
.word ADC_IRQHandler /* ADC1, ADC2 and ADC3s */
.word CAN1_TX_IRQHandler /* CAN1 TX */
.word CAN1_RX0_IRQHandler /* CAN1 RX0 */
.word CAN1_RX1_IRQHandler /* CAN1 RX1 */
.word CAN1_SCE_IRQHandler /* CAN1 SCE */
.word EXTI9_5_IRQHandler /* External Line[9:5]s */
.word TIM1_BRK_TIM9_IRQHandler /* TIM1 Break and TIM9 */
.word TIM1_UP_TIM10_IRQHandler /* TIM1 Update and TIM10 */
.word TIM1_TRG_COM_TIM11_IRQHandler /* TIM1 Trigger and Commutation and TIM11 */
.word TIM1_CC_IRQHandler /* TIM1 Capture Compare */
.word TIM2_IRQHandler /* TIM2 */
.word TIM3_IRQHandler /* TIM3 */
.word TIM4_IRQHandler /* TIM4 */
.word I2C1_EV_IRQHandler /* I2C1 Event */
.word I2C1_ER_IRQHandler /* I2C1 Error */
.word I2C2_EV_IRQHandler /* I2C2 Event */
.word I2C2_ER_IRQHandler /* I2C2 Error */
.word SPI1_IRQHandler /* SPI1 */
.word SPI2_IRQHandler /* SPI2 */
.word USART1_IRQHandler /* USART1 */
.word USART2_IRQHandler /* USART2 */
.word USART3_IRQHandler /* USART3 */
.word EXTI15_10_IRQHandler /* External Line[15:10]s */
.word RTC_Alarm_IRQHandler /* RTC Alarm (A and B) through EXTI Line */
.word OTG_FS_WKUP_IRQHandler /* USB OTG FS Wakeup through EXTI line */
.word TIM8_BRK_TIM12_IRQHandler /* TIM8 Break and TIM12 */
.word TIM8_UP_TIM13_IRQHandler /* TIM8 Update and TIM13 */
.word TIM8_TRG_COM_TIM14_IRQHandler /* TIM8 Trigger and Commutation and TIM14 */
.word TIM8_CC_IRQHandler /* TIM8 Capture Compare */
.word DMA1_Stream7_IRQHandler /* DMA1 Stream7 */
.word FMC_IRQHandler /* FMC */
.word SDIO_IRQHandler /* SDIO */
.word TIM5_IRQHandler /* TIM5 */
.word SPI3_IRQHandler /* SPI3 */
.word UART4_IRQHandler /* UART4 */
.word UART5_IRQHandler /* UART5 */
.word TIM6_DAC_IRQHandler /* TIM6 and DAC1&2 underrun errors */
.word TIM7_IRQHandler /* TIM7 */
.word DMA2_Stream0_IRQHandler /* DMA2 Stream 0 */
.word DMA2_Stream1_IRQHandler /* DMA2 Stream 1 */
.word DMA2_Stream2_IRQHandler /* DMA2 Stream 2 */
.word DMA2_Stream3_IRQHandler /* DMA2 Stream 3 */
.word DMA2_Stream4_IRQHandler /* DMA2 Stream 4 */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word CAN2_TX_IRQHandler /* CAN2 TX */
.word CAN2_RX0_IRQHandler /* CAN2 RX0 */
.word CAN2_RX1_IRQHandler /* CAN2 RX1 */
.word CAN2_SCE_IRQHandler /* CAN2 SCE */
.word OTG_FS_IRQHandler /* USB OTG FS */
.word DMA2_Stream5_IRQHandler /* DMA2 Stream 5 */
.word DMA2_Stream6_IRQHandler /* DMA2 Stream 6 */
.word DMA2_Stream7_IRQHandler /* DMA2 Stream 7 */
.word USART6_IRQHandler /* USART6 */
.word I2C3_EV_IRQHandler /* I2C3 event */
.word I2C3_ER_IRQHandler /* I2C3 error */
.word OTG_HS_EP1_OUT_IRQHandler /* USB OTG HS End Point 1 Out */
.word OTG_HS_EP1_IN_IRQHandler /* USB OTG HS End Point 1 In */
.word OTG_HS_WKUP_IRQHandler /* USB OTG HS Wakeup through EXTI */
.word OTG_HS_IRQHandler /* USB OTG HS */
.word DCMI_IRQHandler /* DCMI */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word FPU_IRQHandler /* FPU */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word SPI4_IRQHandler /* SPI4 */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word SAI1_IRQHandler /* SAI1 */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word 0 /* Reserved */
.word SAI2_IRQHandler /* SAI2 */
.word QUADSPI_IRQHandler /* QuadSPI */
.word CEC_IRQHandler /* CEC */
.word SPDIF_RX_IRQHandler /* SPDIF RX */
.word FMPI2C1_EV_IRQHandler /* FMPI2C 1 Event */
.word FMPI2C1_ER_IRQHandler /* FMPI2C 1 Error */
/*******************************************************************************
*
* Provide weak aliases for each Exception handler to the Default_Handler.
* As they are weak aliases, any function with the same name will override
* this definition.
*
*******************************************************************************/
.weak NMI_Handler
.thumb_set NMI_Handler,Default_Handler
.weak HardFault_Handler
.thumb_set HardFault_Handler,Default_Handler
.weak MemManage_Handler
.thumb_set MemManage_Handler,Default_Handler
.weak BusFault_Handler
.thumb_set BusFault_Handler,Default_Handler
.weak UsageFault_Handler
.thumb_set UsageFault_Handler,Default_Handler
.weak SVC_Handler
.thumb_set SVC_Handler,Default_Handler
.weak DebugMon_Handler
.thumb_set DebugMon_Handler,Default_Handler
.weak PendSV_Handler
.thumb_set PendSV_Handler,Default_Handler
.weak SysTick_Handler
.thumb_set SysTick_Handler,Default_Handler
.weak WWDG_IRQHandler
.thumb_set WWDG_IRQHandler,Default_Handler
.weak PVD_IRQHandler
.thumb_set PVD_IRQHandler,Default_Handler
.weak TAMP_STAMP_IRQHandler
.thumb_set TAMP_STAMP_IRQHandler,Default_Handler
.weak RTC_WKUP_IRQHandler
.thumb_set RTC_WKUP_IRQHandler,Default_Handler
.weak FLASH_IRQHandler
.thumb_set FLASH_IRQHandler,Default_Handler
.weak RCC_IRQHandler
.thumb_set RCC_IRQHandler,Default_Handler
.weak EXTI0_IRQHandler
.thumb_set EXTI0_IRQHandler,Default_Handler
.weak EXTI1_IRQHandler
.thumb_set EXTI1_IRQHandler,Default_Handler
.weak EXTI2_IRQHandler
.thumb_set EXTI2_IRQHandler,Default_Handler
.weak EXTI3_IRQHandler
.thumb_set EXTI3_IRQHandler,Default_Handler
.weak EXTI4_IRQHandler
.thumb_set EXTI4_IRQHandler,Default_Handler
.weak DMA1_Stream0_IRQHandler
.thumb_set DMA1_Stream0_IRQHandler,Default_Handler
.weak DMA1_Stream1_IRQHandler
.thumb_set DMA1_Stream1_IRQHandler,Default_Handler
.weak DMA1_Stream2_IRQHandler
.thumb_set DMA1_Stream2_IRQHandler,Default_Handler
.weak DMA1_Stream3_IRQHandler
.thumb_set DMA1_Stream3_IRQHandler,Default_Handler
.weak DMA1_Stream4_IRQHandler
.thumb_set DMA1_Stream4_IRQHandler,Default_Handler
.weak DMA1_Stream5_IRQHandler
.thumb_set DMA1_Stream5_IRQHandler,Default_Handler
.weak DMA1_Stream6_IRQHandler
.thumb_set DMA1_Stream6_IRQHandler,Default_Handler
.weak ADC_IRQHandler
.thumb_set ADC_IRQHandler,Default_Handler
.weak CAN1_TX_IRQHandler
.thumb_set CAN1_TX_IRQHandler,Default_Handler
.weak CAN1_RX0_IRQHandler
.thumb_set CAN1_RX0_IRQHandler,Default_Handler
.weak CAN1_RX1_IRQHandler
.thumb_set CAN1_RX1_IRQHandler,Default_Handler
.weak CAN1_SCE_IRQHandler
.thumb_set CAN1_SCE_IRQHandler,Default_Handler
.weak EXTI9_5_IRQHandler
.thumb_set EXTI9_5_IRQHandler,Default_Handler
.weak TIM1_BRK_TIM9_IRQHandler
.thumb_set TIM1_BRK_TIM9_IRQHandler,Default_Handler
.weak TIM1_UP_TIM10_IRQHandler
.thumb_set TIM1_UP_TIM10_IRQHandler,Default_Handler
.weak TIM1_TRG_COM_TIM11_IRQHandler
.thumb_set TIM1_TRG_COM_TIM11_IRQHandler,Default_Handler
.weak TIM1_CC_IRQHandler
.thumb_set TIM1_CC_IRQHandler,Default_Handler
.weak TIM2_IRQHandler
.thumb_set TIM2_IRQHandler,Default_Handler
.weak TIM3_IRQHandler
.thumb_set TIM3_IRQHandler,Default_Handler
.weak TIM4_IRQHandler
.thumb_set TIM4_IRQHandler,Default_Handler
.weak I2C1_EV_IRQHandler
.thumb_set I2C1_EV_IRQHandler,Default_Handler
.weak I2C1_ER_IRQHandler
.thumb_set I2C1_ER_IRQHandler,Default_Handler
.weak I2C2_EV_IRQHandler
.thumb_set I2C2_EV_IRQHandler,Default_Handler
.weak I2C2_ER_IRQHandler
.thumb_set I2C2_ER_IRQHandler,Default_Handler
.weak SPI1_IRQHandler
.thumb_set SPI1_IRQHandler,Default_Handler
.weak SPI2_IRQHandler
.thumb_set SPI2_IRQHandler,Default_Handler
.weak USART1_IRQHandler
.thumb_set USART1_IRQHandler,Default_Handler
.weak USART2_IRQHandler
.thumb_set USART2_IRQHandler,Default_Handler
.weak USART3_IRQHandler
.thumb_set USART3_IRQHandler,Default_Handler
.weak EXTI15_10_IRQHandler
.thumb_set EXTI15_10_IRQHandler,Default_Handler
.weak RTC_Alarm_IRQHandler
.thumb_set RTC_Alarm_IRQHandler,Default_Handler
.weak OTG_FS_WKUP_IRQHandler
.thumb_set OTG_FS_WKUP_IRQHandler,Default_Handler
.weak TIM8_BRK_TIM12_IRQHandler
.thumb_set TIM8_BRK_TIM12_IRQHandler,Default_Handler
.weak TIM8_UP_TIM13_IRQHandler
.thumb_set TIM8_UP_TIM13_IRQHandler,Default_Handler
.weak TIM8_TRG_COM_TIM14_IRQHandler
.thumb_set TIM8_TRG_COM_TIM14_IRQHandler,Default_Handler
.weak TIM8_CC_IRQHandler
.thumb_set TIM8_CC_IRQHandler,Default_Handler
.weak DMA1_Stream7_IRQHandler
.thumb_set DMA1_Stream7_IRQHandler,Default_Handler
.weak FMC_IRQHandler
.thumb_set FMC_IRQHandler,Default_Handler
.weak SDIO_IRQHandler
.thumb_set SDIO_IRQHandler,Default_Handler
.weak TIM5_IRQHandler
.thumb_set TIM5_IRQHandler,Default_Handler
.weak SPI3_IRQHandler
.thumb_set SPI3_IRQHandler,Default_Handler
.weak UART4_IRQHandler
.thumb_set UART4_IRQHandler,Default_Handler
.weak UART5_IRQHandler
.thumb_set UART5_IRQHandler,Default_Handler
.weak TIM6_DAC_IRQHandler
.thumb_set TIM6_DAC_IRQHandler,Default_Handler
.weak TIM7_IRQHandler
.thumb_set TIM7_IRQHandler,Default_Handler
.weak DMA2_Stream0_IRQHandler
.thumb_set DMA2_Stream0_IRQHandler,Default_Handler
.weak DMA2_Stream1_IRQHandler
.thumb_set DMA2_Stream1_IRQHandler,Default_Handler
.weak DMA2_Stream2_IRQHandler
.thumb_set DMA2_Stream2_IRQHandler,Default_Handler
.weak DMA2_Stream3_IRQHandler
.thumb_set DMA2_Stream3_IRQHandler,Default_Handler
.weak DMA2_Stream4_IRQHandler
.thumb_set DMA2_Stream4_IRQHandler,Default_Handler
.weak CAN2_TX_IRQHandler
.thumb_set CAN2_TX_IRQHandler,Default_Handler
.weak CAN2_RX0_IRQHandler
.thumb_set CAN2_RX0_IRQHandler,Default_Handler
.weak CAN2_RX1_IRQHandler
.thumb_set CAN2_RX1_IRQHandler,Default_Handler
.weak CAN2_SCE_IRQHandler
.thumb_set CAN2_SCE_IRQHandler,Default_Handler
.weak OTG_FS_IRQHandler
.thumb_set OTG_FS_IRQHandler,Default_Handler
.weak DMA2_Stream5_IRQHandler
.thumb_set DMA2_Stream5_IRQHandler,Default_Handler
.weak DMA2_Stream6_IRQHandler
.thumb_set DMA2_Stream6_IRQHandler,Default_Handler
.weak DMA2_Stream7_IRQHandler
.thumb_set DMA2_Stream7_IRQHandler,Default_Handler
.weak USART6_IRQHandler
.thumb_set USART6_IRQHandler,Default_Handler
.weak I2C3_EV_IRQHandler
.thumb_set I2C3_EV_IRQHandler,Default_Handler
.weak I2C3_ER_IRQHandler
.thumb_set I2C3_ER_IRQHandler,Default_Handler
.weak OTG_HS_EP1_OUT_IRQHandler
.thumb_set OTG_HS_EP1_OUT_IRQHandler,Default_Handler
.weak OTG_HS_EP1_IN_IRQHandler
.thumb_set OTG_HS_EP1_IN_IRQHandler,Default_Handler
.weak OTG_HS_WKUP_IRQHandler
.thumb_set OTG_HS_WKUP_IRQHandler,Default_Handler
.weak OTG_HS_IRQHandler
.thumb_set OTG_HS_IRQHandler,Default_Handler
.weak DCMI_IRQHandler
.thumb_set DCMI_IRQHandler,Default_Handler
.weak FPU_IRQHandler
.thumb_set FPU_IRQHandler,Default_Handler
.weak SPI4_IRQHandler
.thumb_set SPI4_IRQHandler,Default_Handler
.weak SAI1_IRQHandler
.thumb_set SAI1_IRQHandler,Default_Handler
.weak SAI2_IRQHandler
.thumb_set SAI2_IRQHandler,Default_Handler
.weak QUADSPI_IRQHandler
.thumb_set QUADSPI_IRQHandler,Default_Handler
.weak CEC_IRQHandler
.thumb_set CEC_IRQHandler,Default_Handler
.weak SPDIF_RX_IRQHandler
.thumb_set SPDIF_RX_IRQHandler,Default_Handler
.weak FMPI2C1_EV_IRQHandler
.thumb_set FMPI2C1_EV_IRQHandler,Default_Handler
.weak FMPI2C1_ER_IRQHandler
.thumb_set FMPI2C1_ER_IRQHandler,Default_Handler
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
{
"pile_set_name": "Github"
}
|
/*
* The MIT License
*
* Copyright (c) 2016, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
@Library('zot-stuff@master')
import org.foo.Zot
@Library('zot-stuff@master')
import org.foo.Zot
def z = new Zot(steps)
pipeline {
agent any
stages {
stage ('prepare') {
steps {
script {
z.echo("hello")
}
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
# one
---
example
|
{
"pile_set_name": "Github"
}
|
{
"title": "SETTINGS",
"groups": [
{
"title": "EDITOR",
"items": [
{
"title": "THEME",
"type": "list",
"key": "editor.theme",
"value": 38,
"items": [
"3024-day",
"3024-night",
"abcdef",
"ambiance-mobile",
"ambiance",
"base16-dark",
"base16-light",
"bespin",
"blackboard",
"cobalt",
"colorforth",
"darcula",
"dracula",
"duotone-dark",
"duotone-light",
"eclipse",
"elegant",
"erlang-dark",
"gruvbox-dark",
"hopscotch",
"icecoder",
"idea",
"isotope",
"lesser-dark",
"liquibyte",
"lucario",
"material-darker",
"material-ocean",
"material-palenight",
"material",
"mbo",
"mdn-like",
"midnight",
"monokai",
"moxer",
"neat",
"neo",
"night",
"nord",
"oceanic-next",
"panda-syntax",
"paraiso-dark",
"paraiso-light",
"pastel-on-dark",
"railscasts",
"rubyblue",
"seti",
"shadowfox",
"solarized",
"ssms",
"the-matrix",
"tomorrow-night-bright",
"tomorrow-night-eighties",
"ttcn",
"twilight",
"vibrant-ink",
"xq-dark",
"xq-light",
"yeti",
"yonce",
"zenburn"
]
},
{
"title": "FONT_NAME",
"type": "list",
"key": "editor.font.name",
"value": 0,
"items": [
"Menlo",
"Source Code Pro",
"Monaco",
"Iosevka",
"Ubuntu Mono",
"Hack",
"Cascadia Code"
]
},
{
"title": "FONT_SIZE",
"type": "number",
"key": "editor.font.size",
"value": 15
},
{
"title": "LINE_HEIGHT",
"type": "number",
"key": "editor.line.height",
"value": 20
},
{
"title": "SHOWS_LINE_NUMBERS",
"type": "boolean",
"key": "editor.line.numbers",
"value": false
},
{
"title": "SHOWS_INVISIBLES",
"type": "boolean",
"key": "editor.invisibles",
"value": false
},
{
"title": "RUN_PRETTIER",
"type": "script",
"value": "$app.notify({'name': 'prettify'})"
}
]
},
{
"title": "WINDOW",
"items": [
{
"title": "MAX_WIDTH",
"type": "string",
"key": "window.width.max",
"value": "150%"
},
{
"title": "HORIZONTAL_PADDING",
"type": "number",
"key": "window.padding.x",
"value": 10
},
{
"title": "VERTICAL_PADDING",
"type": "number",
"key": "window.padding.y",
"value": 10
},
{
"title": "SHADOW_OFFSET_X",
"type": "number",
"key": "window.shadow.x",
"value": 10
},
{
"title": "SHADOW_OFFSET_Y",
"type": "number",
"key": "window.shadow.y",
"value": 10
},
{
"title": "SHADOW_RADIUS",
"type": "number",
"key": "window.shadow.radius",
"value": 15
},
{
"title": "BACKGROUND_COLOR",
"type": "string",
"key": "window.bg.color",
"value": "#FFFFFF"
},
{
"title": "BACKGROUND_ALPHA",
"type": "number",
"key": "window.bg.alpha",
"value": 0
}
]
},
{
"title": "",
"items": [
{
"title": "ABOUT",
"type": "script",
"value": "require('scripts/readme').open();"
}
]
}
]
}
|
{
"pile_set_name": "Github"
}
|
# The MIT License
#
# Italian localization plugin for Jenkins
# Copyright © 2020 Alessandro Menti
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
title=Dump thread di {0}
Thread\ Dump=Dump thread
|
{
"pile_set_name": "Github"
}
|
==Phrack Inc.==
Volume One, Issue Nine, Phile #7 of 10
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
(512)-396-1120
The Shack // presents
A Multi-User Chat Program for DEC-10s
Original Program by
TTY-Man
Modified and Clarified by
+++The Mentor+++
October 6th, 1986
Intro: Unlike its more sophisticated older brother, the VAX, the DEC has no
easy-to-use communication system like the VMS PHONE utility. The following
program makes use of the MIC file type available on most DECs. Each user that
wishes to be involved in the conference needs to run the program from his area
using the .DO COM command. The program can be entered with any editor (I
recommend SED if you have VT52 emulation), and should be saved as COM.MIC. The
program does not assume any specific terminal type or emulation. You will
have to know the TTY number of any person you wish to add to the conference,
but this is available through a .SYSTAT command or .R WHO (see below.)
SYSTAT
This is an example of a SYSTAT to used to determine TTY#...
Status of Saturn 7.03.2 at 7:27:51 on 03-Oct-86
Uptime 40:41:14, 77% Null time = 77% Idle + 0% Lost, 9% Overhead
27 Jobs in use out of 128. 27 logged in (LOGMAX of 127), 16 detached.
PPN# TTY# CURR SIZE
19 [OPR] 6 OPR 56+39 HB 18
20 7,20 5 OPR 23+39 HB 24 $
21 2501,1007 56 COMPIL 8+8 ^C 1:34 $
22 66,1012 57 TECO 10+12 TI 39
23 66,1011 62 1022 16+55 TI 36 $
24 [SELF] 64 SYSTAT 23+SPY RN 0 $
26 [OPR] DET STOMPR 10+9 SL 2
27 16011,1003 DET DIRECT 17+32 ^C 30 $
36 [OPR] DET FILDAE 17 HB 1:57
The TTY# is available in the TTY column... DET means that the user is
detached and is unavailable for chatting...
Below is an example of .R WHO to obtain the same information...
/- jobs in use out of 127.
Job Who Line PPN
20 OPERATOR 20 5 7,20
21 DISPONDENT 56 2501,1007
22 ADP-TBO 57 66,1012
23 ADP-MDL 62 66,1011
24 THE MENTOR 64 XXXX,XXX
27 GEO4440103 Det 16011,1003
In each case, I am on TTY# 64...
Anyway, use the following program, it's more convenient that doing a
.SEN <tty> every time you want to send a message. Also, to shut out an
annoying sender, use .SET TTY GAG. To remove, .SET TTY NO GAG... pretty
simple, huh?
start::
!
!Now in loop: 'a 'b 'c 'd 'e 'f
!
.mic input A,"Destination Terminal 1:"
.if ($a="") .goto welcome
.mic input B,"Destination Terminal 2:"
.if ($b="") .goto welcome
.mic input C,"Destination Terminal 3:"
.if ($c="") .goto welcome
.mic input D,"Destination Terminal 4:"
.if ($d="") .goto welcome
.mic input E,"Destination Terminal 5:"
.if ($e="") .goto welcome
.mic input F,"Destination Terminal 6:"
.if ($f="") .goto welcome
welcome::
!Sending Hello Message...
sen 'a Conference Forming on TTYs 'b 'c 'd 'e 'f ... DO COM to these to join'
sen 'b Conference Forming on TTYs 'a 'c 'd 'e 'f ... DO COM to these to join'
sen 'c Conference Forming on TTYs 'a 'b 'd 'e 'f ... DO COM to these to join'
sen 'd Conference Forming on TTYs 'a 'b 'c 'e 'f ... DO COM to these to join'
sen 'e Conference Forming on TTYs 'a 'b 'c 'd 'f ... DO COM to these to join'
sen 'f Conference Forming on TTYs 'a 'b 'c 'd 'e ... DO COM to these to join'
!
!Type /h for help
com::
.mic input G,"T>"
!Checking Commands.. Wait..
.if ($g="/h") .goto help
.if ($g="/k") .goto kill
.if ($g="/l") .goto list
.if ($g="/d") .goto drop
.if ($g="/t") .goto time
.if ($g="/w") .goto who
.if ($g="/u") .goto users
.if ($g="/q") .goto quit
.if ($g="/r") .backto start
.if ($g="/ac") .goto ack
!Transmitting.. Wait..
sen 'a 'g
sen 'b 'g
sen 'c 'g
sen 'd 'g
sen 'e 'g
sen 'f 'g
.backto com
help::
!
! Internal Commands
!
! /H -> This Menu /K -> Kill
! /L -> List Terminals /U -> Users
! /W -> R who /AC-> Alert Caller
! /Q -> Quit
! /R -> Restart/Add
! /T -> Show Date/Time
! /D -> Drop Caller
!
! All Commands must be in lower case.
!
.backto com
list::
!
!Currently Connected To Terminals: 'a 'b 'c 'd 'e 'f
!
.backto com
who::
.revive
.r who
'<silence>
.backto com
users::
.revive
.r users
'<silence>
.BACKTO COM
QUIT::
!
!Call The Shack... 512-396-1120 300/1200 24 hours
!
.mic cancel
drop::
!
!Send Hangup Message:: Enter Terminal Number To Be Disconnected.
!
.mic input h,"Destination Terminal Number:"
.sen 'h <=- Communication Terminated at '<time> -=>
.backto start
ack::
.mic input h,"Destination Terminal Number:"
.sen 'h %TMRR - Timeout Error, Response Required, Please ACKNOWLEDGE!
.backto com
kill::
!
!Send Message To Specific Terminal In A Loop
.mic input n,"Are You Sure (Y/N)?"
.if ($n="y") then .goto k1
!%Function Aborted - Returning To Communication Mode.
.backto com
k1::
.mic input h,"Destination Terminal Number:"
.mic input n,"K>"
dog::
!Transmitting...CTRL-C Aborts!
.sen 'h'n
.backto dog
time::
!
!Current Date : '<date>
!Current Time : '<time>
!
.backto com
Wasn't that neat? A feature that you can implement separately to be a
pain in the ass is the recursive MIC that sends an annoying message to a
specified terminal. It is almost impossible for them to shut you out without
logging out unless they are already gagged.
Just create a small MIC file called BUG.MIC... to do it in two lines,
simply type...
.SEN <tty # goes here> Eat hot photons, Vogon slime!
.DO BUG
That's it! I hope this comes in useful to someone out there! Give us
a call at The Shack... 512-396-1120 300/1200 baud, 24 hours a day... And a
special welcome to all the feds who will doubtlessly be calling since the
number appears in here... we have nothing to hide!
+++The Mentor+++
|
{
"pile_set_name": "Github"
}
|
/**
******************************************************************************
* @file stm32f10x_adc.h
* @author MCD Application Team
* @version V3.5.0
* @date 11-March-2011
* @brief This file contains all the functions prototypes for the ADC firmware
* library.
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2011 STMicroelectronics</center></h2>
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F10x_ADC_H
#define __STM32F10x_ADC_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
/** @addtogroup STM32F10x_StdPeriph_Driver
* @{
*/
/** @addtogroup ADC
* @{
*/
/** @defgroup ADC_Exported_Types
* @{
*/
/**
* @brief ADC Init structure definition
*/
typedef struct
{
uint32_t ADC_Mode; /*!< Configures the ADC to operate in independent or
dual mode.
This parameter can be a value of @ref ADC_mode */
FunctionalState ADC_ScanConvMode; /*!< Specifies whether the conversion is performed in
Scan (multichannels) or Single (one channel) mode.
This parameter can be set to ENABLE or DISABLE */
FunctionalState ADC_ContinuousConvMode; /*!< Specifies whether the conversion is performed in
Continuous or Single mode.
This parameter can be set to ENABLE or DISABLE. */
uint32_t ADC_ExternalTrigConv; /*!< Defines the external trigger used to start the analog
to digital conversion of regular channels. This parameter
can be a value of @ref ADC_external_trigger_sources_for_regular_channels_conversion */
uint32_t ADC_DataAlign; /*!< Specifies whether the ADC data alignment is left or right.
This parameter can be a value of @ref ADC_data_align */
uint8_t ADC_NbrOfChannel; /*!< Specifies the number of ADC channels that will be converted
using the sequencer for regular channel group.
This parameter must range from 1 to 16. */
}ADC_InitTypeDef;
/**
* @}
*/
/** @defgroup ADC_Exported_Constants
* @{
*/
#define IS_ADC_ALL_PERIPH(PERIPH) (((PERIPH) == ADC1) || \
((PERIPH) == ADC2) || \
((PERIPH) == ADC3))
#define IS_ADC_DMA_PERIPH(PERIPH) (((PERIPH) == ADC1) || \
((PERIPH) == ADC3))
/** @defgroup ADC_mode
* @{
*/
#define ADC_Mode_Independent ((uint32_t)0x00000000)
#define ADC_Mode_RegInjecSimult ((uint32_t)0x00010000)
#define ADC_Mode_RegSimult_AlterTrig ((uint32_t)0x00020000)
#define ADC_Mode_InjecSimult_FastInterl ((uint32_t)0x00030000)
#define ADC_Mode_InjecSimult_SlowInterl ((uint32_t)0x00040000)
#define ADC_Mode_InjecSimult ((uint32_t)0x00050000)
#define ADC_Mode_RegSimult ((uint32_t)0x00060000)
#define ADC_Mode_FastInterl ((uint32_t)0x00070000)
#define ADC_Mode_SlowInterl ((uint32_t)0x00080000)
#define ADC_Mode_AlterTrig ((uint32_t)0x00090000)
#define IS_ADC_MODE(MODE) (((MODE) == ADC_Mode_Independent) || \
((MODE) == ADC_Mode_RegInjecSimult) || \
((MODE) == ADC_Mode_RegSimult_AlterTrig) || \
((MODE) == ADC_Mode_InjecSimult_FastInterl) || \
((MODE) == ADC_Mode_InjecSimult_SlowInterl) || \
((MODE) == ADC_Mode_InjecSimult) || \
((MODE) == ADC_Mode_RegSimult) || \
((MODE) == ADC_Mode_FastInterl) || \
((MODE) == ADC_Mode_SlowInterl) || \
((MODE) == ADC_Mode_AlterTrig))
/**
* @}
*/
/** @defgroup ADC_external_trigger_sources_for_regular_channels_conversion
* @{
*/
#define ADC_ExternalTrigConv_T1_CC1 ((uint32_t)0x00000000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigConv_T1_CC2 ((uint32_t)0x00020000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigConv_T2_CC2 ((uint32_t)0x00060000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigConv_T3_TRGO ((uint32_t)0x00080000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigConv_T4_CC4 ((uint32_t)0x000A0000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigConv_Ext_IT11_TIM8_TRGO ((uint32_t)0x000C0000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigConv_T1_CC3 ((uint32_t)0x00040000) /*!< For ADC1, ADC2 and ADC3 */
#define ADC_ExternalTrigConv_None ((uint32_t)0x000E0000) /*!< For ADC1, ADC2 and ADC3 */
#define ADC_ExternalTrigConv_T3_CC1 ((uint32_t)0x00000000) /*!< For ADC3 only */
#define ADC_ExternalTrigConv_T2_CC3 ((uint32_t)0x00020000) /*!< For ADC3 only */
#define ADC_ExternalTrigConv_T8_CC1 ((uint32_t)0x00060000) /*!< For ADC3 only */
#define ADC_ExternalTrigConv_T8_TRGO ((uint32_t)0x00080000) /*!< For ADC3 only */
#define ADC_ExternalTrigConv_T5_CC1 ((uint32_t)0x000A0000) /*!< For ADC3 only */
#define ADC_ExternalTrigConv_T5_CC3 ((uint32_t)0x000C0000) /*!< For ADC3 only */
#define IS_ADC_EXT_TRIG(REGTRIG) (((REGTRIG) == ADC_ExternalTrigConv_T1_CC1) || \
((REGTRIG) == ADC_ExternalTrigConv_T1_CC2) || \
((REGTRIG) == ADC_ExternalTrigConv_T1_CC3) || \
((REGTRIG) == ADC_ExternalTrigConv_T2_CC2) || \
((REGTRIG) == ADC_ExternalTrigConv_T3_TRGO) || \
((REGTRIG) == ADC_ExternalTrigConv_T4_CC4) || \
((REGTRIG) == ADC_ExternalTrigConv_Ext_IT11_TIM8_TRGO) || \
((REGTRIG) == ADC_ExternalTrigConv_None) || \
((REGTRIG) == ADC_ExternalTrigConv_T3_CC1) || \
((REGTRIG) == ADC_ExternalTrigConv_T2_CC3) || \
((REGTRIG) == ADC_ExternalTrigConv_T8_CC1) || \
((REGTRIG) == ADC_ExternalTrigConv_T8_TRGO) || \
((REGTRIG) == ADC_ExternalTrigConv_T5_CC1) || \
((REGTRIG) == ADC_ExternalTrigConv_T5_CC3))
/**
* @}
*/
/** @defgroup ADC_data_align
* @{
*/
#define ADC_DataAlign_Right ((uint32_t)0x00000000)
#define ADC_DataAlign_Left ((uint32_t)0x00000800)
#define IS_ADC_DATA_ALIGN(ALIGN) (((ALIGN) == ADC_DataAlign_Right) || \
((ALIGN) == ADC_DataAlign_Left))
/**
* @}
*/
/** @defgroup ADC_channels
* @{
*/
#define ADC_Channel_0 ((uint8_t)0x00)
#define ADC_Channel_1 ((uint8_t)0x01)
#define ADC_Channel_2 ((uint8_t)0x02)
#define ADC_Channel_3 ((uint8_t)0x03)
#define ADC_Channel_4 ((uint8_t)0x04)
#define ADC_Channel_5 ((uint8_t)0x05)
#define ADC_Channel_6 ((uint8_t)0x06)
#define ADC_Channel_7 ((uint8_t)0x07)
#define ADC_Channel_8 ((uint8_t)0x08)
#define ADC_Channel_9 ((uint8_t)0x09)
#define ADC_Channel_10 ((uint8_t)0x0A)
#define ADC_Channel_11 ((uint8_t)0x0B)
#define ADC_Channel_12 ((uint8_t)0x0C)
#define ADC_Channel_13 ((uint8_t)0x0D)
#define ADC_Channel_14 ((uint8_t)0x0E)
#define ADC_Channel_15 ((uint8_t)0x0F)
#define ADC_Channel_16 ((uint8_t)0x10)
#define ADC_Channel_17 ((uint8_t)0x11)
#define ADC_Channel_TempSensor ((uint8_t)ADC_Channel_16)
#define ADC_Channel_Vrefint ((uint8_t)ADC_Channel_17)
#define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) == ADC_Channel_0) || ((CHANNEL) == ADC_Channel_1) || \
((CHANNEL) == ADC_Channel_2) || ((CHANNEL) == ADC_Channel_3) || \
((CHANNEL) == ADC_Channel_4) || ((CHANNEL) == ADC_Channel_5) || \
((CHANNEL) == ADC_Channel_6) || ((CHANNEL) == ADC_Channel_7) || \
((CHANNEL) == ADC_Channel_8) || ((CHANNEL) == ADC_Channel_9) || \
((CHANNEL) == ADC_Channel_10) || ((CHANNEL) == ADC_Channel_11) || \
((CHANNEL) == ADC_Channel_12) || ((CHANNEL) == ADC_Channel_13) || \
((CHANNEL) == ADC_Channel_14) || ((CHANNEL) == ADC_Channel_15) || \
((CHANNEL) == ADC_Channel_16) || ((CHANNEL) == ADC_Channel_17))
/**
* @}
*/
/** @defgroup ADC_sampling_time
* @{
*/
#define ADC_SampleTime_1Cycles5 ((uint8_t)0x00)
#define ADC_SampleTime_7Cycles5 ((uint8_t)0x01)
#define ADC_SampleTime_13Cycles5 ((uint8_t)0x02)
#define ADC_SampleTime_28Cycles5 ((uint8_t)0x03)
#define ADC_SampleTime_41Cycles5 ((uint8_t)0x04)
#define ADC_SampleTime_55Cycles5 ((uint8_t)0x05)
#define ADC_SampleTime_71Cycles5 ((uint8_t)0x06)
#define ADC_SampleTime_239Cycles5 ((uint8_t)0x07)
#define IS_ADC_SAMPLE_TIME(TIME) (((TIME) == ADC_SampleTime_1Cycles5) || \
((TIME) == ADC_SampleTime_7Cycles5) || \
((TIME) == ADC_SampleTime_13Cycles5) || \
((TIME) == ADC_SampleTime_28Cycles5) || \
((TIME) == ADC_SampleTime_41Cycles5) || \
((TIME) == ADC_SampleTime_55Cycles5) || \
((TIME) == ADC_SampleTime_71Cycles5) || \
((TIME) == ADC_SampleTime_239Cycles5))
/**
* @}
*/
/** @defgroup ADC_external_trigger_sources_for_injected_channels_conversion
* @{
*/
#define ADC_ExternalTrigInjecConv_T2_TRGO ((uint32_t)0x00002000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigInjecConv_T2_CC1 ((uint32_t)0x00003000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigInjecConv_T3_CC4 ((uint32_t)0x00004000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigInjecConv_T4_TRGO ((uint32_t)0x00005000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigInjecConv_Ext_IT15_TIM8_CC4 ((uint32_t)0x00006000) /*!< For ADC1 and ADC2 */
#define ADC_ExternalTrigInjecConv_T1_TRGO ((uint32_t)0x00000000) /*!< For ADC1, ADC2 and ADC3 */
#define ADC_ExternalTrigInjecConv_T1_CC4 ((uint32_t)0x00001000) /*!< For ADC1, ADC2 and ADC3 */
#define ADC_ExternalTrigInjecConv_None ((uint32_t)0x00007000) /*!< For ADC1, ADC2 and ADC3 */
#define ADC_ExternalTrigInjecConv_T4_CC3 ((uint32_t)0x00002000) /*!< For ADC3 only */
#define ADC_ExternalTrigInjecConv_T8_CC2 ((uint32_t)0x00003000) /*!< For ADC3 only */
#define ADC_ExternalTrigInjecConv_T8_CC4 ((uint32_t)0x00004000) /*!< For ADC3 only */
#define ADC_ExternalTrigInjecConv_T5_TRGO ((uint32_t)0x00005000) /*!< For ADC3 only */
#define ADC_ExternalTrigInjecConv_T5_CC4 ((uint32_t)0x00006000) /*!< For ADC3 only */
#define IS_ADC_EXT_INJEC_TRIG(INJTRIG) (((INJTRIG) == ADC_ExternalTrigInjecConv_T1_TRGO) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T1_CC4) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T2_TRGO) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T2_CC1) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T3_CC4) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T4_TRGO) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_Ext_IT15_TIM8_CC4) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_None) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T4_CC3) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T8_CC2) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T8_CC4) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T5_TRGO) || \
((INJTRIG) == ADC_ExternalTrigInjecConv_T5_CC4))
/**
* @}
*/
/** @defgroup ADC_injected_channel_selection
* @{
*/
#define ADC_InjectedChannel_1 ((uint8_t)0x14)
#define ADC_InjectedChannel_2 ((uint8_t)0x18)
#define ADC_InjectedChannel_3 ((uint8_t)0x1C)
#define ADC_InjectedChannel_4 ((uint8_t)0x20)
#define IS_ADC_INJECTED_CHANNEL(CHANNEL) (((CHANNEL) == ADC_InjectedChannel_1) || \
((CHANNEL) == ADC_InjectedChannel_2) || \
((CHANNEL) == ADC_InjectedChannel_3) || \
((CHANNEL) == ADC_InjectedChannel_4))
/**
* @}
*/
/** @defgroup ADC_analog_watchdog_selection
* @{
*/
#define ADC_AnalogWatchdog_SingleRegEnable ((uint32_t)0x00800200)
#define ADC_AnalogWatchdog_SingleInjecEnable ((uint32_t)0x00400200)
#define ADC_AnalogWatchdog_SingleRegOrInjecEnable ((uint32_t)0x00C00200)
#define ADC_AnalogWatchdog_AllRegEnable ((uint32_t)0x00800000)
#define ADC_AnalogWatchdog_AllInjecEnable ((uint32_t)0x00400000)
#define ADC_AnalogWatchdog_AllRegAllInjecEnable ((uint32_t)0x00C00000)
#define ADC_AnalogWatchdog_None ((uint32_t)0x00000000)
#define IS_ADC_ANALOG_WATCHDOG(WATCHDOG) (((WATCHDOG) == ADC_AnalogWatchdog_SingleRegEnable) || \
((WATCHDOG) == ADC_AnalogWatchdog_SingleInjecEnable) || \
((WATCHDOG) == ADC_AnalogWatchdog_SingleRegOrInjecEnable) || \
((WATCHDOG) == ADC_AnalogWatchdog_AllRegEnable) || \
((WATCHDOG) == ADC_AnalogWatchdog_AllInjecEnable) || \
((WATCHDOG) == ADC_AnalogWatchdog_AllRegAllInjecEnable) || \
((WATCHDOG) == ADC_AnalogWatchdog_None))
/**
* @}
*/
/** @defgroup ADC_interrupts_definition
* @{
*/
#define ADC_IT_EOC ((uint16_t)0x0220)
#define ADC_IT_AWD ((uint16_t)0x0140)
#define ADC_IT_JEOC ((uint16_t)0x0480)
#define IS_ADC_IT(IT) ((((IT) & (uint16_t)0xF81F) == 0x00) && ((IT) != 0x00))
#define IS_ADC_GET_IT(IT) (((IT) == ADC_IT_EOC) || ((IT) == ADC_IT_AWD) || \
((IT) == ADC_IT_JEOC))
/**
* @}
*/
/** @defgroup ADC_flags_definition
* @{
*/
#define ADC_FLAG_AWD ((uint8_t)0x01)
#define ADC_FLAG_EOC ((uint8_t)0x02)
#define ADC_FLAG_JEOC ((uint8_t)0x04)
#define ADC_FLAG_JSTRT ((uint8_t)0x08)
#define ADC_FLAG_STRT ((uint8_t)0x10)
#define IS_ADC_CLEAR_FLAG(FLAG) ((((FLAG) & (uint8_t)0xE0) == 0x00) && ((FLAG) != 0x00))
#define IS_ADC_GET_FLAG(FLAG) (((FLAG) == ADC_FLAG_AWD) || ((FLAG) == ADC_FLAG_EOC) || \
((FLAG) == ADC_FLAG_JEOC) || ((FLAG)== ADC_FLAG_JSTRT) || \
((FLAG) == ADC_FLAG_STRT))
/**
* @}
*/
/** @defgroup ADC_thresholds
* @{
*/
#define IS_ADC_THRESHOLD(THRESHOLD) ((THRESHOLD) <= 0xFFF)
/**
* @}
*/
/** @defgroup ADC_injected_offset
* @{
*/
#define IS_ADC_OFFSET(OFFSET) ((OFFSET) <= 0xFFF)
/**
* @}
*/
/** @defgroup ADC_injected_length
* @{
*/
#define IS_ADC_INJECTED_LENGTH(LENGTH) (((LENGTH) >= 0x1) && ((LENGTH) <= 0x4))
/**
* @}
*/
/** @defgroup ADC_injected_rank
* @{
*/
#define IS_ADC_INJECTED_RANK(RANK) (((RANK) >= 0x1) && ((RANK) <= 0x4))
/**
* @}
*/
/** @defgroup ADC_regular_length
* @{
*/
#define IS_ADC_REGULAR_LENGTH(LENGTH) (((LENGTH) >= 0x1) && ((LENGTH) <= 0x10))
/**
* @}
*/
/** @defgroup ADC_regular_rank
* @{
*/
#define IS_ADC_REGULAR_RANK(RANK) (((RANK) >= 0x1) && ((RANK) <= 0x10))
/**
* @}
*/
/** @defgroup ADC_regular_discontinuous_mode_number
* @{
*/
#define IS_ADC_REGULAR_DISC_NUMBER(NUMBER) (((NUMBER) >= 0x1) && ((NUMBER) <= 0x8))
/**
* @}
*/
/**
* @}
*/
/** @defgroup ADC_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup ADC_Exported_Functions
* @{
*/
void ADC_DeInit(ADC_TypeDef* ADCx);
void ADC_Init(ADC_TypeDef* ADCx, ADC_InitTypeDef* ADC_InitStruct);
void ADC_StructInit(ADC_InitTypeDef* ADC_InitStruct);
void ADC_Cmd(ADC_TypeDef* ADCx, FunctionalState NewState);
void ADC_DMACmd(ADC_TypeDef* ADCx, FunctionalState NewState);
void ADC_ITConfig(ADC_TypeDef* ADCx, uint16_t ADC_IT, FunctionalState NewState);
void ADC_ResetCalibration(ADC_TypeDef* ADCx);
FlagStatus ADC_GetResetCalibrationStatus(ADC_TypeDef* ADCx);
void ADC_StartCalibration(ADC_TypeDef* ADCx);
FlagStatus ADC_GetCalibrationStatus(ADC_TypeDef* ADCx);
void ADC_SoftwareStartConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
FlagStatus ADC_GetSoftwareStartConvStatus(ADC_TypeDef* ADCx);
void ADC_DiscModeChannelCountConfig(ADC_TypeDef* ADCx, uint8_t Number);
void ADC_DiscModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
void ADC_RegularChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel, uint8_t Rank, uint8_t ADC_SampleTime);
void ADC_ExternalTrigConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
uint16_t ADC_GetConversionValue(ADC_TypeDef* ADCx);
uint32_t ADC_GetDualModeConversionValue(void);
void ADC_AutoInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
void ADC_InjectedDiscModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
void ADC_ExternalTrigInjectedConvConfig(ADC_TypeDef* ADCx, uint32_t ADC_ExternalTrigInjecConv);
void ADC_ExternalTrigInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
void ADC_SoftwareStartInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
FlagStatus ADC_GetSoftwareStartInjectedConvCmdStatus(ADC_TypeDef* ADCx);
void ADC_InjectedChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel, uint8_t Rank, uint8_t ADC_SampleTime);
void ADC_InjectedSequencerLengthConfig(ADC_TypeDef* ADCx, uint8_t Length);
void ADC_SetInjectedOffset(ADC_TypeDef* ADCx, uint8_t ADC_InjectedChannel, uint16_t Offset);
uint16_t ADC_GetInjectedConversionValue(ADC_TypeDef* ADCx, uint8_t ADC_InjectedChannel);
void ADC_AnalogWatchdogCmd(ADC_TypeDef* ADCx, uint32_t ADC_AnalogWatchdog);
void ADC_AnalogWatchdogThresholdsConfig(ADC_TypeDef* ADCx, uint16_t HighThreshold, uint16_t LowThreshold);
void ADC_AnalogWatchdogSingleChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel);
void ADC_TempSensorVrefintCmd(FunctionalState NewState);
FlagStatus ADC_GetFlagStatus(ADC_TypeDef* ADCx, uint8_t ADC_FLAG);
void ADC_ClearFlag(ADC_TypeDef* ADCx, uint8_t ADC_FLAG);
ITStatus ADC_GetITStatus(ADC_TypeDef* ADCx, uint16_t ADC_IT);
void ADC_ClearITPendingBit(ADC_TypeDef* ADCx, uint16_t ADC_IT);
#ifdef __cplusplus
}
#endif
#endif /*__STM32F10x_ADC_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2018-2020 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef ARM_COMPUTE_WRAPPER_SET_LANE_H
#define ARM_COMPUTE_WRAPPER_SET_LANE_H
#include <arm_neon.h>
namespace arm_compute
{
namespace wrapper
{
#define VSETLANE_IMPL_8(stype, atype, vtype, postfix) \
inline stype vsetlane(const atype value, const vtype vector, const unsigned int lane) \
{ \
switch(lane) \
{ \
case 0: \
return vset_lane_##postfix(value, vector, 0); \
case 1: \
return vset_lane_##postfix(value, vector, 1); \
case 2: \
return vset_lane_##postfix(value, vector, 2); \
case 3: \
return vset_lane_##postfix(value, vector, 3); \
case 4: \
return vset_lane_##postfix(value, vector, 4); \
case 5: \
return vset_lane_##postfix(value, vector, 5); \
case 6: \
return vset_lane_##postfix(value, vector, 6); \
case 7: \
return vset_lane_##postfix(value, vector, 7); \
default: \
ARM_COMPUTE_ERROR("Invalid lane"); \
} \
}
#define VSETLANE_IMPL_4(stype, atype, vtype, postfix) \
inline stype vsetlane(const atype value, const vtype vector, const unsigned int lane) \
{ \
switch(lane) \
{ \
case 0: \
return vset_lane_##postfix(value, vector, 0); \
case 1: \
return vset_lane_##postfix(value, vector, 1); \
case 2: \
return vset_lane_##postfix(value, vector, 2); \
case 3: \
return vset_lane_##postfix(value, vector, 3); \
default: \
ARM_COMPUTE_ERROR("Invalid lane"); \
} \
}
#define VSETLANE_IMPL_2(stype, atype, vtype, postfix) \
inline stype vsetlane(const atype value, const vtype vector, const unsigned int lane) \
{ \
switch(lane) \
{ \
case 0: \
return vset_lane_##postfix(value, vector, 0); \
case 1: \
return vset_lane_##postfix(value, vector, 1); \
default: \
ARM_COMPUTE_ERROR("Invalid lane"); \
} \
}
VSETLANE_IMPL_8(uint8x8_t, uint8_t, uint8x8_t, u8)
VSETLANE_IMPL_8(int8x8_t, int8_t, int8x8_t, s8)
VSETLANE_IMPL_4(uint16x4_t, uint16_t, uint16x4_t, u16)
VSETLANE_IMPL_4(int16x4_t, int16_t, int16x4_t, s16)
VSETLANE_IMPL_2(uint32x2_t, uint32_t, uint32x2_t, u32)
VSETLANE_IMPL_2(int32x2_t, int32_t, int32x2_t, s32)
VSETLANE_IMPL_2(float32x2_t, float, float32x2_t, f32)
#ifdef __ARM_FEATURE_FP16_VECTOR_ARITHMETIC
VSETLANE_IMPL_4(float16x4_t, float16_t, float16x4_t, f16)
#endif // __ARM_FEATURE_FP16_VECTOR_ARITHMETIC
#define VSETQLANE_IMPL_16(stype, atype, vtype, postfix) \
inline stype vsetlane(const atype value, const vtype vector, const unsigned int lane) \
{ \
switch(lane) \
{ \
case 0: \
return vsetq_lane_##postfix(value, vector, 0); \
case 1: \
return vsetq_lane_##postfix(value, vector, 1); \
case 2: \
return vsetq_lane_##postfix(value, vector, 2); \
case 3: \
return vsetq_lane_##postfix(value, vector, 3); \
case 4: \
return vsetq_lane_##postfix(value, vector, 4); \
case 5: \
return vsetq_lane_##postfix(value, vector, 5); \
case 6: \
return vsetq_lane_##postfix(value, vector, 6); \
case 7: \
return vsetq_lane_##postfix(value, vector, 7); \
case 8: \
return vsetq_lane_##postfix(value, vector, 8); \
case 9: \
return vsetq_lane_##postfix(value, vector, 9); \
case 10: \
return vsetq_lane_##postfix(value, vector, 10); \
case 11: \
return vsetq_lane_##postfix(value, vector, 11); \
case 12: \
return vsetq_lane_##postfix(value, vector, 12); \
case 13: \
return vsetq_lane_##postfix(value, vector, 13); \
case 14: \
return vsetq_lane_##postfix(value, vector, 14); \
case 15: \
return vsetq_lane_##postfix(value, vector, 15); \
default: \
ARM_COMPUTE_ERROR("Invalid lane"); \
} \
}
#define VSETQLANE_IMPL_8(stype, atype, vtype, postfix) \
inline stype vsetlane(const atype value, const vtype vector, const unsigned int lane) \
{ \
switch(lane) \
{ \
case 0: \
return vsetq_lane_##postfix(value, vector, 0); \
case 1: \
return vsetq_lane_##postfix(value, vector, 1); \
case 2: \
return vsetq_lane_##postfix(value, vector, 2); \
case 3: \
return vsetq_lane_##postfix(value, vector, 3); \
case 4: \
return vsetq_lane_##postfix(value, vector, 4); \
case 5: \
return vsetq_lane_##postfix(value, vector, 5); \
case 6: \
return vsetq_lane_##postfix(value, vector, 6); \
case 7: \
return vsetq_lane_##postfix(value, vector, 7); \
default: \
ARM_COMPUTE_ERROR("Invalid lane"); \
} \
}
#define VSETQLANE_IMPL_4(stype, atype, vtype, postfix) \
inline stype vsetlane(const atype value, const vtype vector, const unsigned int lane) \
{ \
switch(lane) \
{ \
case 0: \
return vsetq_lane_##postfix(value, vector, 0); \
case 1: \
return vsetq_lane_##postfix(value, vector, 1); \
case 2: \
return vsetq_lane_##postfix(value, vector, 2); \
case 3: \
return vsetq_lane_##postfix(value, vector, 3); \
default: \
ARM_COMPUTE_ERROR("Invalid lane"); \
} \
}
VSETQLANE_IMPL_16(uint8x16_t, uint8_t, uint8x16_t, u8)
VSETQLANE_IMPL_16(int8x16_t, int8_t, int8x16_t, s8)
VSETQLANE_IMPL_8(uint16x8_t, uint16_t, uint16x8_t, u16)
VSETQLANE_IMPL_8(int16x8_t, int16_t, int16x8_t, s16)
VSETQLANE_IMPL_4(uint32x4_t, uint32_t, uint32x4_t, u32)
VSETQLANE_IMPL_4(int32x4_t, int32_t, int32x4_t, s32)
VSETQLANE_IMPL_4(float32x4_t, float, float32x4_t, f32)
#ifdef __ARM_FEATURE_FP16_VECTOR_ARITHMETIC
VSETQLANE_IMPL_8(float16x8_t, float16_t, float16x8_t, f16)
#endif // __ARM_FEATURE_FP16_VECTOR_ARITHMETIC
#undef VSETLANE_IMPL_8
#undef VSETLANE_IMPL_4
#undef VSETLANE_IMPL_2
#undef VSETQLANE_IMPL_16
#undef VSETQLANE_IMPL_8
#undef VSETQLANE_IMPL_4
} // namespace wrapper
} // namespace arm_compute
#endif /* ARM_COMPUTE_WRAPPER_SET_LANE_H */
|
{
"pile_set_name": "Github"
}
|
/*
FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
All rights reserved
VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
This file is part of the FreeRTOS distribution.
FreeRTOS is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License (version 2) as published by the
Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
***************************************************************************
>>! NOTE: The modification to the GPL is included to allow you to !<<
>>! distribute a combined work that includes FreeRTOS without being !<<
>>! obliged to provide the source code for proprietary components !<<
>>! outside of the FreeRTOS kernel. !<<
***************************************************************************
FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. Full license text is available on the following
link: http://www.freertos.org/a00114.html
***************************************************************************
* *
* FreeRTOS provides completely free yet professionally developed, *
* robust, strictly quality controlled, supported, and cross *
* platform software that is more than just the market leader, it *
* is the industry's de facto standard. *
* *
* Help yourself get started quickly while simultaneously helping *
* to support the FreeRTOS project by purchasing a FreeRTOS *
* tutorial book, reference manual, or both: *
* http://www.FreeRTOS.org/Documentation *
* *
***************************************************************************
http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading
the FAQ page "My application does not run, what could be wrong?". Have you
defined configASSERT()?
http://www.FreeRTOS.org/support - In return for receiving this top quality
embedded software for free we request you assist our global community by
participating in the support forum.
http://www.FreeRTOS.org/training - Investing in training allows your team to
be as productive as possible as early as possible. Now you can receive
FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
Ltd, and the world's leading authority on the world's leading RTOS.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool, a DOS
compatible FAT file system, and our tiny thread aware UDP/IP stack.
http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS
licenses offer ticketed support, indemnification and commercial middleware.
http://www.SafeRTOS.com - High Integrity Systems also provide a safety
engineered and independently SIL3 certified version for use in safety and
mission critical applications that require provable dependability.
1 tab == 4 spaces!
*/
#ifndef INC_TASK_H
#define INC_TASK_H
#ifndef INC_FREERTOS_H
#error "include FreeRTOS.h must appear in source files before include task.h"
#endif
#include "list.h"
#ifdef __cplusplus
extern "C" {
#endif
/*-----------------------------------------------------------
* MACROS AND DEFINITIONS
*----------------------------------------------------------*/
#define tskKERNEL_VERSION_NUMBER "V8.2.1"
#define tskKERNEL_VERSION_MAJOR 8
#define tskKERNEL_VERSION_MINOR 2
#define tskKERNEL_VERSION_BUILD 1
/**
* task. h
*
* Type by which tasks are referenced. For example, a call to xTaskCreate
* returns (via a pointer parameter) an TaskHandle_t variable that can then
* be used as a parameter to vTaskDelete to delete the task.
*
* \defgroup TaskHandle_t TaskHandle_t
* \ingroup Tasks
*/
typedef void * TaskHandle_t;
/*
* Defines the prototype to which the application task hook function must
* conform.
*/
typedef BaseType_t (*TaskHookFunction_t)( void * );
/* Task states returned by eTaskGetState. */
typedef enum
{
eRunning = 0, /* A task is querying the state of itself, so must be running. */
eReady, /* The task being queried is in a read or pending ready list. */
eBlocked, /* The task being queried is in the Blocked state. */
eSuspended, /* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */
eDeleted /* The task being queried has been deleted, but its TCB has not yet been freed. */
} eTaskState;
/* Actions that can be performed when vTaskNotify() is called. */
typedef enum
{
eNoAction = 0, /* Notify the task without updating its notify value. */
eSetBits, /* Set bits in the task's notification value. */
eIncrement, /* Increment the task's notification value. */
eSetValueWithOverwrite, /* Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */
eSetValueWithoutOverwrite /* Set the task's notification value if the previous value has been read by the task. */
} eNotifyAction;
/*
* Used internally only.
*/
typedef struct xTIME_OUT
{
BaseType_t xOverflowCount;
TickType_t xTimeOnEntering;
} TimeOut_t;
/*
* Defines the memory ranges allocated to the task when an MPU is used.
*/
typedef struct xMEMORY_REGION
{
void *pvBaseAddress;
uint32_t ulLengthInBytes;
uint32_t ulParameters;
} MemoryRegion_t;
/*
* Parameters required to create an MPU protected task.
*/
typedef struct xTASK_PARAMETERS
{
TaskFunction_t pvTaskCode;
const char * const pcName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
uint16_t usStackDepth;
void *pvParameters;
UBaseType_t uxPriority;
StackType_t *puxStackBuffer;
MemoryRegion_t xRegions[ portNUM_CONFIGURABLE_REGIONS ];
} TaskParameters_t;
/* Used with the uxTaskGetSystemState() function to return the state of each task
in the system. */
typedef struct xTASK_STATUS
{
TaskHandle_t xHandle; /* The handle of the task to which the rest of the information in the structure relates. */
const char *pcTaskName; /* A pointer to the task's name. This value will be invalid if the task was deleted since the structure was populated! */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
UBaseType_t xTaskNumber; /* A number unique to the task. */
eTaskState eCurrentState; /* The state in which the task existed when the structure was populated. */
UBaseType_t uxCurrentPriority; /* The priority at which the task was running (may be inherited) when the structure was populated. */
UBaseType_t uxBasePriority; /* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex. Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */
uint32_t ulRunTimeCounter; /* The total run time allocated to the task so far, as defined by the run time stats clock. See http://www.freertos.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */
uint16_t usStackHighWaterMark; /* The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. */
} TaskStatus_t;
/* Possible return values for eTaskConfirmSleepModeStatus(). */
typedef enum
{
eAbortSleep = 0, /* A task has been made ready or a context switch pended since portSUPPORESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */
eStandardSleep, /* Enter a sleep mode that will not last any longer than the expected idle time. */
eNoTasksWaitingTimeout /* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */
} eSleepModeStatus;
/**
* Defines the priority used by the idle task. This must not be modified.
*
* \ingroup TaskUtils
*/
#define tskIDLE_PRIORITY ( ( UBaseType_t ) 0U )
/**
* task. h
*
* Macro for forcing a context switch.
*
* \defgroup taskYIELD taskYIELD
* \ingroup SchedulerControl
*/
#define taskYIELD() portYIELD()
/**
* task. h
*
* Macro to mark the start of a critical code region. Preemptive context
* switches cannot occur when in a critical region.
*
* NOTE: This may alter the stack (depending on the portable implementation)
* so must be used with care!
*
* \defgroup taskENTER_CRITICAL taskENTER_CRITICAL
* \ingroup SchedulerControl
*/
#define taskENTER_CRITICAL() portENTER_CRITICAL()
#define taskENTER_CRITICAL_FROM_ISR( x ) portSET_INTERRUPT_MASK_FROM_ISR( x )
/**
* task. h
*
* Macro to mark the end of a critical code region. Preemptive context
* switches cannot occur when in a critical region.
*
* NOTE: This may alter the stack (depending on the portable implementation)
* so must be used with care!
*
* \defgroup taskEXIT_CRITICAL taskEXIT_CRITICAL
* \ingroup SchedulerControl
*/
#define taskEXIT_CRITICAL() portEXIT_CRITICAL()
#define taskEXIT_CRITICAL_FROM_ISR() portCLEAR_INTERRUPT_MASK_FROM_ISR()
/**
* task. h
*
* Macro to disable all maskable interrupts.
*
* \defgroup taskDISABLE_INTERRUPTS taskDISABLE_INTERRUPTS
* \ingroup SchedulerControl
*/
#define taskDISABLE_INTERRUPTS() portDISABLE_INTERRUPTS()
/**
* task. h
*
* Macro to enable microcontroller interrupts.
*
* \defgroup taskENABLE_INTERRUPTS taskENABLE_INTERRUPTS
* \ingroup SchedulerControl
*/
#define taskENABLE_INTERRUPTS() portENABLE_INTERRUPTS()
/* Definitions returned by xTaskGetSchedulerState(). taskSCHEDULER_SUSPENDED is
0 to generate more optimal code when configASSERT() is defined as the constant
is used in assert() statements. */
#define taskSCHEDULER_SUSPENDED ( ( BaseType_t ) 0 )
#define taskSCHEDULER_NOT_STARTED ( ( BaseType_t ) 1 )
#define taskSCHEDULER_RUNNING ( ( BaseType_t ) 2 )
/*-----------------------------------------------------------
* TASK CREATION API
*----------------------------------------------------------*/
/**
* task. h
*<pre>
BaseType_t xTaskCreate(
TaskFunction_t pvTaskCode,
const char * const pcName,
uint16_t usStackDepth,
void *pvParameters,
UBaseType_t uxPriority,
TaskHandle_t *pvCreatedTask
);</pre>
*
* Create a new task and add it to the list of tasks that are ready to run.
*
* xTaskCreate() can only be used to create a task that has unrestricted
* access to the entire microcontroller memory map. Systems that include MPU
* support can alternatively create an MPU constrained task using
* xTaskCreateRestricted().
*
* @param pvTaskCode Pointer to the task entry function. Tasks
* must be implemented to never return (i.e. continuous loop).
*
* @param pcName A descriptive name for the task. This is mainly used to
* facilitate debugging. Max length defined by configMAX_TASK_NAME_LEN - default
* is 16.
*
* @param usStackDepth The size of the task stack specified as the number of
* variables the stack can hold - not the number of bytes. For example, if
* the stack is 16 bits wide and usStackDepth is defined as 100, 200 bytes
* will be allocated for stack storage.
*
* @param pvParameters Pointer that will be used as the parameter for the task
* being created.
*
* @param uxPriority The priority at which the task should run. Systems that
* include MPU support can optionally create tasks in a privileged (system)
* mode by setting bit portPRIVILEGE_BIT of the priority parameter. For
* example, to create a privileged task at priority 2 the uxPriority parameter
* should be set to ( 2 | portPRIVILEGE_BIT ).
*
* @param pvCreatedTask Used to pass back a handle by which the created task
* can be referenced.
*
* @return pdPASS if the task was successfully created and added to a ready
* list, otherwise an error code defined in the file projdefs.h
*
* Example usage:
<pre>
// Task to be created.
void vTaskCode( void * pvParameters )
{
for( ;; )
{
// Task code goes here.
}
}
// Function that creates a task.
void vOtherFunction( void )
{
static uint8_t ucParameterToPass;
TaskHandle_t xHandle = NULL;
// Create the task, storing the handle. Note that the passed parameter ucParameterToPass
// must exist for the lifetime of the task, so in this case is declared static. If it was just an
// an automatic stack variable it might no longer exist, or at least have been corrupted, by the time
// the new task attempts to access it.
xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle );
configASSERT( xHandle );
// Use the handle to delete the task.
if( xHandle != NULL )
{
vTaskDelete( xHandle );
}
}
</pre>
* \defgroup xTaskCreate xTaskCreate
* \ingroup Tasks
*/
#define xTaskCreate( pvTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask ) xTaskGenericCreate( ( pvTaskCode ), ( pcName ), ( usStackDepth ), ( pvParameters ), ( uxPriority ), ( pxCreatedTask ), ( NULL ), ( NULL ) )
/**
* task. h
*<pre>
BaseType_t xTaskCreateRestricted( TaskParameters_t *pxTaskDefinition, TaskHandle_t *pxCreatedTask );</pre>
*
* xTaskCreateRestricted() should only be used in systems that include an MPU
* implementation.
*
* Create a new task and add it to the list of tasks that are ready to run.
* The function parameters define the memory regions and associated access
* permissions allocated to the task.
*
* @param pxTaskDefinition Pointer to a structure that contains a member
* for each of the normal xTaskCreate() parameters (see the xTaskCreate() API
* documentation) plus an optional stack buffer and the memory region
* definitions.
*
* @param pxCreatedTask Used to pass back a handle by which the created task
* can be referenced.
*
* @return pdPASS if the task was successfully created and added to a ready
* list, otherwise an error code defined in the file projdefs.h
*
* Example usage:
<pre>
// Create an TaskParameters_t structure that defines the task to be created.
static const TaskParameters_t xCheckTaskParameters =
{
vATask, // pvTaskCode - the function that implements the task.
"ATask", // pcName - just a text name for the task to assist debugging.
100, // usStackDepth - the stack size DEFINED IN WORDS.
NULL, // pvParameters - passed into the task function as the function parameters.
( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state.
cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack.
// xRegions - Allocate up to three separate memory regions for access by
// the task, with appropriate access permissions. Different processors have
// different memory alignment requirements - refer to the FreeRTOS documentation
// for full information.
{
// Base address Length Parameters
{ cReadWriteArray, 32, portMPU_REGION_READ_WRITE },
{ cReadOnlyArray, 32, portMPU_REGION_READ_ONLY },
{ cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE }
}
};
int main( void )
{
TaskHandle_t xHandle;
// Create a task from the const structure defined above. The task handle
// is requested (the second parameter is not NULL) but in this case just for
// demonstration purposes as its not actually used.
xTaskCreateRestricted( &xRegTest1Parameters, &xHandle );
// Start the scheduler.
vTaskStartScheduler();
// Will only get here if there was insufficient memory to create the idle
// and/or timer task.
for( ;; );
}
</pre>
* \defgroup xTaskCreateRestricted xTaskCreateRestricted
* \ingroup Tasks
*/
#define xTaskCreateRestricted( x, pxCreatedTask ) xTaskGenericCreate( ((x)->pvTaskCode), ((x)->pcName), ((x)->usStackDepth), ((x)->pvParameters), ((x)->uxPriority), (pxCreatedTask), ((x)->puxStackBuffer), ((x)->xRegions) )
/**
* task. h
*<pre>
void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions );</pre>
*
* Memory regions are assigned to a restricted task when the task is created by
* a call to xTaskCreateRestricted(). These regions can be redefined using
* vTaskAllocateMPURegions().
*
* @param xTask The handle of the task being updated.
*
* @param xRegions A pointer to an MemoryRegion_t structure that contains the
* new memory region definitions.
*
* Example usage:
<pre>
// Define an array of MemoryRegion_t structures that configures an MPU region
// allowing read/write access for 1024 bytes starting at the beginning of the
// ucOneKByte array. The other two of the maximum 3 definable regions are
// unused so set to zero.
static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] =
{
// Base address Length Parameters
{ ucOneKByte, 1024, portMPU_REGION_READ_WRITE },
{ 0, 0, 0 },
{ 0, 0, 0 }
};
void vATask( void *pvParameters )
{
// This task was created such that it has access to certain regions of
// memory as defined by the MPU configuration. At some point it is
// desired that these MPU regions are replaced with that defined in the
// xAltRegions const struct above. Use a call to vTaskAllocateMPURegions()
// for this purpose. NULL is used as the task handle to indicate that this
// function should modify the MPU regions of the calling task.
vTaskAllocateMPURegions( NULL, xAltRegions );
// Now the task can continue its function, but from this point on can only
// access its stack and the ucOneKByte array (unless any other statically
// defined or shared regions have been declared elsewhere).
}
</pre>
* \defgroup xTaskCreateRestricted xTaskCreateRestricted
* \ingroup Tasks
*/
void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions ) PRIVILEGED_FUNCTION;
/**
* task. h
* <pre>void vTaskDelete( TaskHandle_t xTask );</pre>
*
* INCLUDE_vTaskDelete must be defined as 1 for this function to be available.
* See the configuration section for more information.
*
* Remove a task from the RTOS real time kernel's management. The task being
* deleted will be removed from all ready, blocked, suspended and event lists.
*
* NOTE: The idle task is responsible for freeing the kernel allocated
* memory from tasks that have been deleted. It is therefore important that
* the idle task is not starved of microcontroller processing time if your
* application makes any calls to vTaskDelete (). Memory allocated by the
* task code is not automatically freed, and should be freed before the task
* is deleted.
*
* See the demo application file death.c for sample code that utilises
* vTaskDelete ().
*
* @param xTask The handle of the task to be deleted. Passing NULL will
* cause the calling task to be deleted.
*
* Example usage:
<pre>
void vOtherFunction( void )
{
TaskHandle_t xHandle;
// Create the task, storing the handle.
xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
// Use the handle to delete the task.
vTaskDelete( xHandle );
}
</pre>
* \defgroup vTaskDelete vTaskDelete
* \ingroup Tasks
*/
void vTaskDelete( TaskHandle_t xTaskToDelete ) PRIVILEGED_FUNCTION;
/*-----------------------------------------------------------
* TASK CONTROL API
*----------------------------------------------------------*/
/**
* task. h
* <pre>void vTaskDelay( const TickType_t xTicksToDelay );</pre>
*
* Delay a task for a given number of ticks. The actual time that the
* task remains blocked depends on the tick rate. The constant
* portTICK_PERIOD_MS can be used to calculate real time from the tick
* rate - with the resolution of one tick period.
*
* INCLUDE_vTaskDelay must be defined as 1 for this function to be available.
* See the configuration section for more information.
*
*
* vTaskDelay() specifies a time at which the task wishes to unblock relative to
* the time at which vTaskDelay() is called. For example, specifying a block
* period of 100 ticks will cause the task to unblock 100 ticks after
* vTaskDelay() is called. vTaskDelay() does not therefore provide a good method
* of controlling the frequency of a periodic task as the path taken through the
* code, as well as other task and interrupt activity, will effect the frequency
* at which vTaskDelay() gets called and therefore the time at which the task
* next executes. See vTaskDelayUntil() for an alternative API function designed
* to facilitate fixed frequency execution. It does this by specifying an
* absolute time (rather than a relative time) at which the calling task should
* unblock.
*
* @param xTicksToDelay The amount of time, in tick periods, that
* the calling task should block.
*
* Example usage:
void vTaskFunction( void * pvParameters )
{
// Block for 500ms.
const TickType_t xDelay = 500 / portTICK_PERIOD_MS;
for( ;; )
{
// Simply toggle the LED every 500ms, blocking between each toggle.
vToggleLED();
vTaskDelay( xDelay );
}
}
* \defgroup vTaskDelay vTaskDelay
* \ingroup TaskCtrl
*/
void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION;
/**
* task. h
* <pre>void vTaskDelayUntil( TickType_t *pxPreviousWakeTime, const TickType_t xTimeIncrement );</pre>
*
* INCLUDE_vTaskDelayUntil must be defined as 1 for this function to be available.
* See the configuration section for more information.
*
* Delay a task until a specified time. This function can be used by periodic
* tasks to ensure a constant execution frequency.
*
* This function differs from vTaskDelay () in one important aspect: vTaskDelay () will
* cause a task to block for the specified number of ticks from the time vTaskDelay () is
* called. It is therefore difficult to use vTaskDelay () by itself to generate a fixed
* execution frequency as the time between a task starting to execute and that task
* calling vTaskDelay () may not be fixed [the task may take a different path though the
* code between calls, or may get interrupted or preempted a different number of times
* each time it executes].
*
* Whereas vTaskDelay () specifies a wake time relative to the time at which the function
* is called, vTaskDelayUntil () specifies the absolute (exact) time at which it wishes to
* unblock.
*
* The constant portTICK_PERIOD_MS can be used to calculate real time from the tick
* rate - with the resolution of one tick period.
*
* @param pxPreviousWakeTime Pointer to a variable that holds the time at which the
* task was last unblocked. The variable must be initialised with the current time
* prior to its first use (see the example below). Following this the variable is
* automatically updated within vTaskDelayUntil ().
*
* @param xTimeIncrement The cycle time period. The task will be unblocked at
* time *pxPreviousWakeTime + xTimeIncrement. Calling vTaskDelayUntil with the
* same xTimeIncrement parameter value will cause the task to execute with
* a fixed interface period.
*
* Example usage:
<pre>
// Perform an action every 10 ticks.
void vTaskFunction( void * pvParameters )
{
TickType_t xLastWakeTime;
const TickType_t xFrequency = 10;
// Initialise the xLastWakeTime variable with the current time.
xLastWakeTime = xTaskGetTickCount ();
for( ;; )
{
// Wait for the next cycle.
vTaskDelayUntil( &xLastWakeTime, xFrequency );
// Perform action here.
}
}
</pre>
* \defgroup vTaskDelayUntil vTaskDelayUntil
* \ingroup TaskCtrl
*/
void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) PRIVILEGED_FUNCTION;
/**
* task. h
* <pre>UBaseType_t uxTaskPriorityGet( TaskHandle_t xTask );</pre>
*
* INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available.
* See the configuration section for more information.
*
* Obtain the priority of any task.
*
* @param xTask Handle of the task to be queried. Passing a NULL
* handle results in the priority of the calling task being returned.
*
* @return The priority of xTask.
*
* Example usage:
<pre>
void vAFunction( void )
{
TaskHandle_t xHandle;
// Create a task, storing the handle.
xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
// ...
// Use the handle to obtain the priority of the created task.
// It was created with tskIDLE_PRIORITY, but may have changed
// it itself.
if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY )
{
// The task has changed it's priority.
}
// ...
// Is our priority higher than the created task?
if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) )
{
// Our priority (obtained using NULL handle) is higher.
}
}
</pre>
* \defgroup uxTaskPriorityGet uxTaskPriorityGet
* \ingroup TaskCtrl
*/
UBaseType_t uxTaskPriorityGet( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
/**
* task. h
* <pre>UBaseType_t uxTaskPriorityGetFromISR( TaskHandle_t xTask );</pre>
*
* A version of uxTaskPriorityGet() that can be used from an ISR.
*/
UBaseType_t uxTaskPriorityGetFromISR( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
/**
* task. h
* <pre>eTaskState eTaskGetState( TaskHandle_t xTask );</pre>
*
* INCLUDE_eTaskGetState must be defined as 1 for this function to be available.
* See the configuration section for more information.
*
* Obtain the state of any task. States are encoded by the eTaskState
* enumerated type.
*
* @param xTask Handle of the task to be queried.
*
* @return The state of xTask at the time the function was called. Note the
* state of the task might change between the function being called, and the
* functions return value being tested by the calling task.
*/
eTaskState eTaskGetState( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
/**
* task. h
* <pre>void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority );</pre>
*
* INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available.
* See the configuration section for more information.
*
* Set the priority of any task.
*
* A context switch will occur before the function returns if the priority
* being set is higher than the currently executing task.
*
* @param xTask Handle to the task for which the priority is being set.
* Passing a NULL handle results in the priority of the calling task being set.
*
* @param uxNewPriority The priority to which the task will be set.
*
* Example usage:
<pre>
void vAFunction( void )
{
TaskHandle_t xHandle;
// Create a task, storing the handle.
xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
// ...
// Use the handle to raise the priority of the created task.
vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 );
// ...
// Use a NULL handle to raise our priority to the same value.
vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 );
}
</pre>
* \defgroup vTaskPrioritySet vTaskPrioritySet
* \ingroup TaskCtrl
*/
void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) PRIVILEGED_FUNCTION;
/**
* task. h
* <pre>void vTaskSuspend( TaskHandle_t xTaskToSuspend );</pre>
*
* INCLUDE_vTaskSuspend must be defined as 1 for this function to be available.
* See the configuration section for more information.
*
* Suspend any task. When suspended a task will never get any microcontroller
* processing time, no matter what its priority.
*
* Calls to vTaskSuspend are not accumulative -
* i.e. calling vTaskSuspend () twice on the same task still only requires one
* call to vTaskResume () to ready the suspended task.
*
* @param xTaskToSuspend Handle to the task being suspended. Passing a NULL
* handle will cause the calling task to be suspended.
*
* Example usage:
<pre>
void vAFunction( void )
{
TaskHandle_t xHandle;
// Create a task, storing the handle.
xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
// ...
// Use the handle to suspend the created task.
vTaskSuspend( xHandle );
// ...
// The created task will not run during this period, unless
// another task calls vTaskResume( xHandle ).
//...
// Suspend ourselves.
vTaskSuspend( NULL );
// We cannot get here unless another task calls vTaskResume
// with our handle as the parameter.
}
</pre>
* \defgroup vTaskSuspend vTaskSuspend
* \ingroup TaskCtrl
*/
void vTaskSuspend( TaskHandle_t xTaskToSuspend ) PRIVILEGED_FUNCTION;
/**
* task. h
* <pre>void vTaskResume( TaskHandle_t xTaskToResume );</pre>
*
* INCLUDE_vTaskSuspend must be defined as 1 for this function to be available.
* See the configuration section for more information.
*
* Resumes a suspended task.
*
* A task that has been suspended by one or more calls to vTaskSuspend ()
* will be made available for running again by a single call to
* vTaskResume ().
*
* @param xTaskToResume Handle to the task being readied.
*
* Example usage:
<pre>
void vAFunction( void )
{
TaskHandle_t xHandle;
// Create a task, storing the handle.
xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
// ...
// Use the handle to suspend the created task.
vTaskSuspend( xHandle );
// ...
// The created task will not run during this period, unless
// another task calls vTaskResume( xHandle ).
//...
// Resume the suspended task ourselves.
vTaskResume( xHandle );
// The created task will once again get microcontroller processing
// time in accordance with its priority within the system.
}
</pre>
* \defgroup vTaskResume vTaskResume
* \ingroup TaskCtrl
*/
void vTaskResume( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION;
/**
* task. h
* <pre>void xTaskResumeFromISR( TaskHandle_t xTaskToResume );</pre>
*
* INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be
* available. See the configuration section for more information.
*
* An implementation of vTaskResume() that can be called from within an ISR.
*
* A task that has been suspended by one or more calls to vTaskSuspend ()
* will be made available for running again by a single call to
* xTaskResumeFromISR ().
*
* xTaskResumeFromISR() should not be used to synchronise a task with an
* interrupt if there is a chance that the interrupt could arrive prior to the
* task being suspended - as this can lead to interrupts being missed. Use of a
* semaphore as a synchronisation mechanism would avoid this eventuality.
*
* @param xTaskToResume Handle to the task being readied.
*
* @return pdTRUE if resuming the task should result in a context switch,
* otherwise pdFALSE. This is used by the ISR to determine if a context switch
* may be required following the ISR.
*
* \defgroup vTaskResumeFromISR vTaskResumeFromISR
* \ingroup TaskCtrl
*/
BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION;
/*-----------------------------------------------------------
* SCHEDULER CONTROL
*----------------------------------------------------------*/
/**
* task. h
* <pre>void vTaskStartScheduler( void );</pre>
*
* Starts the real time kernel tick processing. After calling the kernel
* has control over which tasks are executed and when.
*
* See the demo application file main.c for an example of creating
* tasks and starting the kernel.
*
* Example usage:
<pre>
void vAFunction( void )
{
// Create at least one task before starting the kernel.
xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
// Start the real time kernel with preemption.
vTaskStartScheduler ();
// Will not get here unless a task calls vTaskEndScheduler ()
}
</pre>
*
* \defgroup vTaskStartScheduler vTaskStartScheduler
* \ingroup SchedulerControl
*/
void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION;
/**
* task. h
* <pre>void vTaskEndScheduler( void );</pre>
*
* NOTE: At the time of writing only the x86 real mode port, which runs on a PC
* in place of DOS, implements this function.
*
* Stops the real time kernel tick. All created tasks will be automatically
* deleted and multitasking (either preemptive or cooperative) will
* stop. Execution then resumes from the point where vTaskStartScheduler ()
* was called, as if vTaskStartScheduler () had just returned.
*
* See the demo application file main. c in the demo/PC directory for an
* example that uses vTaskEndScheduler ().
*
* vTaskEndScheduler () requires an exit function to be defined within the
* portable layer (see vPortEndScheduler () in port. c for the PC port). This
* performs hardware specific operations such as stopping the kernel tick.
*
* vTaskEndScheduler () will cause all of the resources allocated by the
* kernel to be freed - but will not free resources allocated by application
* tasks.
*
* Example usage:
<pre>
void vTaskCode( void * pvParameters )
{
for( ;; )
{
// Task code goes here.
// At some point we want to end the real time kernel processing
// so call ...
vTaskEndScheduler ();
}
}
void vAFunction( void )
{
// Create at least one task before starting the kernel.
xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
// Start the real time kernel with preemption.
vTaskStartScheduler ();
// Will only get here when the vTaskCode () task has called
// vTaskEndScheduler (). When we get here we are back to single task
// execution.
}
</pre>
*
* \defgroup vTaskEndScheduler vTaskEndScheduler
* \ingroup SchedulerControl
*/
void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION;
/**
* task. h
* <pre>void vTaskSuspendAll( void );</pre>
*
* Suspends the scheduler without disabling interrupts. Context switches will
* not occur while the scheduler is suspended.
*
* After calling vTaskSuspendAll () the calling task will continue to execute
* without risk of being swapped out until a call to xTaskResumeAll () has been
* made.
*
* API functions that have the potential to cause a context switch (for example,
* vTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler
* is suspended.
*
* Example usage:
<pre>
void vTask1( void * pvParameters )
{
for( ;; )
{
// Task code goes here.
// ...
// At some point the task wants to perform a long operation during
// which it does not want to get swapped out. It cannot use
// taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
// operation may cause interrupts to be missed - including the
// ticks.
// Prevent the real time kernel swapping out the task.
vTaskSuspendAll ();
// Perform the operation here. There is no need to use critical
// sections as we have all the microcontroller processing time.
// During this time interrupts will still operate and the kernel
// tick count will be maintained.
// ...
// The operation is complete. Restart the kernel.
xTaskResumeAll ();
}
}
</pre>
* \defgroup vTaskSuspendAll vTaskSuspendAll
* \ingroup SchedulerControl
*/
void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION;
/**
* task. h
* <pre>BaseType_t xTaskResumeAll( void );</pre>
*
* Resumes scheduler activity after it was suspended by a call to
* vTaskSuspendAll().
*
* xTaskResumeAll() only resumes the scheduler. It does not unsuspend tasks
* that were previously suspended by a call to vTaskSuspend().
*
* @return If resuming the scheduler caused a context switch then pdTRUE is
* returned, otherwise pdFALSE is returned.
*
* Example usage:
<pre>
void vTask1( void * pvParameters )
{
for( ;; )
{
// Task code goes here.
// ...
// At some point the task wants to perform a long operation during
// which it does not want to get swapped out. It cannot use
// taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
// operation may cause interrupts to be missed - including the
// ticks.
// Prevent the real time kernel swapping out the task.
vTaskSuspendAll ();
// Perform the operation here. There is no need to use critical
// sections as we have all the microcontroller processing time.
// During this time interrupts will still operate and the real
// time kernel tick count will be maintained.
// ...
// The operation is complete. Restart the kernel. We want to force
// a context switch - but there is no point if resuming the scheduler
// caused a context switch already.
if( !xTaskResumeAll () )
{
taskYIELD ();
}
}
}
</pre>
* \defgroup xTaskResumeAll xTaskResumeAll
* \ingroup SchedulerControl
*/
BaseType_t xTaskResumeAll( void ) PRIVILEGED_FUNCTION;
/*-----------------------------------------------------------
* TASK UTILITIES
*----------------------------------------------------------*/
/**
* task. h
* <PRE>TickType_t xTaskGetTickCount( void );</PRE>
*
* @return The count of ticks since vTaskStartScheduler was called.
*
* \defgroup xTaskGetTickCount xTaskGetTickCount
* \ingroup TaskUtils
*/
TickType_t xTaskGetTickCount( void ) PRIVILEGED_FUNCTION;
/**
* task. h
* <PRE>TickType_t xTaskGetTickCountFromISR( void );</PRE>
*
* @return The count of ticks since vTaskStartScheduler was called.
*
* This is a version of xTaskGetTickCount() that is safe to be called from an
* ISR - provided that TickType_t is the natural word size of the
* microcontroller being used or interrupt nesting is either not supported or
* not being used.
*
* \defgroup xTaskGetTickCountFromISR xTaskGetTickCountFromISR
* \ingroup TaskUtils
*/
TickType_t xTaskGetTickCountFromISR( void ) PRIVILEGED_FUNCTION;
/**
* task. h
* <PRE>uint16_t uxTaskGetNumberOfTasks( void );</PRE>
*
* @return The number of tasks that the real time kernel is currently managing.
* This includes all ready, blocked and suspended tasks. A task that
* has been deleted but not yet freed by the idle task will also be
* included in the count.
*
* \defgroup uxTaskGetNumberOfTasks uxTaskGetNumberOfTasks
* \ingroup TaskUtils
*/
UBaseType_t uxTaskGetNumberOfTasks( void ) PRIVILEGED_FUNCTION;
/**
* task. h
* <PRE>char *pcTaskGetTaskName( TaskHandle_t xTaskToQuery );</PRE>
*
* @return The text (human readable) name of the task referenced by the handle
* xTaskToQuery. A task can query its own name by either passing in its own
* handle, or by setting xTaskToQuery to NULL. INCLUDE_pcTaskGetTaskName must be
* set to 1 in FreeRTOSConfig.h for pcTaskGetTaskName() to be available.
*
* \defgroup pcTaskGetTaskName pcTaskGetTaskName
* \ingroup TaskUtils
*/
char *pcTaskGetTaskName( TaskHandle_t xTaskToQuery ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
/**
* task.h
* <PRE>UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask );</PRE>
*
* INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for
* this function to be available.
*
* Returns the high water mark of the stack associated with xTask. That is,
* the minimum free stack space there has been (in words, so on a 32 bit machine
* a value of 1 means 4 bytes) since the task started. The smaller the returned
* number the closer the task has come to overflowing its stack.
*
* @param xTask Handle of the task associated with the stack to be checked.
* Set xTask to NULL to check the stack of the calling task.
*
* @return The smallest amount of free stack space there has been (in words, so
* actual spaces on the stack rather than bytes) since the task referenced by
* xTask was created.
*/
UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
/* When using trace macros it is sometimes necessary to include task.h before
FreeRTOS.h. When this is done TaskHookFunction_t will not yet have been defined,
so the following two prototypes will cause a compilation error. This can be
fixed by simply guarding against the inclusion of these two prototypes unless
they are explicitly required by the configUSE_APPLICATION_TASK_TAG configuration
constant. */
#ifdef configUSE_APPLICATION_TASK_TAG
#if configUSE_APPLICATION_TASK_TAG == 1
/**
* task.h
* <pre>void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction );</pre>
*
* Sets pxHookFunction to be the task hook function used by the task xTask.
* Passing xTask as NULL has the effect of setting the calling tasks hook
* function.
*/
void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) PRIVILEGED_FUNCTION;
/**
* task.h
* <pre>void xTaskGetApplicationTaskTag( TaskHandle_t xTask );</pre>
*
* Returns the pxHookFunction value assigned to the task xTask.
*/
TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
#endif /* configUSE_APPLICATION_TASK_TAG ==1 */
#endif /* ifdef configUSE_APPLICATION_TASK_TAG */
#if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 )
/* Each task contains an array of pointers that is dimensioned by the
configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The
kernel does not use the pointers itself, so the application writer can use
the pointers for any purpose they wish. The following two functions are
used to set and query a pointer respectively. */
void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue );
void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex );
#endif
/**
* task.h
* <pre>BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter );</pre>
*
* Calls the hook function associated with xTask. Passing xTask as NULL has
* the effect of calling the Running tasks (the calling task) hook function.
*
* pvParameter is passed to the hook function for the task to interpret as it
* wants. The return value is the value returned by the task hook function
* registered by the user.
*/
BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) PRIVILEGED_FUNCTION;
/**
* xTaskGetIdleTaskHandle() is only available if
* INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h.
*
* Simply returns the handle of the idle task. It is not valid to call
* xTaskGetIdleTaskHandle() before the scheduler has been started.
*/
TaskHandle_t xTaskGetIdleTaskHandle( void );
/**
* configUSE_TRACE_FACILITY must be defined as 1 in FreeRTOSConfig.h for
* uxTaskGetSystemState() to be available.
*
* uxTaskGetSystemState() populates an TaskStatus_t structure for each task in
* the system. TaskStatus_t structures contain, among other things, members
* for the task handle, task name, task priority, task state, and total amount
* of run time consumed by the task. See the TaskStatus_t structure
* definition in this file for the full member list.
*
* NOTE: This function is intended for debugging use only as its use results in
* the scheduler remaining suspended for an extended period.
*
* @param pxTaskStatusArray A pointer to an array of TaskStatus_t structures.
* The array must contain at least one TaskStatus_t structure for each task
* that is under the control of the RTOS. The number of tasks under the control
* of the RTOS can be determined using the uxTaskGetNumberOfTasks() API function.
*
* @param uxArraySize The size of the array pointed to by the pxTaskStatusArray
* parameter. The size is specified as the number of indexes in the array, or
* the number of TaskStatus_t structures contained in the array, not by the
* number of bytes in the array.
*
* @param pulTotalRunTime If configGENERATE_RUN_TIME_STATS is set to 1 in
* FreeRTOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the
* total run time (as defined by the run time stats clock, see
* http://www.freertos.org/rtos-run-time-stats.html) since the target booted.
* pulTotalRunTime can be set to NULL to omit the total run time information.
*
* @return The number of TaskStatus_t structures that were populated by
* uxTaskGetSystemState(). This should equal the number returned by the
* uxTaskGetNumberOfTasks() API function, but will be zero if the value passed
* in the uxArraySize parameter was too small.
*
* Example usage:
<pre>
// This example demonstrates how a human readable table of run time stats
// information is generated from raw data provided by uxTaskGetSystemState().
// The human readable table is written to pcWriteBuffer
void vTaskGetRunTimeStats( char *pcWriteBuffer )
{
TaskStatus_t *pxTaskStatusArray;
volatile UBaseType_t uxArraySize, x;
uint32_t ulTotalRunTime, ulStatsAsPercentage;
// Make sure the write buffer does not contain a string.
*pcWriteBuffer = 0x00;
// Take a snapshot of the number of tasks in case it changes while this
// function is executing.
uxArraySize = uxTaskGetNumberOfTasks();
// Allocate a TaskStatus_t structure for each task. An array could be
// allocated statically at compile time.
pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) );
if( pxTaskStatusArray != NULL )
{
// Generate raw status information about each task.
uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime );
// For percentage calculations.
ulTotalRunTime /= 100UL;
// Avoid divide by zero errors.
if( ulTotalRunTime > 0 )
{
// For each populated position in the pxTaskStatusArray array,
// format the raw data as human readable ASCII data
for( x = 0; x < uxArraySize; x++ )
{
// What percentage of the total run time has the task used?
// This will always be rounded down to the nearest integer.
// ulTotalRunTimeDiv100 has already been divided by 100.
ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime;
if( ulStatsAsPercentage > 0UL )
{
sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
}
else
{
// If the percentage is zero here then the task has
// consumed less than 1% of the total run time.
sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter );
}
pcWriteBuffer += strlen( ( char * ) pcWriteBuffer );
}
}
// The array is no longer needed, free the memory it consumes.
vPortFree( pxTaskStatusArray );
}
}
</pre>
*/
UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime );
/**
* task. h
* <PRE>void vTaskList( char *pcWriteBuffer );</PRE>
*
* configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must
* both be defined as 1 for this function to be available. See the
* configuration section of the FreeRTOS.org website for more information.
*
* NOTE 1: This function will disable interrupts for its duration. It is
* not intended for normal application runtime use but as a debug aid.
*
* Lists all the current tasks, along with their current state and stack
* usage high water mark.
*
* Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or
* suspended ('S').
*
* PLEASE NOTE:
*
* This function is provided for convenience only, and is used by many of the
* demo applications. Do not consider it to be part of the scheduler.
*
* vTaskList() calls uxTaskGetSystemState(), then formats part of the
* uxTaskGetSystemState() output into a human readable table that displays task
* names, states and stack usage.
*
* vTaskList() has a dependency on the sprintf() C library function that might
* bloat the code size, use a lot of stack, and provide different results on
* different platforms. An alternative, tiny, third party, and limited
* functionality implementation of sprintf() is provided in many of the
* FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note
* printf-stdarg.c does not provide a full snprintf() implementation!).
*
* It is recommended that production systems call uxTaskGetSystemState()
* directly to get access to raw stats data, rather than indirectly through a
* call to vTaskList().
*
* @param pcWriteBuffer A buffer into which the above mentioned details
* will be written, in ASCII form. This buffer is assumed to be large
* enough to contain the generated report. Approximately 40 bytes per
* task should be sufficient.
*
* \defgroup vTaskList vTaskList
* \ingroup TaskUtils
*/
void vTaskList( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
/**
* task. h
* <PRE>void vTaskGetRunTimeStats( char *pcWriteBuffer );</PRE>
*
* configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS
* must both be defined as 1 for this function to be available. The application
* must also then provide definitions for
* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE()
* to configure a peripheral timer/counter and return the timers current count
* value respectively. The counter should be at least 10 times the frequency of
* the tick count.
*
* NOTE 1: This function will disable interrupts for its duration. It is
* not intended for normal application runtime use but as a debug aid.
*
* Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total
* accumulated execution time being stored for each task. The resolution
* of the accumulated time value depends on the frequency of the timer
* configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro.
* Calling vTaskGetRunTimeStats() writes the total execution time of each
* task into a buffer, both as an absolute count value and as a percentage
* of the total system execution time.
*
* NOTE 2:
*
* This function is provided for convenience only, and is used by many of the
* demo applications. Do not consider it to be part of the scheduler.
*
* vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the
* uxTaskGetSystemState() output into a human readable table that displays the
* amount of time each task has spent in the Running state in both absolute and
* percentage terms.
*
* vTaskGetRunTimeStats() has a dependency on the sprintf() C library function
* that might bloat the code size, use a lot of stack, and provide different
* results on different platforms. An alternative, tiny, third party, and
* limited functionality implementation of sprintf() is provided in many of the
* FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note
* printf-stdarg.c does not provide a full snprintf() implementation!).
*
* It is recommended that production systems call uxTaskGetSystemState() directly
* to get access to raw stats data, rather than indirectly through a call to
* vTaskGetRunTimeStats().
*
* @param pcWriteBuffer A buffer into which the execution times will be
* written, in ASCII form. This buffer is assumed to be large enough to
* contain the generated report. Approximately 40 bytes per task should
* be sufficient.
*
* \defgroup vTaskGetRunTimeStats vTaskGetRunTimeStats
* \ingroup TaskUtils
*/
void vTaskGetRunTimeStats( char *pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
/**
* task. h
* <PRE>BaseType_t xTaskNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction );</PRE>
*
* configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
* function to be available.
*
* When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
* "notification value", which is a 32-bit unsigned integer (uint32_t).
*
* Events can be sent to a task using an intermediary object. Examples of such
* objects are queues, semaphores, mutexes and event groups. Task notifications
* are a method of sending an event directly to a task without the need for such
* an intermediary object.
*
* A notification sent to a task can optionally perform an action, such as
* update, overwrite or increment the task's notification value. In that way
* task notifications can be used to send data to a task, or be used as light
* weight and fast binary or counting semaphores.
*
* A notification sent to a task will remain pending until it is cleared by the
* task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was
* already in the Blocked state to wait for a notification when the notification
* arrives then the task will automatically be removed from the Blocked state
* (unblocked) and the notification cleared.
*
* A task can use xTaskNotifyWait() to [optionally] block to wait for a
* notification to be pending, or ulTaskNotifyTake() to [optionally] block
* to wait for its notification value to have a non-zero value. The task does
* not consume any CPU time while it is in the Blocked state.
*
* See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
*
* @param xTaskToNotify The handle of the task being notified. The handle to a
* task can be returned from the xTaskCreate() API function used to create the
* task, and the handle of the currently running task can be obtained by calling
* xTaskGetCurrentTaskHandle().
*
* @param ulValue Data that can be sent with the notification. How the data is
* used depends on the value of the eAction parameter.
*
* @param eAction Specifies how the notification updates the task's notification
* value, if at all. Valid values for eAction are as follows:
*
* eSetBits -
* The task's notification value is bitwise ORed with ulValue. xTaskNofify()
* always returns pdPASS in this case.
*
* eIncrement -
* The task's notification value is incremented. ulValue is not used and
* xTaskNotify() always returns pdPASS in this case.
*
* eSetValueWithOverwrite -
* The task's notification value is set to the value of ulValue, even if the
* task being notified had not yet processed the previous notification (the
* task already had a notification pending). xTaskNotify() always returns
* pdPASS in this case.
*
* eSetValueWithoutOverwrite -
* If the task being notified did not already have a notification pending then
* the task's notification value is set to ulValue and xTaskNotify() will
* return pdPASS. If the task being notified already had a notification
* pending then no action is performed and pdFAIL is returned.
*
* eNoAction -
* The task receives a notification without its notification value being
* updated. ulValue is not used and xTaskNotify() always returns pdPASS in
* this case.
*
* pulPreviousNotificationValue -
* Can be used to pass out the subject task's notification value before any
* bits are modified by the notify function.
*
* @return Dependent on the value of eAction. See the description of the
* eAction parameter.
*
* \defgroup xTaskNotify xTaskNotify
* \ingroup TaskNotifications
*/
BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue );
#define xTaskNotify( xTaskToNotify, ulValue, eAction ) xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL )
#define xTaskNotifyAndQuery( xTaskToNotify, ulValue, eAction, pulPreviousNotifyValue ) xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotifyValue ) )
/**
* task. h
* <PRE>BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken );</PRE>
*
* configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
* function to be available.
*
* When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
* "notification value", which is a 32-bit unsigned integer (uint32_t).
*
* A version of xTaskNotify() that can be used from an interrupt service routine
* (ISR).
*
* Events can be sent to a task using an intermediary object. Examples of such
* objects are queues, semaphores, mutexes and event groups. Task notifications
* are a method of sending an event directly to a task without the need for such
* an intermediary object.
*
* A notification sent to a task can optionally perform an action, such as
* update, overwrite or increment the task's notification value. In that way
* task notifications can be used to send data to a task, or be used as light
* weight and fast binary or counting semaphores.
*
* A notification sent to a task will remain pending until it is cleared by the
* task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was
* already in the Blocked state to wait for a notification when the notification
* arrives then the task will automatically be removed from the Blocked state
* (unblocked) and the notification cleared.
*
* A task can use xTaskNotifyWait() to [optionally] block to wait for a
* notification to be pending, or ulTaskNotifyTake() to [optionally] block
* to wait for its notification value to have a non-zero value. The task does
* not consume any CPU time while it is in the Blocked state.
*
* See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
*
* @param xTaskToNotify The handle of the task being notified. The handle to a
* task can be returned from the xTaskCreate() API function used to create the
* task, and the handle of the currently running task can be obtained by calling
* xTaskGetCurrentTaskHandle().
*
* @param ulValue Data that can be sent with the notification. How the data is
* used depends on the value of the eAction parameter.
*
* @param eAction Specifies how the notification updates the task's notification
* value, if at all. Valid values for eAction are as follows:
*
* eSetBits -
* The task's notification value is bitwise ORed with ulValue. xTaskNofify()
* always returns pdPASS in this case.
*
* eIncrement -
* The task's notification value is incremented. ulValue is not used and
* xTaskNotify() always returns pdPASS in this case.
*
* eSetValueWithOverwrite -
* The task's notification value is set to the value of ulValue, even if the
* task being notified had not yet processed the previous notification (the
* task already had a notification pending). xTaskNotify() always returns
* pdPASS in this case.
*
* eSetValueWithoutOverwrite -
* If the task being notified did not already have a notification pending then
* the task's notification value is set to ulValue and xTaskNotify() will
* return pdPASS. If the task being notified already had a notification
* pending then no action is performed and pdFAIL is returned.
*
* eNoAction -
* The task receives a notification without its notification value being
* updated. ulValue is not used and xTaskNotify() always returns pdPASS in
* this case.
*
* @param pxHigherPriorityTaskWoken xTaskNotifyFromISR() will set
* *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the
* task to which the notification was sent to leave the Blocked state, and the
* unblocked task has a priority higher than the currently running task. If
* xTaskNotifyFromISR() sets this value to pdTRUE then a context switch should
* be requested before the interrupt is exited. How a context switch is
* requested from an ISR is dependent on the port - see the documentation page
* for the port in use.
*
* @return Dependent on the value of eAction. See the description of the
* eAction parameter.
*
* \defgroup xTaskNotify xTaskNotify
* \ingroup TaskNotifications
*/
BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken );
/**
* task. h
* <PRE>BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait );</pre>
*
* configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
* function to be available.
*
* When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
* "notification value", which is a 32-bit unsigned integer (uint32_t).
*
* Events can be sent to a task using an intermediary object. Examples of such
* objects are queues, semaphores, mutexes and event groups. Task notifications
* are a method of sending an event directly to a task without the need for such
* an intermediary object.
*
* A notification sent to a task can optionally perform an action, such as
* update, overwrite or increment the task's notification value. In that way
* task notifications can be used to send data to a task, or be used as light
* weight and fast binary or counting semaphores.
*
* A notification sent to a task will remain pending until it is cleared by the
* task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was
* already in the Blocked state to wait for a notification when the notification
* arrives then the task will automatically be removed from the Blocked state
* (unblocked) and the notification cleared.
*
* A task can use xTaskNotifyWait() to [optionally] block to wait for a
* notification to be pending, or ulTaskNotifyTake() to [optionally] block
* to wait for its notification value to have a non-zero value. The task does
* not consume any CPU time while it is in the Blocked state.
*
* See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
*
* @param ulBitsToClearOnEntry Bits that are set in ulBitsToClearOnEntry value
* will be cleared in the calling task's notification value before the task
* checks to see if any notifications are pending, and optionally blocks if no
* notifications are pending. Setting ulBitsToClearOnEntry to ULONG_MAX (if
* limits.h is included) or 0xffffffffUL (if limits.h is not included) will have
* the effect of resetting the task's notification value to 0. Setting
* ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged.
*
* @param ulBitsToClearOnExit If a notification is pending or received before
* the calling task exits the xTaskNotifyWait() function then the task's
* notification value (see the xTaskNotify() API function) is passed out using
* the pulNotificationValue parameter. Then any bits that are set in
* ulBitsToClearOnExit will be cleared in the task's notification value (note
* *pulNotificationValue is set before any bits are cleared). Setting
* ulBitsToClearOnExit to ULONG_MAX (if limits.h is included) or 0xffffffffUL
* (if limits.h is not included) will have the effect of resetting the task's
* notification value to 0 before the function exits. Setting
* ulBitsToClearOnExit to 0 will leave the task's notification value unchanged
* when the function exits (in which case the value passed out in
* pulNotificationValue will match the task's notification value).
*
* @param pulNotificationValue Used to pass the task's notification value out
* of the function. Note the value passed out will not be effected by the
* clearing of any bits caused by ulBitsToClearOnExit being non-zero.
*
* @param xTicksToWait The maximum amount of time that the task should wait in
* the Blocked state for a notification to be received, should a notification
* not already be pending when xTaskNotifyWait() was called. The task
* will not consume any processing time while it is in the Blocked state. This
* is specified in kernel ticks, the macro pdMS_TO_TICSK( value_in_ms ) can be
* used to convert a time specified in milliseconds to a time specified in
* ticks.
*
* @return If a notification was received (including notifications that were
* already pending when xTaskNotifyWait was called) then pdPASS is
* returned. Otherwise pdFAIL is returned.
*
* \defgroup xTaskNotifyWait xTaskNotifyWait
* \ingroup TaskNotifications
*/
BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait );
/**
* task. h
* <PRE>BaseType_t xTaskNotifyGive( TaskHandle_t xTaskToNotify );</PRE>
*
* configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro
* to be available.
*
* When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
* "notification value", which is a 32-bit unsigned integer (uint32_t).
*
* Events can be sent to a task using an intermediary object. Examples of such
* objects are queues, semaphores, mutexes and event groups. Task notifications
* are a method of sending an event directly to a task without the need for such
* an intermediary object.
*
* A notification sent to a task can optionally perform an action, such as
* update, overwrite or increment the task's notification value. In that way
* task notifications can be used to send data to a task, or be used as light
* weight and fast binary or counting semaphores.
*
* xTaskNotifyGive() is a helper macro intended for use when task notifications
* are used as light weight and faster binary or counting semaphore equivalents.
* Actual FreeRTOS semaphores are given using the xSemaphoreGive() API function,
* the equivalent action that instead uses a task notification is
* xTaskNotifyGive().
*
* When task notifications are being used as a binary or counting semaphore
* equivalent then the task being notified should wait for the notification
* using the ulTaskNotificationTake() API function rather than the
* xTaskNotifyWait() API function.
*
* See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
*
* @param xTaskToNotify The handle of the task being notified. The handle to a
* task can be returned from the xTaskCreate() API function used to create the
* task, and the handle of the currently running task can be obtained by calling
* xTaskGetCurrentTaskHandle().
*
* @return xTaskNotifyGive() is a macro that calls xTaskNotify() with the
* eAction parameter set to eIncrement - so pdPASS is always returned.
*
* \defgroup xTaskNotifyGive xTaskNotifyGive
* \ingroup TaskNotifications
*/
#define xTaskNotifyGive( xTaskToNotify ) xTaskNotify( ( xTaskToNotify ), 0, eIncrement );
/**
* task. h
* <PRE>void vTaskNotifyGiveFromISR( TaskHandle_t xTaskHandle, BaseType_t *pxHigherPriorityTaskWoken );
*
* configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro
* to be available.
*
* When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
* "notification value", which is a 32-bit unsigned integer (uint32_t).
*
* A version of xTaskNotifyGive() that can be called from an interrupt service
* routine (ISR).
*
* Events can be sent to a task using an intermediary object. Examples of such
* objects are queues, semaphores, mutexes and event groups. Task notifications
* are a method of sending an event directly to a task without the need for such
* an intermediary object.
*
* A notification sent to a task can optionally perform an action, such as
* update, overwrite or increment the task's notification value. In that way
* task notifications can be used to send data to a task, or be used as light
* weight and fast binary or counting semaphores.
*
* vTaskNotifyGiveFromISR() is intended for use when task notifications are
* used as light weight and faster binary or counting semaphore equivalents.
* Actual FreeRTOS semaphores are given from an ISR using the
* xSemaphoreGiveFromISR() API function, the equivalent action that instead uses
* a task notification is vTaskNotifyGiveFromISR().
*
* When task notifications are being used as a binary or counting semaphore
* equivalent then the task being notified should wait for the notification
* using the ulTaskNotificationTake() API function rather than the
* xTaskNotifyWait() API function.
*
* See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
*
* @param xTaskToNotify The handle of the task being notified. The handle to a
* task can be returned from the xTaskCreate() API function used to create the
* task, and the handle of the currently running task can be obtained by calling
* xTaskGetCurrentTaskHandle().
*
* @param pxHigherPriorityTaskWoken vTaskNotifyGiveFromISR() will set
* *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the
* task to which the notification was sent to leave the Blocked state, and the
* unblocked task has a priority higher than the currently running task. If
* vTaskNotifyGiveFromISR() sets this value to pdTRUE then a context switch
* should be requested before the interrupt is exited. How a context switch is
* requested from an ISR is dependent on the port - see the documentation page
* for the port in use.
*
* \defgroup xTaskNotifyWait xTaskNotifyWait
* \ingroup TaskNotifications
*/
void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken );
/**
* task. h
* <PRE>uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait );</pre>
*
* configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
* function to be available.
*
* When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
* "notification value", which is a 32-bit unsigned integer (uint32_t).
*
* Events can be sent to a task using an intermediary object. Examples of such
* objects are queues, semaphores, mutexes and event groups. Task notifications
* are a method of sending an event directly to a task without the need for such
* an intermediary object.
*
* A notification sent to a task can optionally perform an action, such as
* update, overwrite or increment the task's notification value. In that way
* task notifications can be used to send data to a task, or be used as light
* weight and fast binary or counting semaphores.
*
* ulTaskNotifyTake() is intended for use when a task notification is used as a
* faster and lighter weight binary or counting semaphore alternative. Actual
* FreeRTOS semaphores are taken using the xSemaphoreTake() API function, the
* equivalent action that instead uses a task notification is
* ulTaskNotifyTake().
*
* When a task is using its notification value as a binary or counting semaphore
* other tasks should send notifications to it using the xTaskNotifyGive()
* macro, or xTaskNotify() function with the eAction parameter set to
* eIncrement.
*
* ulTaskNotifyTake() can either clear the task's notification value to
* zero on exit, in which case the notification value acts like a binary
* semaphore, or decrement the task's notification value on exit, in which case
* the notification value acts like a counting semaphore.
*
* A task can use ulTaskNotifyTake() to [optionally] block to wait for a
* the task's notification value to be non-zero. The task does not consume any
* CPU time while it is in the Blocked state.
*
* Where as xTaskNotifyWait() will return when a notification is pending,
* ulTaskNotifyTake() will return when the task's notification value is
* not zero.
*
* See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
*
* @param xClearCountOnExit if xClearCountOnExit is pdFALSE then the task's
* notification value is decremented when the function exits. In this way the
* notification value acts like a counting semaphore. If xClearCountOnExit is
* not pdFALSE then the task's notification value is cleared to zero when the
* function exits. In this way the notification value acts like a binary
* semaphore.
*
* @param xTicksToWait The maximum amount of time that the task should wait in
* the Blocked state for the task's notification value to be greater than zero,
* should the count not already be greater than zero when
* ulTaskNotifyTake() was called. The task will not consume any processing
* time while it is in the Blocked state. This is specified in kernel ticks,
* the macro pdMS_TO_TICSK( value_in_ms ) can be used to convert a time
* specified in milliseconds to a time specified in ticks.
*
* @return The task's notification count before it is either cleared to zero or
* decremented (see the xClearCountOnExit parameter).
*
* \defgroup ulTaskNotifyTake ulTaskNotifyTake
* \ingroup TaskNotifications
*/
uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait );
/*-----------------------------------------------------------
* SCHEDULER INTERNALS AVAILABLE FOR PORTING PURPOSES
*----------------------------------------------------------*/
/*
* THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY
* INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS
* AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
*
* Called from the real time kernel tick (either preemptive or cooperative),
* this increments the tick count and checks if any tasks that are blocked
* for a finite period required removing from a blocked list and placing on
* a ready list. If a non-zero value is returned then a context switch is
* required because either:
* + A task was removed from a blocked list because its timeout had expired,
* or
* + Time slicing is in use and there is a task of equal priority to the
* currently running task.
*/
BaseType_t xTaskIncrementTick( void ) PRIVILEGED_FUNCTION;
/*
* THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN
* INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
*
* THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED.
*
* Removes the calling task from the ready list and places it both
* on the list of tasks waiting for a particular event, and the
* list of delayed tasks. The task will be removed from both lists
* and replaced on the ready list should either the event occur (and
* there be no higher priority tasks waiting on the same event) or
* the delay period expires.
*
* The 'unordered' version replaces the event list item value with the
* xItemValue value, and inserts the list item at the end of the list.
*
* The 'ordered' version uses the existing event list item value (which is the
* owning tasks priority) to insert the list item into the event list is task
* priority order.
*
* @param pxEventList The list containing tasks that are blocked waiting
* for the event to occur.
*
* @param xItemValue The item value to use for the event list item when the
* event list is not ordered by task priority.
*
* @param xTicksToWait The maximum amount of time that the task should wait
* for the event to occur. This is specified in kernel ticks,the constant
* portTICK_PERIOD_MS can be used to convert kernel ticks into a real time
* period.
*/
void vTaskPlaceOnEventList( List_t * const pxEventList, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
/*
* THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN
* INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
*
* THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED.
*
* This function performs nearly the same function as vTaskPlaceOnEventList().
* The difference being that this function does not permit tasks to block
* indefinitely, whereas vTaskPlaceOnEventList() does.
*
*/
void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
/*
* THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN
* INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
*
* THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED.
*
* Removes a task from both the specified event list and the list of blocked
* tasks, and places it on a ready queue.
*
* xTaskRemoveFromEventList()/xTaskRemoveFromUnorderedEventList() will be called
* if either an event occurs to unblock a task, or the block timeout period
* expires.
*
* xTaskRemoveFromEventList() is used when the event list is in task priority
* order. It removes the list item from the head of the event list as that will
* have the highest priority owning task of all the tasks on the event list.
* xTaskRemoveFromUnorderedEventList() is used when the event list is not
* ordered and the event list items hold something other than the owning tasks
* priority. In this case the event list item value is updated to the value
* passed in the xItemValue parameter.
*
* @return pdTRUE if the task being removed has a higher priority than the task
* making the call, otherwise pdFALSE.
*/
BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) PRIVILEGED_FUNCTION;
BaseType_t xTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, const TickType_t xItemValue ) PRIVILEGED_FUNCTION;
/*
* THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY
* INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS
* AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
*
* Sets the pointer to the current TCB to the TCB of the highest priority task
* that is ready to run.
*/
void vTaskSwitchContext( void ) PRIVILEGED_FUNCTION;
/*
* THESE FUNCTIONS MUST NOT BE USED FROM APPLICATION CODE. THEY ARE USED BY
* THE EVENT BITS MODULE.
*/
TickType_t uxTaskResetEventItemValue( void ) PRIVILEGED_FUNCTION;
/*
* Return the handle of the calling task.
*/
TaskHandle_t xTaskGetCurrentTaskHandle( void ) PRIVILEGED_FUNCTION;
/*
* Capture the current time status for future reference.
*/
void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION;
/*
* Compare the time status now with that previously captured to see if the
* timeout has expired.
*/
BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ) PRIVILEGED_FUNCTION;
/*
* Shortcut used by the queue implementation to prevent unnecessary call to
* taskYIELD();
*/
void vTaskMissedYield( void ) PRIVILEGED_FUNCTION;
/*
* Returns the scheduler state as taskSCHEDULER_RUNNING,
* taskSCHEDULER_NOT_STARTED or taskSCHEDULER_SUSPENDED.
*/
BaseType_t xTaskGetSchedulerState( void ) PRIVILEGED_FUNCTION;
/*
* Raises the priority of the mutex holder to that of the calling task should
* the mutex holder have a priority less than the calling task.
*/
void vTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION;
/*
* Set the priority of a task back to its proper priority in the case that it
* inherited a higher priority while it was holding a semaphore.
*/
BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION;
/*
* Generic version of the task creation function which is in turn called by the
* xTaskCreate() and xTaskCreateRestricted() macros.
*/
BaseType_t xTaskGenericCreate( TaskFunction_t pxTaskCode, const char * const pcName, const uint16_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pxCreatedTask, StackType_t * const puxStackBuffer, const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
/*
* Get the uxTCBNumber assigned to the task referenced by the xTask parameter.
*/
UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
/*
* Set the uxTaskNumber of the task referenced by the xTask parameter to
* uxHandle.
*/
void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle ) PRIVILEGED_FUNCTION;
/*
* Only available when configUSE_TICKLESS_IDLE is set to 1.
* If tickless mode is being used, or a low power mode is implemented, then
* the tick interrupt will not execute during idle periods. When this is the
* case, the tick count value maintained by the scheduler needs to be kept up
* to date with the actual execution time by being skipped forward by a time
* equal to the idle period.
*/
void vTaskStepTick( const TickType_t xTicksToJump ) PRIVILEGED_FUNCTION;
/*
* Only avilable when configUSE_TICKLESS_IDLE is set to 1.
* Provided for use within portSUPPRESS_TICKS_AND_SLEEP() to allow the port
* specific sleep function to determine if it is ok to proceed with the sleep,
* and if it is ok to proceed, if it is ok to sleep indefinitely.
*
* This function is necessary because portSUPPRESS_TICKS_AND_SLEEP() is only
* called with the scheduler suspended, not from within a critical section. It
* is therefore possible for an interrupt to request a context switch between
* portSUPPRESS_TICKS_AND_SLEEP() and the low power mode actually being
* entered. eTaskConfirmSleepModeStatus() should be called from a short
* critical section between the timer being stopped and the sleep mode being
* entered to ensure it is ok to proceed into the sleep mode.
*/
eSleepModeStatus eTaskConfirmSleepModeStatus( void ) PRIVILEGED_FUNCTION;
/*
* For internal use only. Increment the mutex held count when a mutex is
* taken and return the handle of the task that has taken the mutex.
*/
void *pvTaskIncrementMutexHeldCount( void );
#ifdef __cplusplus
}
#endif
#endif /* INC_TASK_H */
|
{
"pile_set_name": "Github"
}
|
/*
FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
All rights reserved
VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
This file is part of the FreeRTOS distribution.
FreeRTOS is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License (version 2) as published by the
Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
***************************************************************************
>>! NOTE: The modification to the GPL is included to allow you to !<<
>>! distribute a combined work that includes FreeRTOS without being !<<
>>! obliged to provide the source code for proprietary components !<<
>>! outside of the FreeRTOS kernel. !<<
***************************************************************************
FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. Full license text is available on the following
link: http://www.freertos.org/a00114.html
***************************************************************************
* *
* FreeRTOS provides completely free yet professionally developed, *
* robust, strictly quality controlled, supported, and cross *
* platform software that is more than just the market leader, it *
* is the industry's de facto standard. *
* *
* Help yourself get started quickly while simultaneously helping *
* to support the FreeRTOS project by purchasing a FreeRTOS *
* tutorial book, reference manual, or both: *
* http://www.FreeRTOS.org/Documentation *
* *
***************************************************************************
http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading
the FAQ page "My application does not run, what could be wrong?". Have you
defined configASSERT()?
http://www.FreeRTOS.org/support - In return for receiving this top quality
embedded software for free we request you assist our global community by
participating in the support forum.
http://www.FreeRTOS.org/training - Investing in training allows your team to
be as productive as possible as early as possible. Now you can receive
FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
Ltd, and the world's leading authority on the world's leading RTOS.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool, a DOS
compatible FAT file system, and our tiny thread aware UDP/IP stack.
http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS
licenses offer ticketed support, indemnification and commercial middleware.
http://www.SafeRTOS.com - High Integrity Systems also provide a safety
engineered and independently SIL3 certified version for use in safety and
mission critical applications that require provable dependability.
1 tab == 4 spaces!
*/
/*-----------------------------------------------------------
* Implementation of functions defined in portable.h for the ARM CM4F port.
*----------------------------------------------------------*/
/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"
#ifndef __TARGET_FPU_VFP
#error This port can only be used when the project options are configured to enable hardware floating point support.
#endif
#if configMAX_SYSCALL_INTERRUPT_PRIORITY == 0
#error configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0. See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
#endif
#ifndef configSYSTICK_CLOCK_HZ
#define configSYSTICK_CLOCK_HZ configCPU_CLOCK_HZ
/* Ensure the SysTick is clocked at the same frequency as the core. */
#define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
#else
/* The way the SysTick is clocked is not modified in case it is not the same
as the core. */
#define portNVIC_SYSTICK_CLK_BIT ( 0 )
#endif
/* The __weak attribute does not work as you might expect with the Keil tools
so the configOVERRIDE_DEFAULT_TICK_CONFIGURATION constant must be set to 1 if
the application writer wants to provide their own implementation of
vPortSetupTimerInterrupt(). Ensure configOVERRIDE_DEFAULT_TICK_CONFIGURATION
is defined. */
#ifndef configOVERRIDE_DEFAULT_TICK_CONFIGURATION
#define configOVERRIDE_DEFAULT_TICK_CONFIGURATION 0
#endif
/* Constants required to manipulate the core. Registers first... */
#define portNVIC_SYSTICK_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000e010 ) )
#define portNVIC_SYSTICK_LOAD_REG ( * ( ( volatile uint32_t * ) 0xe000e014 ) )
#define portNVIC_SYSTICK_CURRENT_VALUE_REG ( * ( ( volatile uint32_t * ) 0xe000e018 ) )
#define portNVIC_SYSPRI2_REG ( * ( ( volatile uint32_t * ) 0xe000ed20 ) )
/* ...then bits in the registers. */
#define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
#define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
#define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
#define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL )
#define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL )
#define portNVIC_PENDSV_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL )
#define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL )
/* Constants required to check the validity of an interrupt priority. */
#define portFIRST_USER_INTERRUPT_NUMBER ( 16 )
#define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 )
#define portAIRCR_REG ( * ( ( volatile uint32_t * ) 0xE000ED0C ) )
#define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff )
#define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 )
#define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 )
#define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL )
#define portPRIGROUP_SHIFT ( 8UL )
/* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
#define portVECTACTIVE_MASK ( 0xFFUL )
/* Constants required to manipulate the VFP. */
#define portFPCCR ( ( volatile uint32_t * ) 0xe000ef34 ) /* Floating point context control register. */
#define portASPEN_AND_LSPEN_BITS ( 0x3UL << 30UL )
/* Constants required to set up the initial stack. */
#define portINITIAL_XPSR ( 0x01000000 )
#define portINITIAL_EXEC_RETURN ( 0xfffffffd )
/* The systick is a 24-bit counter. */
#define portMAX_24_BIT_NUMBER ( 0xffffffUL )
/* A fiddle factor to estimate the number of SysTick counts that would have
occurred while the SysTick counter is stopped during tickless idle
calculations. */
#define portMISSED_COUNTS_FACTOR ( 45UL )
/* Each task maintains its own interrupt status in the critical nesting
variable. */
static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
/*
* Setup the timer to generate the tick interrupts. The implementation in this
* file is weak to allow application writers to change the timer used to
* generate the tick interrupt.
*/
void vPortSetupTimerInterrupt( void );
/*
* Exception handlers.
*/
void xPortPendSVHandler( void );
void xPortSysTickHandler( void );
void vPortSVCHandler( void );
/*
* Start first task is a separate function so it can be tested in isolation.
*/
static void prvStartFirstTask( void );
/*
* Functions defined in portasm.s to enable the VFP.
*/
static void prvEnableVFP( void );
/*
* Used to catch tasks that attempt to return from their implementing function.
*/
static void prvTaskExitError( void );
/*-----------------------------------------------------------*/
/*
* The number of SysTick increments that make up one tick period.
*/
#if configUSE_TICKLESS_IDLE == 1
static uint32_t ulTimerCountsForOneTick = 0;
#endif /* configUSE_TICKLESS_IDLE */
/*
* The maximum number of tick periods that can be suppressed is limited by the
* 24 bit resolution of the SysTick timer.
*/
#if configUSE_TICKLESS_IDLE == 1
static uint32_t xMaximumPossibleSuppressedTicks = 0;
#endif /* configUSE_TICKLESS_IDLE */
/*
* Compensate for the CPU cycles that pass while the SysTick is stopped (low
* power functionality only.
*/
#if configUSE_TICKLESS_IDLE == 1
static uint32_t ulStoppedTimerCompensation = 0;
#endif /* configUSE_TICKLESS_IDLE */
/*
* Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
* FreeRTOS API functions are not called from interrupts that have been assigned
* a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
*/
#if ( configASSERT_DEFINED == 1 )
static uint8_t ucMaxSysCallPriority = 0;
static uint32_t ulMaxPRIGROUPValue = 0;
static const volatile uint8_t * const pcInterruptPriorityRegisters = ( uint8_t * ) portNVIC_IP_REGISTERS_OFFSET_16;
#endif /* configASSERT_DEFINED */
/*-----------------------------------------------------------*/
/*
* See header file for description.
*/
StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
{
/* Simulate the stack frame as it would be created by a context switch
interrupt. */
/* Offset added to account for the way the MCU uses the stack on entry/exit
of interrupts, and to ensure alignment. */
pxTopOfStack--;
*pxTopOfStack = portINITIAL_XPSR; /* xPSR */
pxTopOfStack--;
*pxTopOfStack = ( StackType_t ) pxCode; /* PC */
pxTopOfStack--;
*pxTopOfStack = ( StackType_t ) prvTaskExitError; /* LR */
/* Save code space by skipping register initialisation. */
pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
*pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
/* A save method is being used that requires each task to maintain its
own exec return value. */
pxTopOfStack--;
*pxTopOfStack = portINITIAL_EXEC_RETURN;
pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
return pxTopOfStack;
}
/*-----------------------------------------------------------*/
static void prvTaskExitError( void )
{
/* A function that implements a task must not exit or attempt to return to
its caller as there is nothing to return to. If a task wants to exit it
should instead call vTaskDelete( NULL ).
Artificially force an assert() to be triggered if configASSERT() is
defined, then stop here so application writers can catch the error. */
configASSERT( uxCriticalNesting == ~0UL );
portDISABLE_INTERRUPTS();
for( ;; );
}
/*-----------------------------------------------------------*/
__asm void vPortSVCHandler( void )
{
PRESERVE8
/* Get the location of the current TCB. */
ldr r3, =pxCurrentTCB
ldr r1, [r3]
ldr r0, [r1]
/* Pop the core registers. */
ldmia r0!, {r4-r11, r14}
msr psp, r0
isb
mov r0, #0
msr basepri, r0
bx r14
}
/*-----------------------------------------------------------*/
__asm void prvStartFirstTask( void )
{
PRESERVE8
/* Use the NVIC offset register to locate the stack. */
ldr r0, =0xE000ED08
ldr r0, [r0]
ldr r0, [r0]
/* Set the msp back to the start of the stack. */
msr msp, r0
/* Globally enable interrupts. */
cpsie i
cpsie f
dsb
isb
/* Call SVC to start the first task. */
svc 0
nop
nop
}
/*-----------------------------------------------------------*/
__asm void prvEnableVFP( void )
{
PRESERVE8
/* The FPU enable bits are in the CPACR. */
ldr.w r0, =0xE000ED88
ldr r1, [r0]
/* Enable CP10 and CP11 coprocessors, then save back. */
orr r1, r1, #( 0xf << 20 )
str r1, [r0]
bx r14
nop
}
/*-----------------------------------------------------------*/
/*
* See header file for description.
*/
BaseType_t xPortStartScheduler( void )
{
#if( configASSERT_DEFINED == 1 )
{
volatile uint32_t ulOriginalPriority;
volatile uint8_t * const pucFirstUserPriorityRegister = ( uint8_t * ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
volatile uint8_t ucMaxPriorityValue;
/* Determine the maximum priority from which ISR safe FreeRTOS API
functions can be called. ISR safe functions are those that end in
"FromISR". FreeRTOS maintains separate thread and ISR API functions to
ensure interrupt entry is as fast and simple as possible.
Save the interrupt priority value that is about to be clobbered. */
ulOriginalPriority = *pucFirstUserPriorityRegister;
/* Determine the number of priority bits available. First write to all
possible bits. */
*pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
/* Read the value back to see how many bits stuck. */
ucMaxPriorityValue = *pucFirstUserPriorityRegister;
/* The kernel interrupt priority should be set to the lowest
priority. */
configASSERT( ucMaxPriorityValue == ( configKERNEL_INTERRUPT_PRIORITY & ucMaxPriorityValue ) );
/* Use the same mask on the maximum system call priority. */
ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
/* Calculate the maximum acceptable priority group value for the number
of bits read back. */
ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS;
while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
{
ulMaxPRIGROUPValue--;
ucMaxPriorityValue <<= ( uint8_t ) 0x01;
}
/* Shift the priority group value back to its position within the AIRCR
register. */
ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
/* Restore the clobbered interrupt priority register to its original
value. */
*pucFirstUserPriorityRegister = ulOriginalPriority;
}
#endif /* conifgASSERT_DEFINED */
/* Make PendSV and SysTick the lowest priority interrupts. */
portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI;
portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI;
/* Start the timer that generates the tick ISR. Interrupts are disabled
here already. */
vPortSetupTimerInterrupt();
/* Initialise the critical nesting count ready for the first task. */
uxCriticalNesting = 0;
/* Ensure the VFP is enabled - it should be anyway. */
prvEnableVFP();
/* Lazy save always. */
*( portFPCCR ) |= portASPEN_AND_LSPEN_BITS;
/* Start the first task. */
prvStartFirstTask();
/* Should not get here! */
return 0;
}
/*-----------------------------------------------------------*/
void vPortEndScheduler( void )
{
/* Not implemented in ports where there is nothing to return to.
Artificially force an assert. */
configASSERT( uxCriticalNesting == 1000UL );
}
/*-----------------------------------------------------------*/
void vPortEnterCritical( void )
{
portDISABLE_INTERRUPTS();
uxCriticalNesting++;
/* This is not the interrupt safe version of the enter critical function so
assert() if it is being called from an interrupt context. Only API
functions that end in "FromISR" can be used in an interrupt. Only assert if
the critical nesting count is 1 to protect against recursive calls if the
assert function also uses a critical section. */
if( uxCriticalNesting == 1 )
{
configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
}
}
/*-----------------------------------------------------------*/
void vPortExitCritical( void )
{
configASSERT( uxCriticalNesting );
uxCriticalNesting--;
if( uxCriticalNesting == 0 )
{
portENABLE_INTERRUPTS();
}
}
/*-----------------------------------------------------------*/
__asm void xPortPendSVHandler( void )
{
extern uxCriticalNesting;
extern pxCurrentTCB;
extern vTaskSwitchContext;
PRESERVE8
mrs r0, psp
isb
/* Get the location of the current TCB. */
ldr r3, =pxCurrentTCB
ldr r2, [r3]
/* Is the task using the FPU context? If so, push high vfp registers. */
tst r14, #0x10
it eq
vstmdbeq r0!, {s16-s31}
/* Save the core registers. */
stmdb r0!, {r4-r11, r14}
/* Save the new top of stack into the first member of the TCB. */
str r0, [r2]
stmdb sp!, {r3}
mov r0, #configMAX_SYSCALL_INTERRUPT_PRIORITY
cpsid i
msr basepri, r0
dsb
isb
cpsie i
bl vTaskSwitchContext
mov r0, #0
msr basepri, r0
ldmia sp!, {r3}
/* The first item in pxCurrentTCB is the task top of stack. */
ldr r1, [r3]
ldr r0, [r1]
/* Pop the core registers. */
ldmia r0!, {r4-r11, r14}
/* Is the task using the FPU context? If so, pop the high vfp registers
too. */
tst r14, #0x10
it eq
vldmiaeq r0!, {s16-s31}
msr psp, r0
isb
#ifdef WORKAROUND_PMU_CM001 /* XMC4000 specific errata */
#if WORKAROUND_PMU_CM001 == 1
push { r14 }
pop { pc }
nop
#endif
#endif
bx r14
}
/*-----------------------------------------------------------*/
void xPortSysTickHandler( void )
{
/* The SysTick runs at the lowest interrupt priority, so when this interrupt
executes all interrupts must be unmasked. There is therefore no need to
save and then restore the interrupt mask value as its value is already
known. */
( void ) portSET_INTERRUPT_MASK_FROM_ISR();
{
/* Increment the RTOS tick. */
if( xTaskIncrementTick() != pdFALSE )
{
/* A context switch is required. Context switching is performed in
the PendSV interrupt. Pend the PendSV interrupt. */
portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
}
}
portCLEAR_INTERRUPT_MASK_FROM_ISR( 0 );
}
/*-----------------------------------------------------------*/
#if configUSE_TICKLESS_IDLE == 1
__weak void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
{
uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickCTRL;
TickType_t xModifiableIdleTime;
/* Make sure the SysTick reload value does not overflow the counter. */
if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
{
xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
}
/* Stop the SysTick momentarily. The time the SysTick is stopped for
is accounted for as best it can be, but using the tickless mode will
inevitably result in some tiny drift of the time maintained by the
kernel with respect to calendar time. */
portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;
/* Calculate the reload value required to wait xExpectedIdleTime
tick periods. -1 is used because this code will execute part way
through one of the tick periods. */
ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
if( ulReloadValue > ulStoppedTimerCompensation )
{
ulReloadValue -= ulStoppedTimerCompensation;
}
/* Enter a critical section but don't use the taskENTER_CRITICAL()
method as that will mask interrupts that should exit sleep mode. */
__disable_irq();
/* If a context switch is pending or a task is waiting for the scheduler
to be unsuspended then abandon the low power entry. */
if( eTaskConfirmSleepModeStatus() == eAbortSleep )
{
/* Restart from whatever is left in the count register to complete
this tick period. */
portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;
/* Restart SysTick. */
portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
/* Reset the reload register to the value required for normal tick
periods. */
portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
/* Re-enable interrupts - see comments above __disable_irq() call
above. */
__enable_irq();
}
else
{
/* Set the new reload value. */
portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
/* Clear the SysTick count flag and set the count value back to
zero. */
portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
/* Restart SysTick. */
portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
/* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
set its parameter to 0 to indicate that its implementation contains
its own wait for interrupt or wait for event instruction, and so wfi
should not be executed again. However, the original expected idle
time variable must remain unmodified, so a copy is taken. */
xModifiableIdleTime = xExpectedIdleTime;
configPRE_SLEEP_PROCESSING( &xModifiableIdleTime );
if( xModifiableIdleTime > 0 )
{
__dsb( portSY_FULL_READ_WRITE );
__wfi();
__isb( portSY_FULL_READ_WRITE );
}
configPOST_SLEEP_PROCESSING( &xExpectedIdleTime );
/* Stop SysTick. Again, the time the SysTick is stopped for is
accounted for as best it can be, but using the tickless mode will
inevitably result in some tiny drift of the time maintained by the
kernel with respect to calendar time. */
ulSysTickCTRL = portNVIC_SYSTICK_CTRL_REG;
portNVIC_SYSTICK_CTRL_REG = ( ulSysTickCTRL & ~portNVIC_SYSTICK_ENABLE_BIT );
/* Re-enable interrupts - see comments above __disable_irq() call
above. */
__enable_irq();
if( ( ulSysTickCTRL & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
{
uint32_t ulCalculatedLoadValue;
/* The tick interrupt has already executed, and the SysTick
count reloaded with ulReloadValue. Reset the
portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick
period. */
ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
/* Don't allow a tiny value, or values that have somehow
underflowed because the post sleep hook did something
that took too long. */
if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
{
ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
}
portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
/* The tick interrupt handler will already have pended the tick
processing in the kernel. As the pending tick will be
processed as soon as this function exits, the tick value
maintained by the tick is stepped forward by one less than the
time spent waiting. */
ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
}
else
{
/* Something other than the tick interrupt ended the sleep.
Work out how long the sleep lasted rounded to complete tick
periods (not the ulReload value which accounted for part
ticks). */
ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;
/* How many complete tick periods passed while the processor
was waiting? */
ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
/* The reload value is set to whatever fraction of a single tick
period remains. */
portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1 ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
}
/* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG
again, then set portNVIC_SYSTICK_LOAD_REG back to its standard
value. The critical section is used to ensure the tick interrupt
can only execute once in the case that the reload register is near
zero. */
portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
portENTER_CRITICAL();
{
portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
vTaskStepTick( ulCompleteTickPeriods );
portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
}
portEXIT_CRITICAL();
}
}
#endif /* #if configUSE_TICKLESS_IDLE */
/*-----------------------------------------------------------*/
/*
* Setup the SysTick timer to generate the tick interrupts at the required
* frequency.
*/
#if configOVERRIDE_DEFAULT_TICK_CONFIGURATION == 0
void vPortSetupTimerInterrupt( void )
{
/* Calculate the constants required to configure the tick interrupt. */
#if configUSE_TICKLESS_IDLE == 1
{
ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
}
#endif /* configUSE_TICKLESS_IDLE */
/* Configure SysTick to interrupt at the requested rate. */
portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
}
#endif /* configOVERRIDE_DEFAULT_TICK_CONFIGURATION */
/*-----------------------------------------------------------*/
__asm uint32_t vPortGetIPSR( void )
{
PRESERVE8
mrs r0, ipsr
bx r14
}
/*-----------------------------------------------------------*/
#if( configASSERT_DEFINED == 1 )
void vPortValidateInterruptPriority( void )
{
uint32_t ulCurrentInterrupt;
uint8_t ucCurrentPriority;
/* Obtain the number of the currently executing interrupt. */
ulCurrentInterrupt = vPortGetIPSR();
/* Is the interrupt number a user defined interrupt? */
if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
{
/* Look up the interrupt's priority. */
ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
/* The following assertion will fail if a service routine (ISR) for
an interrupt that has been assigned a priority above
configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
function. ISR safe FreeRTOS API functions must *only* be called
from interrupts that have been assigned a priority at or below
configMAX_SYSCALL_INTERRUPT_PRIORITY.
Numerically low interrupt priority numbers represent logically high
interrupt priorities, therefore the priority of the interrupt must
be set to a value equal to or numerically *higher* than
configMAX_SYSCALL_INTERRUPT_PRIORITY.
Interrupts that use the FreeRTOS API must not be left at their
default priority of zero as that is the highest possible priority,
which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
and therefore also guaranteed to be invalid.
FreeRTOS maintains separate thread and ISR API functions to ensure
interrupt entry is as fast and simple as possible.
The following links provide detailed information:
http://www.freertos.org/RTOS-Cortex-M3-M4.html
http://www.freertos.org/FAQHelp.html */
configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
}
/* Priority grouping: The interrupt controller (NVIC) allows the bits
that define each interrupt's priority to be split between bits that
define the interrupt's pre-emption priority bits and bits that define
the interrupt's sub-priority. For simplicity all bits must be defined
to be pre-emption priority bits. The following assertion will fail if
this is not the case (if some bits represent a sub-priority).
If the application only uses CMSIS libraries for interrupt
configuration then the correct setting can be achieved on all Cortex-M
devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
scheduler. Note however that some vendor specific peripheral libraries
assume a non-zero priority group setting, in which cases using a value
of zero will result in unpredicable behaviour. */
configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
}
#endif /* configASSERT_DEFINED */
|
{
"pile_set_name": "Github"
}
|
SUBROUTINE OPTPX1 (*,STOR,NOGO,NEN,LOC1)
C
C PROCESS PID DATA ON PLIMIT CARD
C
INTEGER STOR(15),SYSBUF,OUTTAP,YCOR,THRU,NAM(2),X(7),IY(1)
CHARACTER UFM*23
COMMON /XMSSG / UFM
COMMON /BLANK / SKP1(5),YCOR
CZZ COMMON /ZZOPT1/ CORE(1)
COMMON /ZZZZZZ/ CORE(1)
COMMON /SYSTEM/ SYSBUF,OUTTAP
EQUIVALENCE (CORE(1),X(1)),(X(7),IY(1))
DATA THRU / 4HTHRU /
C
NAM(1) = STOR(1)
NAM(2) = STOR(2)
IF (STOR(6) .EQ. THRU) GO TO 100
C
C USER SPECIFIED BY EXPLICIT ID-S
C
CALL SORT (0,0,1,1,STOR(5),5)
C
C CREATE PSEUDO THRU RANGE
C LOCATE FIRST NONZERO
C
DO 10 L = 5,9
IF (STOR(L) .NE. 0) GO TO 30
10 CONTINUE
CALL PAGE2 (-2)
WRITE (OUTTAP,20) UFM,NAM
20 FORMAT (A23,' 2293, NO PID ENTRIES ON PLIMIT CARD (',2A4,2H).)
NOGO = NOGO + 1
GO TO 110
C
C LOOP ON ENTRIES
C
30 CONTINUE
I1 = STOR(L)
I3 = 1
35 I2 = STOR(L+1)
IF (L-9) 40,60,130
40 IF (I2-I1-I3) 80,50,60
C
C THRU CAN BE EXPANDED
C
50 L = L + 1
I3 = I3 + 1
GO TO 35
C
C PUT OUT I1,I2
C
60 STOR(1) = I1
STOR(2) = STOR(L)
IF (LOC1+3+NEN .GT. YCOR) GO TO 120
CALL BISHEL (*80,STOR,NEN,4,IY(LOC1))
70 L = L + 1
IF (L-9) 30,30,110
C
C DUPLICATE ENTRIES FOUND
C
80 CALL PAGE2 (-2)
WRITE (OUTTAP,90) UFM,I1,I2,NAM
90 FORMAT (A23,' 2294, DUPLICATE',I8,' THRU',I8,' RANGE FOR ELEMENT',
1 1X,2A4,' REJECTED PLIMIT. SCAN CONTINUED.')
NOGO = NOGO + 1
GO TO 70
C
C USER SPECIFIED BY USING THRU
C
100 L = 8
STOR(9) = STOR(8)
STOR(8) = STOR(5)
GO TO 30
C
C THIS PLIMIT FINISHED
C
110 CONTINUE
RETURN
C
C INSUFFICIENT CORE
C
120 CONTINUE
STOR(1) = NAM(1)
STOR(2) = NAM(2)
RETURN 1
C
130 CALL MESAGE (-7,0,NAM)
GO TO 120
END
|
{
"pile_set_name": "Github"
}
|
Copyright (c) 2005-2013 Joergen Ibsen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|
{
"pile_set_name": "Github"
}
|
@echo off
cd ..
npm start
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2014, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef __NOUVEAU_PLATFORM_H__
#define __NOUVEAU_PLATFORM_H__
#include "nouveau_drm.h"
extern struct platform_driver nouveau_platform_driver;
#endif
|
{
"pile_set_name": "Github"
}
|
/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* -------------------------------------------------------------------------- *
* Lepton *
* -------------------------------------------------------------------------- *
* This is part of the Lepton expression parser originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2013-2016 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *
* THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE *
* USE OR OTHER DEALINGS IN THE SOFTWARE. *
* -------------------------------------------------------------------------- *
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* -------------------------------------------------------------------------- *
* lepton *
* -------------------------------------------------------------------------- *
* This is part of the lepton expression parser originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009-2015 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *
* THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE *
* USE OR OTHER DEALINGS IN THE SOFTWARE. *
* -------------------------------------------------------------------------- */
#include "ExpressionTreeNode.h"
#include "Exception.h"
#include "Operation.h"
namespace PLMD {
using namespace lepton;
using namespace std;
ExpressionTreeNode::ExpressionTreeNode(Operation* operation, const vector<ExpressionTreeNode>& children) : operation(operation), children(children) {
if (operation->getNumArguments() != children.size())
throw Exception("wrong number of arguments to function: "+operation->getName());
}
ExpressionTreeNode::ExpressionTreeNode(Operation* operation, const ExpressionTreeNode& child1, const ExpressionTreeNode& child2) : operation(operation) {
children.push_back(child1);
children.push_back(child2);
if (operation->getNumArguments() != children.size())
throw Exception("wrong number of arguments to function: "+operation->getName());
}
ExpressionTreeNode::ExpressionTreeNode(Operation* operation, const ExpressionTreeNode& child) : operation(operation) {
children.push_back(child);
if (operation->getNumArguments() != children.size())
throw Exception("wrong number of arguments to function: "+operation->getName());
}
ExpressionTreeNode::ExpressionTreeNode(Operation* operation) : operation(operation) {
if (operation->getNumArguments() != children.size())
throw Exception("wrong number of arguments to function: "+operation->getName());
}
ExpressionTreeNode::ExpressionTreeNode(const ExpressionTreeNode& node) : operation(node.operation == NULL ? NULL : node.operation->clone()), children(node.getChildren()) {
}
ExpressionTreeNode::ExpressionTreeNode() : operation(NULL) {
}
ExpressionTreeNode::~ExpressionTreeNode() {
if (operation != NULL)
delete operation;
}
bool ExpressionTreeNode::operator!=(const ExpressionTreeNode& node) const {
if (node.getOperation() != getOperation())
return true;
if (getOperation().isSymmetric() && getChildren().size() == 2) {
if (getChildren()[0] == node.getChildren()[0] && getChildren()[1] == node.getChildren()[1])
return false;
if (getChildren()[0] == node.getChildren()[1] && getChildren()[1] == node.getChildren()[0])
return false;
return true;
}
for (int i = 0; i < (int) getChildren().size(); i++)
if (getChildren()[i] != node.getChildren()[i])
return true;
return false;
}
bool ExpressionTreeNode::operator==(const ExpressionTreeNode& node) const {
return !(*this != node);
}
ExpressionTreeNode& ExpressionTreeNode::operator=(const ExpressionTreeNode& node) {
if (operation != NULL)
delete operation;
operation = node.getOperation().clone();
children = node.getChildren();
return *this;
}
const Operation& ExpressionTreeNode::getOperation() const {
return *operation;
}
const vector<ExpressionTreeNode>& ExpressionTreeNode::getChildren() const {
return children;
}
}
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Facebook.
*
* As with any software that integrates with the Facebook platform, your use of
* this software is subject to the Facebook Developer Principles and Policies
* [http://developers.facebook.com/policy/]. This copyright notice shall be
* included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Facebook.Unity.Gameroom
{
internal interface IGameroomFacebookResultHandler : IFacebookResultHandler
{
}
}
|
{
"pile_set_name": "Github"
}
|
/** @file
Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available under
the terms and conditions of the BSD License that accompanies this distribution.
The full text of the license may be found at
http://opensource.org/licenses/bsd-license.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)utime.h 8.1 (Berkeley) 6/2/93
NetBSD: utime.h,v 1.8 2005/02/03 04:39:32 perry Exp
*/
#ifndef _UTIME_H_
#define _UTIME_H_
#include <sys/cdefs.h>
#include <machine/ansi.h>
#include <sys/time.h>
#if defined(_BSD_TIME_T_) && defined(_EFI_TIME_T)
typedef _EFI_TIME_T time_t;
#undef _BSD_TIME_T_
#undef _EFI_TIME_T
#endif
struct utimbuf {
time_t actime; /* Access time */
time_t modtime; /* Modification time */
};
__BEGIN_DECLS
int utime (const char *path, const struct utimbuf *times);
int utimes (const char *path, const struct timeval *times);
__END_DECLS
#endif /* !_UTIME_H_ */
|
{
"pile_set_name": "Github"
}
|
/*************************************************************
* Copyright (c) 2006 Shotaro Tsuji
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*************************************************************/
/* Please send bug reports to
Shotaro Tsuji
4-1010,
Sakasedai 1-chome,
Takaraduka-si,
Hyogo-ken,
665-0024
Japan
negi4d41@yahoo.co.jp
*/
#include "stdio_p.h"
void clearerr(FILE *stream)
{
stream->_flags &= ~(__SEOF|__SERR);
}
|
{
"pile_set_name": "Github"
}
|
for those who associate italian cinema with fellini and " high art , " the son's room is an inventive , subtle alternative .
written by , directed , and starring nanni moretti , it takes us through the slow , complicated path of bereavement .
slow is the best description for the film at first .
it takes its time in establishing the habits of what appears to be a normal , happy family .
father and mother both work but still find the time to support their son and daughter through homework and after school activities .
they laugh , spend free time together , and reprimand the kids for innocent wrongs with a sigh and soft pat on the shoulder .
you get the feeling there is open communication and unconditional love amongst the foursome .
but suddenly , the son is found to be dead after a diving accident .
the family dynamics begin an unpredictable descent that gives the narrative strength when you least expect it , but can also be trying on the attention span .
though the film drags and even repeats itself , this can be somewhat excused as influenced by the process of grieving .
though nanni moretti wore several hats for this production , it doesn't come across as a vanity piece .
one might wish he hadn't picked the profession of analyst for the father , giovanni ( which he stars as ) , if only because this makes his character's reactions so predictable .
what saves it is a well written script , with spare dialogue and an eclectic variety of human interaction .
the potency of the film lies in the recreation of the tiny details of everyday life that alter due to the death of a close relative , or that remind a depressed person of loss .
you start to take notice of the cracked dishes , ignored when familial bliss was in full swing .
you remember bonding during the routine jogs around the block , and not necessarily huge events like graduation .
even better are the role reversals that take place within the household .
while giovanni and paola ( laura morante ) do check up on their daughter irene ( jasmine trinca ) , there is a sense of being on autopilot .
not only does irene begin to take care of her own needs more , she'll make her parents breakfast in an attempt to crack their new shells to life around them .
these scenes provide interesting portrayals of various coping mechanisms , frequently crossing a boundary as to how much you can help yourself versus others during drastic , unexpected change .
respectfully , gender issues never enter the picture .
self-propelled isolation is universal in terms of dealing , so moretti intelligently uses this tool to separate the family .
though giovanni does stop paolo from discussing andrea at a party with friends , there is never a sense that he or she is more stoic , or more correct in the search to restore a sense of a balance to their lives .
most films that broach the topic of death utilize annoying melodrama , speeches , and conciliatory issues to get the waterworks flowing .
in contrast , the son's room captures a more realistic depiction of the effects of death on a family by graciously flowing among the five stages of mourning ( denial , depression , anger , bargaining , acceptance ) through each of its main characters .
it's not the most engaging 100 minutes , but it is certainly easy to relate to .
|
{
"pile_set_name": "Github"
}
|
Human rights activists and the computer industry joined in a rare show of cooperation on Thursday, urging more effective policing of pornography and violence in the anarchic "virtual wild west" of the Internet.
Stories proliferate about pornography, sexual violence
against women and children, bomb-making recipes, incitement to racial hatred and do-it-yourself fraud schemes that are available at various computer Web sites.
"We acknowledge the problems, we're not abdicating responsibility," said Janet Henderson, lawyer and rights strategy manager for Internet services at British Telecommunications.
"We do have the well-being of customers and ultimately their fundamental freedoms at heart," she told the first European conference on combating violence and pornography in cyberspace.
Lawyers have been studying how to police what appears to be a regulatory vacuum without national boundaries -- while trying to distinguish between what is illegal and what is, more subjectively, harmful.
BT, which launched its Internet access service last March, has adopted what it calls a "taste and decency" policy. Any illegal material found through its access to the computer network is reported to the Internet Watch Foundation, which was created last October.
The foundation, which will pass on information about potentially illegal material to the police, also wants to encourage legal material to be classified, allowing users to block access to certain subjects with filtering software.
Henderson said the Internet allowed anonymous worldwide distribution of vast amounts of extremely violent material and child pornography. But access providers could not be the "moral guardians of the nation".
"Slow but sure is the approach we are taking," she said.
Speakers agreed that without knowing the names of "obscene" websites, even spending hours wandering through cyberspace was unlikely to reveal anything more perturbing than walking into a newsagents. Only with "a great level of intent and technical expertise" was it possible to find obscene material, they said.
But German human rights campaigner Monika Gerstendorfer noted that the Internet made it easier for groups, such as extreme political organisations, to communicate and gather forces worldwide.
German Chancellor Helmut Kohl's cabinet last year approved a bill that will ban websites spreading Nazi propaganda, distributing hardcore pornography to minors and conducting fraudulent business.
The German division of the world's second largest online service, CompuServe GmbH, has said it would consider moving its operations to a neighbouring country if German laws forced Internet companies to control porn on their networks.
|
{
"pile_set_name": "Github"
}
|
/* Part of SWI-Prolog
Author: Jan Wielemaker
E-mail: J.Wielemaker@vu.nl
WWW: http://www.swi-prolog.org
Copyright (c) 1999-2016, University of Amsterdam
VU University Amsterdam
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This file defines a console for porting (unix) stream-based applications
to MS-Windows. It has been developed for SWI-Prolog. The main source is
part of SWI-Prolog.
The SWI-Prolog source is at http://www.swi-prolog.org
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thread design:
<written as a mail to Lutz Wohlrab>
There are two threads. The Prolog engine runs in the main thread. The
other thread deals with the window. Basically, it processes events and
if anything is typed it puts it into a queue.
The main thread at some stage forks the display thread, running
window_loop(). This thread initialises the input and then sends
WM_RLC_READY to the main thread to indicate it is ready to accept data.
If data is to be written, Prolog calls rlc_write(), which posts the
WM_RLC_WRITE to the display thread, waiting on the termination. If data
is to be read, rlc_read() posts a WM_RLC_FLUSH, and then waits while
dispatching events, for the display-thread to fill the buffer and send
WM_RLC_INPUT (which is just sent to make GetMessage() in rlc_read()
return).
Towards an MT version on Windows
--------------------------------
If we want to move towards a multi-threaded version for MS-Windows, the
console code needs to be changed significantly, as we need to be able to
create multiple consoles to support thread_attach_console/0.
The most logical solution seems to be to reverse the thread-structure,
Prolog starting and running in the main-thread and creating a console
creates a new thread for this console. There are two ways to keep track
of the console to use. Cleanest might be to add an argument denoting the
allocated console and alternatively we could use thread-local data. We
can also combine the two: add an additional argument, but allow passing
NULL to use the default console for this thread.
Menus
-----
The current console provides a menu that can be extended from Prolog.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#ifdef O_DEBUG_HEAP
static void initHeapDebug(void);
#include <crtdbg.h>
#else
#define initHeapDebug()
#endif
#include <windows.h>
#include <tchar.h>
#ifndef WM_MOUSEWHEEL /* sometimes not defined */
#define WM_MOUSEWHEEL 0x020A
#endif
#ifndef WM_UNICHAR
#define WM_UNICHAR 0x109
#define UNICODE_NOCHAR 0xFFFF
#endif
#ifdef _MSC_VER
#pragma warning(disable : 4996) /* deprecate open() etc */
#endif
#include <stdlib.h>
#include <io.h>
#include <string.h>
#include <malloc.h>
#define _MAKE_DLL 1
#undef _export
#include "console.h"
#include "menu.h"
#include "common.h"
#include <signal.h>
#include <ctype.h>
#include <stdio.h>
#ifndef isletter
#define isletter(c) (_istalpha(c) || (c) == '_')
#endif
#ifndef MAXPATHLEN
#define MAXPATHLEN 256
#endif
#ifndef CHAR_MAX
#define CHAR_MAX 256
#endif
#define MAXLINE 1024 /* max chars per line */
#define CMD_INITIAL 0
#define CMD_ESC 1
#define CMD_ANSI 2
#define GWL_DATA 0 /* offset for client data */
#define CHG_RESET 0 /* unchenged */
#define CHG_CHANGED 1 /* changed, but no clear */
#define CHG_CLEAR 2 /* clear */
#define CHG_CARET 4 /* caret has moved */
#define SEL_CHAR 0 /* character-unit selection */
#define SEL_WORD 1 /* word-unit selection */
#define SEL_LINE 2 /* line-unit selection */
#ifndef EOS
#define EOS 0
#endif
#define ESC 27 /* the escape character */
#define WM_RLC_INPUT WM_USER+10 /* Just somewhere ... */
#define WM_RLC_WRITE WM_USER+11 /* write data */
#define WM_RLC_FLUSH WM_USER+12 /* flush buffered data */
#define WM_RLC_READY WM_USER+13 /* Window thread is ready */
#define WM_RLC_CLOSEWIN WM_USER+14 /* Close the window */
/*#define WM_RLC_MENU WM_USER+15 Insert a menu (defined in menu.h) */
#define IMODE_RAW 1 /* char-by-char */
#define IMODE_COOKED 2 /* line-by-line */
#define NextLine(b, i) ((i) < (b)->height-1 ? (i)+1 : 0)
#define PrevLine(b, i) ((i) > 0 ? (i)-1 : (b)->height-1)
#define Bounds(v, mn, mx) ((v) < (mn) ? (mn) : (v) > (mx) ? (mx) : (v))
#define Control(x) ((x) - '@')
#define streq(s, q) (_tcscmp((s), (q)) == 0)
#include "console_i.h" /* internal package stuff */
#define OPT_SIZE 0x01
#define OPT_POSITION 0x02
/*******************************
* DATA *
*******************************/
RlcData _rlc_stdio = NULL; /* the main buffer */
static int _rlc_show; /* initial show */
static char _rlc_word_chars[CHAR_MAX]; /* word-characters (selection) */
static const TCHAR * _rlc_program; /* name of the program */
static HANDLE _rlc_hinstance; /* Global instance */
static HICON _rlc_hicon; /* Global icon */
/*******************************
* FUNCTIONS *
*******************************/
static LRESULT WINAPI rlc_wnd_proc(HWND win, UINT msg, WPARAM wP, LPARAM lP);
static void rcl_setup_ansi_colors(RlcData b);
static void rlc_place_caret(RlcData b);
static void rlc_resize_pixel_units(RlcData b, int w, int h);
static RlcData rlc_make_buffer(int w, int h);
static int rlc_count_lines(RlcData b, int from, int to);
static void rlc_add_line(RlcData b);
static void rlc_open_line(RlcData b);
static void rlc_update_scrollbar(RlcData b);
static void rlc_paste(RlcData b);
static void rlc_init_text_dimensions(RlcData b, HFONT f);
static void rlc_save_font_options(HFONT f, rlc_console_attr *attr);
static void rlc_get_options(rlc_console_attr *attr);
static HKEY rlc_option_key(rlc_console_attr *attr, int create);
static void rlc_progbase(TCHAR *path, TCHAR *base);
static int rlc_add_queue(RlcData b, RlcQueue q, int chr);
static int rlc_add_lines(RlcData b, int here, int add);
static void rlc_start_selection(RlcData b, int x, int y);
static void rlc_extend_selection(RlcData b, int x, int y);
static void rlc_word_selection(RlcData b, int x, int y);
static int rlc_has_selection(RlcData b);
static void rlc_set_selection(RlcData b, int sl, int sc, int el, int ec);
static void rlc_copy(RlcData b);
static void rlc_destroy(RlcData b);
static void rlc_request_redraw(RlcData b);
static void rlc_redraw(RlcData b);
static int rlc_breakargs(TCHAR *line, TCHAR **argv);
static void rlc_resize(RlcData b, int w, int h);
static void rlc_adjust_line(RlcData b, int line);
static int text_width(RlcData b, HDC hdc, const text_char *text, int len);
static int tchar_width(RlcData b, HDC hdc, const TCHAR *text, int len);
static void rlc_queryfont(RlcData b);
static void rlc_do_write(RlcData b, TCHAR *buf, int count);
static void rlc_reinit_line(RlcData b, int line);
static void rlc_free_line(RlcData b, int line);
static int rlc_between(RlcData b, int f, int t, int v);
static void free_user_data(RlcData b);
static RlcQueue rlc_make_queue(int size);
static int rlc_from_queue(RlcQueue q);
static int rlc_is_empty_queue(RlcQueue q);
extern int main();
static RlcUpdateHook _rlc_update_hook;
static RlcTimerHook _rlc_timer_hook;
static RlcRenderHook _rlc_render_hook;
static RlcRenderAllHook _rlc_render_all_hook;
static RlcInterruptHook _rlc_interrupt_hook;
static RlcResizeHook _rlc_resize_hook;
static RlcMenuHook _rlc_menu_hook;
static RlcMessageHook _rlc_message_hook;
static int _rlc_copy_output_to_debug_output=0; /* != 0: copy to debugger */
static int emulate_three_buttons;
static HWND emu_hwnd; /* Emulating for this window */
static void _rlc_create_kill_window(RlcData b);
static DWORD WINAPI window_loop(LPVOID arg); /* console window proc */
#ifdef _DEBUG
#include <stdarg.h>
static void Dprintf(const TCHAR *fmt, ...);
static void Dprint_lines(RlcData b, int from, int to);
#define DEBUG(Code) Code
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
It might look a bit weird not to use <assert.h>, but for some reason it
looks as if the application thread continues if the asserting is trapped
using the normal assert()!? Just but a debugger breakpoint on
rlc_assert() and all functions normally.
rlc_check_assertions() is a (very) incomplete check that everything we
expect to be true about the data is indeed the case.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
void
rlc_assert(const TCHAR *msg)
{ MessageBox(NULL, msg, _T("Console assertion failed"), MB_OK|MB_TASKMODAL);
}
void
rlc_check_assertions(RlcData b)
{ int window_last = rlc_add_lines(b, b->window_start, b->window_size-1);
int y;
assert(b->last != b->first || b->first == 0);
assert(b->caret_x >= 0 && b->caret_x < b->width);
/* TBD: debug properly */
/*assert(rlc_between(b, b->window_start, window_last, b->caret_y));*/
for(y=0; y<b->height; y++)
{ TextLine tl = &b->lines[y];
assert(tl->size >= 0 && tl->size <= b->width);
}
}
#else
#define DEBUG(Code) ((void)0)
#define rlc_check_assertions(b)
#endif
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
rlc_long_name(TCHAR *buffer)
Translate a filename, possibly holding 8+3 abbreviated parts into
the `real' filename. I couldn't find a direct call for this. If
you have it, I'd be glad to receive a better implementation.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static void
rlc_long_name(TCHAR *file)
{ TCHAR buf[MAXPATHLEN];
TCHAR *i = file;
TCHAR *o = buf;
TCHAR *ok = buf;
int changed = 0;
while(*i)
{ int dirty = FALSE;
while(*i && *i != '\\')
{ if ( *i == '~' )
dirty++;
*o++ = *i++;
}
if ( dirty )
{ WIN32_FIND_DATA data;
HANDLE h;
*o = '\0';
if ( (h=FindFirstFile(buf, &data)) != INVALID_HANDLE_VALUE )
{ _tcscpy(ok, data.cFileName);
FindClose(h);
o = ok + _tcslen(ok);
changed++;
}
}
if ( *i )
*o++ = *i++;
ok = o;
}
if ( changed )
{ *o = '\0';
_tcscpy(file, buf);
}
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If %PLTERM_CLASS% is in the environment, this value is used as Windows
class identifier for the console window. This allows external programs
to start PLWIN.EXE and find the window it has started in order to embed
it.
In old versions this was fixed to "RlcConsole"
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static TCHAR *
rlc_window_class(HICON icon)
{ static TCHAR winclassname[32];
static WNDCLASS wndClass;
HINSTANCE instance = _rlc_hinstance;
if ( !winclassname[0] )
{ if ( !GetEnvironmentVariable(_T("PLTERM_CLASS"),
winclassname, sizeof(winclassname)) )
_snwprintf(winclassname, sizeof(winclassname)/sizeof(TCHAR),
_T("PlTerm-%d"), (int)(intptr_t)instance);
wndClass.lpszClassName = winclassname;
wndClass.style = CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS;
wndClass.lpfnWndProc = (LPVOID) rlc_wnd_proc;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = sizeof(intptr_t);
wndClass.hInstance = instance;
if ( icon )
wndClass.hIcon = icon;
else
wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndClass.hCursor = LoadCursor(NULL, IDC_IBEAM);
wndClass.hbrBackground = (HBRUSH) NULL;
wndClass.lpszMenuName = NULL;
RegisterClass(&wndClass);
}
return winclassname;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
There are two ways to get the commandline. It is passed to WinMain as
8-bit string. This version does *not* include the command itself. It is
also available through GetCommandLine(), which does include the command
itself and returns LPTSTR (Unicode/ANSI). We assume the latter.
Nevertheless, for backward compatibility as well as easy to extract the
full pathname of the executable, we replace argv[0] with the intptr_t
filename version of the current module, so argv[0] is guaranteed to be a
full path refering to the .exe file.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
int
rlc_main(HANDLE hInstance, HANDLE hPrevInstance,
LPTSTR lpszCmdLine, int nCmdShow,
RlcMain mainfunc, HICON icon)
{ TCHAR * argv[100];
int argc;
TCHAR program[MAXPATHLEN];
TCHAR progbase[100];
RlcData b;
rlc_console_attr attr;
initHeapDebug();
_rlc_hinstance = hInstance;
_rlc_show = nCmdShow;
_rlc_hicon = icon;
GetModuleFileName(hInstance, program, sizeof(program));
rlc_long_name(program);
argc = rlc_breakargs(lpszCmdLine, argv);
argv[0] = program;
rlc_progbase(argv[0], progbase);
memset(&attr, 0, sizeof(attr));
_rlc_program = attr.title = progbase;
_rlc_stdio = b = rlc_create_console(&attr);
if ( mainfunc )
return (*mainfunc)(b, argc, argv);
else
return 0;
}
rlc_console
rlc_create_console(rlc_console_attr *attr)
{ RlcData b;
MSG msg;
const TCHAR *title;
rlc_get_options(attr);
if ( attr->title )
title = attr->title;
else
title = _T("Untitled");
b = rlc_make_buffer(attr->width, attr->savelines);
b->create_attributes = attr;
_tcscpy(b->current_title, title);
if ( attr->key )
{ b->regkey_name = _tcsdup(attr->key);
}
rlc_init_text_dimensions(b, NULL);
_rlc_create_kill_window(b);
DuplicateHandle(GetCurrentProcess(),
GetCurrentThread(),
GetCurrentProcess(),
&b->application_thread,
0,
FALSE,
DUPLICATE_SAME_ACCESS);
b->application_thread_id = GetCurrentThreadId();
b->console_thread = CreateThread(NULL, /* security */
2048, /* stack */
window_loop, b, /* proc+arg */
0, /* flags */
&b->console_thread_id); /* id */
/* wait till the window is created */
GetMessage(&msg, NULL, WM_RLC_READY, WM_RLC_READY);
b->create_attributes = NULL; /* release this data */
return b;
}
static void
rlc_create_window(RlcData b)
{ HWND hwnd;
rlc_console_attr *a = b->create_attributes;
RECT rect;
DWORD style = (WS_OVERLAPPEDWINDOW|WS_VSCROLL);
/* One would assume AdjustWindowRect() uses WS_VSCROLL to add the width of
the scrollbar. I think this isn't true, but maybe there is another reason
for getting 2 characters shorter each invocation ...
*/
rect.left = a->x;
rect.top = a->y;
rect.right = a->x + (a->width+2) * b->cw + GetSystemMetrics(SM_CXVSCROLL);
rect.bottom = a->y + a->height * b->ch;
AdjustWindowRect(&rect, style, TRUE);
hwnd = CreateWindow(rlc_window_class(_rlc_hicon), b->current_title,
style,
a->x, a->y,
rect.right - rect.left,
rect.bottom - rect.top,
NULL, NULL, _rlc_hinstance, NULL);
b->window = hwnd;
SetWindowLongPtr(hwnd, GWL_DATA, (LONG_PTR) b);
SetScrollRange(hwnd, SB_VERT, 0, b->sb_lines, FALSE);
SetScrollPos(hwnd, SB_VERT, b->sb_start, TRUE);
b->queue = rlc_make_queue(256);
b->sb_lines = rlc_count_lines(b, b->first, b->last);
b->sb_start = rlc_count_lines(b, b->first, b->window_start);
rcl_setup_ansi_colors(b);
b->foreground = GetSysColor(COLOR_WINDOWTEXT);
b->background = GetSysColor(COLOR_WINDOW);
b->sel_foreground = GetSysColor(COLOR_HIGHLIGHTTEXT);
b->sel_background = GetSysColor(COLOR_HIGHLIGHT);
if ( GetSystemMetrics(SM_CMOUSEBUTTONS) == 2 )
emulate_three_buttons = 120;
rlc_add_menu_bar(b->window);
ShowWindow(hwnd, _rlc_show);
UpdateWindow(hwnd);
}
int
rlc_iswin32s()
{ if( GetVersion() & 0x80000000 && (GetVersion() & 0xFF) ==3)
return TRUE;
else
return FALSE;
}
static void
rlc_progbase(TCHAR *path, TCHAR *base)
{ TCHAR *s;
TCHAR *e;
if ( !(s=_tcsrchr(path, '\\')) )
s = path; /* takes the filename part */
else
s++;
if ( !(e = _tcschr(s, '.')) )
_tcscpy(base, s);
else
{ _tcsncpy(base, s, e-s);
base[e-s] = '\0';
}
}
/*******************************
* HIDDEN WINDOW *
*******************************/
static LRESULT WINAPI
rlc_kill_wnd_proc(HWND hwnd, UINT message, UINT wParam, LONG lParam)
{ switch(message)
{ case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
static TCHAR *
rlc_kill_window_class()
{ static TCHAR winclassname[32];
static WNDCLASS wndClass;
HINSTANCE instance = _rlc_hinstance;
if ( !winclassname[0] )
{ _snwprintf(winclassname, sizeof(winclassname)/sizeof(TCHAR),
_T("Console-hidden-win%d"), (int)(intptr_t)instance);
wndClass.style = 0;
wndClass.lpfnWndProc = (LPVOID) rlc_kill_wnd_proc;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = instance;
wndClass.hIcon = NULL;
wndClass.hCursor = NULL;
wndClass.hbrBackground = GetStockObject(WHITE_BRUSH);
wndClass.lpszMenuName = NULL;
wndClass.lpszClassName = winclassname;
RegisterClass(&wndClass);
}
return winclassname;
}
static void
_rlc_create_kill_window(RlcData b)
{ b->kill_window = CreateWindow(rlc_kill_window_class(),
_T("Console hidden window"),
0,
0, 0, 32, 32,
NULL, NULL, _rlc_hinstance, NULL);
}
/*******************************
* REGISTRY COMMUNICATION *
*******************************/
#define MAXREGSTRLEN 1024
static void
reg_save_int(HKEY key, const TCHAR *name, int value)
{ DWORD val = value;
if ( RegSetValueEx(key, name, 0,
REG_DWORD_LITTLE_ENDIAN,
(LPBYTE)&val, sizeof(val)) != ERROR_SUCCESS )
DEBUG(MessageBox(NULL, _T("Failed to save int setting"),
_T("Error"), MB_OK));
}
static void
reg_save_str(HKEY key, const TCHAR *name, TCHAR *value)
{ if ( RegSetValueEx(key, name, 0, REG_SZ,
(LPBYTE)value, (DWORD)(_tcslen(value)+1)*sizeof(TCHAR)) != ERROR_SUCCESS )
DEBUG(MessageBox(NULL, _T("Failed to save string setting"), _T("Error"), MB_OK));
}
static void
rlc_save_options(RlcData b)
{ HKEY key;
rlc_console_attr attr;
memset(&attr, 0, sizeof(attr));
attr.key = b->regkey_name;
if ( !(key = rlc_option_key(&attr, TRUE)) )
return;
reg_save_int(key, _T("SaveLines"), b->height);
if ( b->modified_options & OPT_SIZE )
{ reg_save_int(key, _T("Width"), b->width);
reg_save_int(key, _T("Height"), b->window_size);
}
if ( b->modified_options & OPT_POSITION )
{ reg_save_int(key, _T("X"), b->win_x);
reg_save_int(key, _T("Y"), b->win_y);
}
rlc_save_font_options(b->hfont, &attr);
if ( attr.face_name[0] )
{ reg_save_str(key, _T("FaceName"), attr.face_name);
reg_save_int(key, _T("FontFamily"), attr.font_family);
reg_save_int(key, _T("FontSize"), attr.font_size);
reg_save_int(key, _T("FontWeight"), attr.font_weight);
reg_save_int(key, _T("FontCharSet"), attr.font_char_set);
}
RegCloseKey(key);
}
static void
reg_get_int(HKEY key, const TCHAR *name, int mn, int def, int mx, int *value)
{ DWORD type;
BYTE data[8];
DWORD len = sizeof(data);
if ( *value )
return; /* use default */
if ( RegQueryValueEx(key, name, NULL, &type, data, &len) == ERROR_SUCCESS )
{ switch(type)
{ /*case REG_DWORD:*/ /* Same case !? */
case REG_DWORD_LITTLE_ENDIAN:
{ DWORD *valp = (DWORD *)data;
int v = *valp;
if ( mn < mx )
{ if ( v < mn )
v = mn;
else if ( v > mx )
v = mx;
}
*value = v;
}
}
} else
*value = def;
}
static void
reg_get_str(HKEY key, const TCHAR *name, TCHAR *value, int length)
{ DWORD type;
BYTE data[MAXREGSTRLEN*sizeof(TCHAR)];
DWORD len = sizeof(data);
if ( *value )
return; /* use default */
if ( RegQueryValueEx(key, name, NULL, &type, data, &len) == ERROR_SUCCESS )
{ switch(type)
{ case REG_SZ:
{ TCHAR *val = (TCHAR*)data;
_tcsncpy(value, val, length-1);
value[length-1] = '\0';
}
}
}
}
HKEY
reg_open_key(TCHAR **which, int create)
{ HKEY key = HKEY_CURRENT_USER;
DWORD disp;
LONG rval;
for( ; *which; which++)
{ HKEY tmp;
if ( which[1] )
{ if ( RegOpenKeyEx(key, which[0], 0L, KEY_READ, &tmp) == ERROR_SUCCESS )
{ key = tmp;
continue;
}
if ( !create )
return NULL;
}
rval = RegCreateKeyEx(key, which[0], 0, _T(""), 0,
KEY_ALL_ACCESS, NULL, &tmp, &disp);
RegCloseKey(key);
if ( rval == ERROR_SUCCESS )
key = tmp;
else
return NULL;
}
return key;
}
static HKEY
rlc_option_key(rlc_console_attr *attr, int create)
{ TCHAR Prog[256];
TCHAR *address[] = { _T("Software"),
RLC_VENDOR,
Prog,
_T("Console"),
(TCHAR *)attr->key, /* possible secondary key */
NULL
};
const TCHAR *s;
TCHAR *q;
for(s=_rlc_program, q=Prog; *s; s++, q++) /* capitalise the key */
{ *q = (s==_rlc_program ? _totupper(*s) : _totlower(*s));
}
*q = EOS;
return reg_open_key(address, create);
}
static void
rlc_get_options(rlc_console_attr *attr)
{ HKEY key;
if ( !(key = rlc_option_key(attr, FALSE)) )
{ if ( !attr->width ) attr->width = 80;
if ( !attr->height ) attr->height = 24;
if ( !attr->savelines ) attr->savelines = 200;
return;
}
{ int minx, miny, maxx, maxy;
RECT rect;
SystemParametersInfo(SPI_GETWORKAREA, 0, &rect, 0);
minx = rect.top;
miny = rect.left;
maxx = rect.right - 40;
maxy = rect.bottom - 40;
reg_get_int(key, _T("SaveLines"), 200, 200, 100000, &attr->savelines);
reg_get_int(key, _T("Width"), 20, 80, 300, &attr->width);
reg_get_int(key, _T("Height"), 5, 24, 100, &attr->height);
reg_get_int(key, _T("X"), minx, minx, maxx, &attr->x);
reg_get_int(key, _T("Y"), miny, miny, maxy, &attr->y);
}
reg_get_str(key, _T("FaceName"), attr->face_name,
sizeof(attr->face_name)/sizeof(TCHAR));
reg_get_int(key, _T("FontFamily"), 0, 0, 0, &attr->font_family);
reg_get_int(key, _T("FontSize"), 0, 0, 0, &attr->font_size);
reg_get_int(key, _T("FontWeight"), 0, 0, 0, &attr->font_weight);
reg_get_int(key, _T("FontCharSet"), 0, 0, 0, &attr->font_char_set);
RegCloseKey(key);
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Windows-'95 appears to quote names of files because files may hold
spaces. rlc_breakargs() will pass a quoted strings as one argument. If
it can't find the closing quote, it will tread the quote as a normal
character.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static int
rlc_breakargs(TCHAR *line, TCHAR **argv)
{ int argc = 0;
while(*line)
{ int q;
while(*line && _istspace(*line))
line++;
if ( (q = *line) == '"' || q == '\'' ) /* quoted arguments */
{ TCHAR *start = line+1;
TCHAR *end = start;
while( *end && *end != q )
end++;
if ( *end == q )
{ *end = '\0';
argv[argc++] = start;
line = end+1;
continue;
}
}
if ( *line )
{ argv[argc++] = line;
while(*line && !_istspace(*line))
line++;
if ( *line )
*line++ = '\0';
}
}
argv[argc] = NULL; /* add trailing NULL pointer to argv */
return argc;
}
/*******************************
* ANSI COLORS *
*******************************/
/* See http://en.wikipedia.org/wiki/ANSI_escape_code */
static void
rcl_setup_ansi_colors(RlcData b)
{ b->sgr_flags = TF_DEFAULT;
#ifdef ANSI_VGA_COLORS
/* normal versions */
b->ansi_color[0] = RGB( 0, 0, 0); /* black */
b->ansi_color[1] = RGB(170, 0, 0); /* red */
b->ansi_color[2] = RGB(0, 170, 0); /* green */
b->ansi_color[3] = RGB(170, 85, 0); /* yellow */
b->ansi_color[4] = RGB( 0, 0,170); /* blue */
b->ansi_color[5] = RGB(170, 0,170); /* magenta */
b->ansi_color[6] = RGB( 0,170,170); /* cyan */
b->ansi_color[7] = RGB(170,170,170); /* white */
/* bright/light versions */
b->ansi_color[8] = RGB( 85, 85, 85); /* black */
b->ansi_color[9] = RGB(255, 85, 85); /* red */
b->ansi_color[10] = RGB( 85,255, 85); /* green */
b->ansi_color[11] = RGB(255,255, 85); /* yellow */
b->ansi_color[12] = RGB( 85, 85,255); /* blue */
b->ansi_color[13] = RGB(255, 85,255); /* magenta */
b->ansi_color[14] = RGB( 85,255,255); /* cyan */
b->ansi_color[15] = RGB(255,255,255); /* white */
#else /*XTERM*/
/* normal versions */
b->ansi_color[0] = RGB( 0, 0, 0); /* black */
b->ansi_color[1] = RGB(205, 0, 0); /* red */
b->ansi_color[2] = RGB(0, 205, 0); /* green */
b->ansi_color[3] = RGB(205,205, 0); /* yellow */
b->ansi_color[4] = RGB( 0, 0,238); /* blue */
b->ansi_color[5] = RGB(205, 0,205); /* magenta */
b->ansi_color[6] = RGB( 0,205,205); /* cyan */
b->ansi_color[7] = RGB(229,229,229); /* white */
/* bright/light versions */
b->ansi_color[8] = RGB(127,127,127); /* black */
b->ansi_color[9] = RGB(255, 0, 0); /* red */
b->ansi_color[10] = RGB( 0,255, 0); /* green */
b->ansi_color[11] = RGB(255,255, 0); /* yellow */
b->ansi_color[12] = RGB( 92, 92,255); /* blue */
b->ansi_color[13] = RGB(255, 0,255); /* magenta */
b->ansi_color[14] = RGB( 0,255,255); /* cyan */
b->ansi_color[15] = RGB(255,255,255); /* white */
#endif
}
/*******************************
* ATTRIBUTES *
*******************************/
COLORREF
rlc_color(rlc_console con, int which, COLORREF c)
{ HDC hdc;
COLORREF old;
RlcData b = rlc_get_data(con);
hdc = GetDC(NULL);
c = GetNearestColor(hdc, c);
ReleaseDC(NULL, hdc);
switch(which)
{ case RLC_WINDOW:
old = b->background;
b->background = c;
break;
case RLC_TEXT:
old = b->foreground;
b->foreground = c;
break;
case RLC_HIGHLIGHT:
old = b->sel_background;
b->sel_background = c;
break;
case RLC_HIGHLIGHTTEXT:
old = b->sel_foreground;
b->sel_foreground = c;
break;
default:
return (COLORREF)-1;
}
if ( b->window )
InvalidateRect(b->window, NULL, TRUE);
return old;
}
static int
rlc_kill(RlcData b)
{ DWORD_PTR result;
switch(b->closing++)
{ case 0:
b->queue->flags |= RLC_EOF;
PostThreadMessage(b->application_thread_id, WM_RLC_INPUT, 0, 0);
return TRUE;
case 1:
if ( _rlc_interrupt_hook )
{ (*_rlc_interrupt_hook)(b, SIGINT);
return TRUE;
}
default:
if ( !SendMessageTimeout(b->kill_window,
WM_DESTROY,
0, 0,
SMTO_ABORTIFHUNG,
5000,
&result) )
{ if ( b->window )
{ switch( MessageBox(b->window,
_T("Main task is not responding.")
_T("Click \"OK\" to terminate it"),
_T("Error"),
MB_OKCANCEL|MB_ICONEXCLAMATION|MB_APPLMODAL) )
{ case IDCANCEL:
return FALSE;
}
TerminateThread(b->application_thread, 1);
return TRUE;
}
}
}
return FALSE;
}
static void
rlc_interrupt(RlcData b)
{ if ( _rlc_interrupt_hook )
(*_rlc_interrupt_hook)((rlc_console)b, SIGINT);
else
raise(SIGINT);
}
static void
typed_char(RlcData b, int chr)
{ if ( chr == Control('C') && rlc_has_selection(b) )
{ rlc_copy(b);
return;
}
rlc_set_selection(b, 0, 0, 0, 0);
if ( chr == Control('C') )
rlc_interrupt(b);
else if ( chr == Control('V') || chr == Control('Y') )
rlc_paste(b);
else if ( b->queue )
rlc_add_queue(b, b->queue, chr);
}
/*******************************
* WINDOW PROCEDURE *
*******************************/
#undef MAKEPOINTS
static inline POINTS
MAKEPOINTS(LPARAM lParam)
{ union
{ LPARAM p;
POINTS pt;
} u;
u.p = lParam;
return u.pt;
}
static void
rlc_destroy(RlcData b)
{ if ( b && b->window )
{ DestroyWindow(b->window);
b->window = NULL;
b->closing = 3;
}
}
static int
IsDownKey(int code)
{ short mask = GetKeyState(code);
return mask & 0x8000;
}
static LRESULT WINAPI
rlc_wnd_proc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{ RlcData b = (RlcData) GetWindowLongPtr(hwnd, GWL_DATA);
switch(message)
{ case WM_CREATE:
return 0;
case WM_SIZE:
if ( wParam != SIZE_MINIMIZED )
{ rlc_resize_pixel_units(b, LOWORD(lParam), HIWORD(lParam));
b->modified_options |= OPT_SIZE;
}
return 0;
case WM_MOVE:
{ WINDOWPLACEMENT placement;
placement.length = sizeof(placement);
GetWindowPlacement(hwnd, &placement);
if ( placement.showCmd == SW_SHOWNORMAL )
{ b->win_x = placement.rcNormalPosition.left;
b->win_y = placement.rcNormalPosition.top;
b->modified_options |= OPT_POSITION;
}
return 0;
}
case WM_SETFOCUS:
b->has_focus = TRUE;
CreateCaret(hwnd, NULL, b->fixedfont ? b->cw : 3, b->ch-1);
rlc_place_caret(b);
return 0;
case WM_KILLFOCUS:
b->has_focus = FALSE;
b->caret_is_shown = FALSE;
HideCaret(hwnd);
DestroyCaret();
return 0;
case WM_PAINT:
rlc_redraw(b);
return 0;
case WM_COMMAND:
{ UINT item = (UINT) LOWORD(wParam);
const TCHAR *name;
switch( item )
{ case IDM_PASTE:
rlc_paste(b);
return 0;
case IDM_COPY:
rlc_copy(b);
return 0; /* no op: already done */
case IDM_CUT:
break; /* TBD: cut */
case IDM_BREAK:
rlc_interrupt(b);
break;
case IDM_FONT:
rlc_queryfont(b);
return 0;
case IDM_EXIT:
if ( rlc_kill(b) )
return 0;
break;
}
if ( (name = lookupMenuId(item)) )
{ if ( _rlc_menu_hook )
{ (*_rlc_menu_hook)(b, name);
}
return 0;
}
break;
}
{ int chr;
case WM_KEYDOWN: /* up is sent only once */
{ switch((int) wParam)
{ case VK_DELETE: chr = 127; break;
case VK_LEFT: chr = Control('B'); break;
case VK_RIGHT: chr = Control('F'); break;
case VK_UP: chr = Control('P'); break;
case VK_DOWN: chr = Control('N'); break;
case VK_HOME: chr = Control('A'); break;
case VK_END: chr = Control('E'); break;
case VK_CANCEL: rlc_interrupt(b); return 0;
case VK_PRIOR: /* page up */
{ int maxdo = rlc_count_lines(b, b->first, b->window_start);
int pagdo = b->window_size - 1;
b->window_start = rlc_add_lines(b, b->window_start,
-min(maxdo, pagdo));
scrolledbykey:
rlc_update_scrollbar(b);
InvalidateRect(hwnd, NULL, FALSE);
return 0;
}
case VK_NEXT: /* page down */
{ int maxup = rlc_count_lines(b, b->window_start, b->last);
int pagup = b->window_size - 1;
b->window_start = rlc_add_lines(b, b->window_start,
min(maxup, pagup));
goto scrolledbykey;
}
default:
goto break2;
}
if ( chr > 0 )
{ if ( IsDownKey(VK_CONTROL) )
typed_char(b, ESC);
typed_char(b, chr);
return 0;
}
break2:
break;
}
case WM_UNICHAR:
chr = (int)wParam;
typed_char(b, chr);
return 0;
case WM_SYSCHAR: typed_char(b, ESC); /* Play escape-something */
case WM_CHAR: chr = (int)wParam;
typed_char(b, chr);
return 0;
}
/* selection handling */
case WM_MBUTTONDOWN:
middle_down:
return 0;
case WM_MBUTTONUP:
middle_up:
rlc_paste(b);
return 0;
case WM_LBUTTONDOWN:
{ POINTS pt;
if ( emulate_three_buttons )
{ MSG msg;
Sleep(emulate_three_buttons);
if ( PeekMessage(&msg, hwnd,
WM_RBUTTONDOWN, WM_RBUTTONDOWN, PM_REMOVE) )
{ emu_hwnd = hwnd;
goto middle_down;
}
}
pt = MAKEPOINTS(lParam);
rlc_start_selection(b, pt.x, pt.y);
return 0;
}
case WM_LBUTTONUP:
case WM_RBUTTONUP:
if ( emu_hwnd == hwnd )
{ if ( wParam & (MK_RBUTTON|MK_LBUTTON) )
goto middle_up;
else
{ emu_hwnd = 0;
return 0;
}
} else
{ rlc_copy(b);
return 0;
}
case WM_LBUTTONDBLCLK:
{ POINTS pt = MAKEPOINTS(lParam);
rlc_word_selection(b, pt.x, pt.y);
return 0;
}
case WM_RBUTTONDOWN:
{ POINTS pt;
if ( emulate_three_buttons )
{ MSG msg;
Sleep(emulate_three_buttons);
if ( PeekMessage(&msg, hwnd,
WM_LBUTTONDOWN, WM_LBUTTONDOWN, PM_REMOVE) )
{ emu_hwnd = hwnd;
goto middle_down;
}
}
pt = MAKEPOINTS(lParam);
rlc_extend_selection(b, pt.x, pt.y);
return 0;
}
case WM_MOUSEMOVE:
{ POINTS pt = MAKEPOINTS(lParam);
if ( (wParam & (MK_LBUTTON|MK_RBUTTON)) &&
(wParam & (MK_LBUTTON|MK_RBUTTON)) != (MK_LBUTTON|MK_RBUTTON) )
{ rlc_extend_selection(b, pt.x, pt.y);
return 0;
}
break;
}
case WM_MOUSEWHEEL:
{ short angle = (short)HIWORD(wParam);
if ( angle < 0 )
{ if ( b->window_start != b->last )
b->window_start = NextLine(b, b->window_start);
} else
{ if ( b->window_start != b->first )
b->window_start = PrevLine(b, b->window_start);
}
rlc_update_scrollbar(b);
InvalidateRect(hwnd, NULL, FALSE);
return 0;
}
/* scrolling */
case WM_VSCROLL:
{ switch( LOWORD(wParam) )
{ case SB_LINEUP:
if ( b->window_start != b->first )
b->window_start = PrevLine(b, b->window_start);
break;
case SB_LINEDOWN:
if ( b->window_start != b->last )
b->window_start = NextLine(b, b->window_start);
break;
case SB_PAGEUP:
{ int maxdo = rlc_count_lines(b, b->first, b->window_start);
int pagdo = b->window_size - 1;
b->window_start = rlc_add_lines(b, b->window_start,
-min(maxdo, pagdo));
break;
}
case SB_PAGEDOWN:
{ int maxup = rlc_count_lines(b, b->window_start, b->last);
int pagup = b->window_size - 1;
b->window_start = rlc_add_lines(b, b->window_start,
min(maxup, pagup));
break;
}
case SB_THUMBTRACK:
b->window_start = rlc_add_lines(b, b->first, HIWORD(wParam));
break;
}
rlc_update_scrollbar(b);
InvalidateRect(hwnd, NULL, FALSE);
return 0;
}
case WM_TIMER:
if ( _rlc_timer_hook && wParam >= RLC_APPTIMER_ID )
{ (*_rlc_timer_hook)((int) wParam);
return 0;
}
break;
case WM_RENDERALLFORMATS:
if ( _rlc_render_all_hook )
{ (*_rlc_render_all_hook)();
return 0;
}
break;
case WM_RENDERFORMAT:
if ( _rlc_render_hook && (*_rlc_render_hook)(wParam) )
return 0;
break;
case WM_ERASEBKGND:
{ HDC hdc = (HDC) wParam;
RECT rect;
HBRUSH hbrush;
COLORREF rgb = b->background;
hbrush = CreateSolidBrush(rgb);
GetClipBox(hdc, &rect);
FillRect(hdc, &rect, hbrush);
DeleteObject(hbrush);
return 1; /* non-zero: I've erased it */
}
case WM_SYSCOLORCHANGE:
b->foreground = GetSysColor(COLOR_WINDOWTEXT);
b->background = GetSysColor(COLOR_WINDOW);
b->sel_foreground = GetSysColor(COLOR_HIGHLIGHTTEXT);
b->sel_background = GetSysColor(COLOR_HIGHLIGHT);
return 0;
case WM_RLC_WRITE:
{ int count = (int)wParam;
TCHAR *buf = (TCHAR *)lParam;
if ( OQSIZE - b->output_queued > count )
{ _tcsncpy(&b->output_queue[b->output_queued], buf, count);
b->output_queued += count;
} else
{ if ( b->output_queued > 0 )
rlc_flush_output(b);
if ( count <= OQSIZE )
{ _tcsncpy(b->output_queue, buf, count);
b->output_queued = count;
} else
rlc_do_write(b, buf, count);
}
return 0;
}
case WM_RLC_FLUSH:
{ rlc_flush_output(b);
return 0;
}
case WM_RLC_MENU:
{ rlc_menu_action((rlc_console) b, (struct menu_data*)lParam);
return 0;
}
case WM_RLC_CLOSEWIN:
return 0;
case WM_CLOSE:
if ( rlc_kill(b) )
return 0;
break;
case WM_DESTROY:
b->window = NULL;
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
static int
rlc_get_message(MSG *msg, HWND hwnd, UINT low, UINT high)
{ int rc;
again:
if ( (rc=GetMessage(msg, hwnd, low, high)) )
{ if ( _rlc_message_hook &&
(*_rlc_message_hook)(msg->hwnd, msg->message,
msg->wParam, msg->lParam) )
goto again;
}
return rc;
}
static void
rlc_dispatch(RlcData b)
{ MSG msg;
if ( rlc_get_message(&msg, NULL, 0, 0) && msg.message != WM_RLC_CLOSEWIN )
{ /* DEBUG(Dprintf("Thread %x got message 0x%04x\n",
GetCurrentThreadId(), msg.message));
*/
TranslateMessage(&msg);
DispatchMessage(&msg);
rlc_flush_output(b);
return;
} else
{ DEBUG(Dprintf(_T("Thread %x got WM_RLC_CLOSEWIN\n"),
GetCurrentThreadId()));
b->queue->flags |= RLC_EOF;
}
}
void
rlc_yield()
{ MSG msg;
while ( PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) )
{ TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
/*******************************
* CHARACTER TYPES *
*******************************/
static void
rlc_init_word_chars()
{ int i;
for(i=0; i<CHAR_MAX; i++)
_rlc_word_chars[i] = (isalnum(i) || i == '_') ? TRUE : FALSE;
}
void
rlc_word_char(int chr, int isword)
{ if ( chr > 0 && chr < CHAR_MAX )
_rlc_word_chars[chr] = isword;
}
int
rlc_is_word_char(int chr)
{ if ( chr > 0 && chr < CHAR_MAX )
return _rlc_word_chars[chr];
return _istalnum((wint_t)chr); /* only UNICODE version */
}
/*******************************
* SELECTION *
*******************************/
#define SelLT(l1, c1, l2, c2) ((l1) < (l2) || ((l1) == (l2) && (c1) < (c2)))
#define SelEQ(l1, c1, l2, c2) ((l1) == (l2) && (c1) == (c2))
static int
rlc_min(RlcData b, int x, int y)
{ if ( rlc_count_lines(b, b->first, x) < rlc_count_lines(b, b->first, y) )
return x;
return y;
}
static int
rlc_max(RlcData b, int x, int y)
{ if ( rlc_count_lines(b, b->first, x) > rlc_count_lines(b, b->first, y) )
return x;
return y;
}
static void
rlc_changed_line(RlcData b, int i, int mask)
{ b->lines[i].changed |= mask;
}
static void
rlc_set_selection(RlcData b, int sl, int sc, int el, int ec)
{ int sch = rlc_min(b, sl, b->sel_start_line);
int ech = rlc_max(b, el, b->sel_end_line);
int nel = NextLine(b, el);
int nsel= NextLine(b, b->sel_end_line);
int i;
int innow = FALSE;
int insoon = FALSE;
/* find the lines that changed */
for(i=sch; ; i = NextLine(b, i))
{ if ( i == sl )
{ insoon = TRUE;
if ( i == b->sel_start_line )
{ innow = TRUE;
if ( sc != b->sel_start_char ||
(i == el && i != b->sel_end_line) ||
(i == b->sel_end_line && i != el) )
rlc_changed_line(b, i, CHG_CHANGED);
} else
rlc_changed_line(b, i, CHG_CHANGED);
} else if ( i == b->sel_start_line )
{ innow = TRUE;
rlc_changed_line(b, i, CHG_CHANGED);
}
if ( i == b->sel_end_line )
{ if ( (i == el && ec != b->sel_end_char) || el != i )
rlc_changed_line(b, i, CHG_CHANGED);
}
if ( innow != insoon )
rlc_changed_line(b, i, CHG_CHANGED);
if ( i == nel )
{ insoon = FALSE;
if ( i == nsel )
innow = FALSE;
else
rlc_changed_line(b, i, CHG_CHANGED);
} else if ( i == nsel )
{ innow = FALSE;
rlc_changed_line(b, i, CHG_CHANGED);
}
if ( i == ech )
break;
}
/* update the attributes */
b->sel_start_line = sl;
b->sel_start_char = sc;
b->sel_end_line = el;
b->sel_end_char = ec;
/* ... and request a repaint */
rlc_request_redraw(b);
}
void
rlc_translate_mouse(RlcData b, int x, int y, int *line, int *chr)
{ int ln = b->window_start;
int n = b->window_size; /* # lines */
TextLine tl;
x-= b->cw; /* margin */
if ( !b->window )
return;
while( y > b->ch && ln != b->last && n-- > 0 )
{ ln = NextLine(b, ln);
y -= b->ch;
}
*line = ln;
tl = &b->lines[ln];
if ( b->fixedfont )
{ *chr = min(x/b->cw, tl->size);
} else if ( tl->size == 0 )
{ *chr = 0;
} else
{ text_char *s = tl->text;
HDC hdc = GetDC(b->window);
int f = 0;
int t = tl->size;
int m = (f+t)/2;
int i;
SelectObject(hdc, b->hfont);
for(i=10; --i > 0; m=(f+t)/2)
{ int w;
w = text_width(b, hdc, s, m);
if ( x > w )
{ int cw;
GetCharWidth32(hdc, s[m].code, s[m].code, &cw);
if ( x < w+cw )
{ *chr = m;
return;
}
f = m+1;
} else
{ t = m;
}
}
*chr = m;
}
}
static void
rlc_start_selection(RlcData b, int x, int y)
{ int l, c;
rlc_translate_mouse(b, x, y, &l, &c);
b->sel_unit = SEL_CHAR;
b->sel_org_line = l;
b->sel_org_char = c;
rlc_set_selection(b, l, c, l, c);
}
static int /* v >= f && v <= t */
rlc_between(RlcData b, int f, int t, int v)
{ int h = rlc_count_lines(b, b->first, v);
if ( h >= rlc_count_lines(b, b->first, f) &&
h <= rlc_count_lines(b, b->first, t) )
return TRUE;
return FALSE;
}
static void
rlc_word_selection(RlcData b, int x, int y)
{ int l, c;
rlc_translate_mouse(b, x, y, &l, &c);
if ( rlc_between(b, b->first, b->last, l) )
{ TextLine tl = &b->lines[l];
if ( c < tl->size && rlc_is_word_char(tl->text[c].code) )
{ int f, t;
for(f=c; f>0 && rlc_is_word_char(tl->text[f-1].code); f--)
;
for(t=c; t<tl->size && rlc_is_word_char(tl->text[t].code); t++)
;
rlc_set_selection(b, l, f, l, t);
}
}
b->sel_unit = SEL_WORD;
}
static void
rlc_extend_selection(RlcData b, int x, int y)
{ int l, c;
int el = b->sel_org_line;
int ec = b->sel_org_char;
rlc_translate_mouse(b, x, y, &l, &c);
if ( SelLT(l, c, b->sel_org_line, b->sel_org_char) )
{ if ( b->sel_unit == SEL_WORD )
{ if ( rlc_between(b, b->first, b->last, l) )
{ TextLine tl = &b->lines[l];
if ( c < tl->size && rlc_is_word_char(tl->text[c].code) )
for(; c > 0 && rlc_is_word_char(tl->text[c-1].code); c--)
;
}
if ( rlc_between(b, b->first, b->last, el) )
{ TextLine tl = &b->lines[el];
if ( ec < tl->size && rlc_is_word_char(tl->text[ec].code) )
for(; ec < tl->size && rlc_is_word_char(tl->text[ec].code); ec++)
;
}
} else if ( b->sel_unit == SEL_LINE )
c = 0;
rlc_set_selection(b, l, c, el, ec);
} else if ( SelLT(b->sel_org_line, b->sel_org_char, l, c) )
{ if ( b->sel_unit == SEL_WORD )
{ if ( rlc_between(b, b->first, b->last, l) )
{ TextLine tl = &b->lines[l];
if ( c < tl->size && rlc_is_word_char(tl->text[c].code) )
for(; c < tl->size && rlc_is_word_char(tl->text[c].code); c++)
;
}
if ( rlc_between(b, b->first, b->last, el) )
{ TextLine tl = &b->lines[el];
if ( ec < tl->size && rlc_is_word_char(tl->text[ec].code) )
for(; ec > 0 && rlc_is_word_char(tl->text[ec-1].code); ec--)
;
}
} else if ( b->sel_unit == SEL_LINE )
c = b->width;
rlc_set_selection(b, el, ec, l, c);
}
}
static TCHAR *
rlc_read_from_window(RlcData b, int sl, int sc, int el, int ec)
{ int bufsize = 256;
TCHAR *buf;
int i = 0;
if ( el < sl || (el == sl && ec < sc) )
return NULL; /* invalid region */
if ( !(buf = rlc_malloc(bufsize * sizeof(TCHAR))) )
return NULL; /* not enough memory */
for( ; ; sc = 0, sl = NextLine(b, sl))
{ TextLine tl = &b->lines[sl];
if ( tl )
{ int e = (sl == el ? ec : tl->size);
if ( e > tl->size )
e = tl->size;
while(sc < e)
{ if ( i+1 >= bufsize )
{ bufsize *= 2;
if ( !(buf = rlc_realloc(buf, bufsize * sizeof(TCHAR))) )
return NULL; /* not enough memory */
}
buf[i++] = tl->text[sc++].code;
}
}
if ( sl == el || sl == b->last )
{ buf[i++] = '\0'; /* Always room for the 0 */
return buf;
}
if ( tl && !tl->softreturn )
{ if ( i+2 >= bufsize )
{ bufsize *= 2;
if ( !(buf = rlc_realloc(buf, bufsize * sizeof(TCHAR))) )
return NULL; /* not enough memory */
}
buf[i++] = '\r'; /* Bill ... */
buf[i++] = '\n';
}
}
}
static int
rlc_has_selection(RlcData b)
{ if ( SelEQ(b->sel_start_line, b->sel_start_char,
b->sel_end_line, b->sel_end_char) )
return FALSE;
return TRUE;
}
static TCHAR *
rlc_selection(RlcData b)
{ if ( rlc_has_selection(b) )
return rlc_read_from_window(b,
b->sel_start_line, b->sel_start_char,
b->sel_end_line, b->sel_end_char);
return NULL;
}
static void
rlc_copy(RlcData b)
{ TCHAR *sel = rlc_selection(b);
if ( sel && b->window )
{ size_t size = _tcslen(sel);
HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (size + 1)*sizeof(TCHAR));
TCHAR far *data;
size_t i;
if ( !mem )
{ MessageBox(NULL, _T("Not enough memory to copy"), _T("Error"), MB_OK);
return;
}
data = GlobalLock(mem);
for(i=0; i<size; i++)
*data++ = sel[i];
*data = '\0';
GlobalUnlock(mem);
OpenClipboard(b->window);
EmptyClipboard();
#ifdef UNICODE
SetClipboardData(CF_UNICODETEXT, mem);
#else
SetClipboardData(CF_TEXT, mem);
#endif
CloseClipboard();
rlc_free(sel);
}
}
/*******************************
* REPAINT *
*******************************/
static void
rlc_place_caret(RlcData b)
{ if ( b->has_focus && b->window )
{ int line = rlc_count_lines(b, b->window_start, b->caret_y);
if ( line < b->window_size )
{ if ( b->fixedfont )
{ SetCaretPos((b->caret_x + 1) * b->cw, line * b->ch);
} else
{ HDC hdc = GetDC(b->window);
int tw;
TextLine tl = &b->lines[b->caret_y];
HFONT old;
old = SelectObject(hdc, b->hfont);
tw = text_width(b, hdc, tl->text, b->caret_x);
SelectObject(hdc, old);
ReleaseDC(b->window, hdc);
SetCaretPos(b->cw + tw, line * b->ch);
}
if ( !b->caret_is_shown )
{ ShowCaret(b->window);
b->caret_is_shown = TRUE;
return;
}
} else
{ if ( b->caret_is_shown == TRUE )
{ HideCaret(b->window);
b->caret_is_shown = FALSE;
}
}
}
b->caret_is_shown = FALSE;
}
static void
rlc_update_scrollbar(RlcData b)
{ if ( b->window )
{ int nsb_lines = rlc_count_lines(b, b->first, b->last);
int nsb_start = rlc_count_lines(b, b->first, b->window_start);
if ( nsb_lines != b->sb_lines ||
nsb_start != b->sb_start )
{ SetScrollRange(b->window, SB_VERT, 0, nsb_lines, FALSE);
SetScrollPos( b->window, SB_VERT, nsb_start, TRUE);
b->sb_lines = nsb_lines;
b->sb_start = nsb_start;
}
}
}
static void
rcl_paint_text(RlcData b, HDC hdc,
TextLine tl, int from, int to,
int ty, int *cx, int insel)
{ text_char *chars, *s;
text_char buf[MAXLINE];
TCHAR text[MAXLINE];
TCHAR *t;
int len = to-from;
int i;
if ( len <= 0 )
return;
if ( tl->text && to <= tl->size )
{ chars = &tl->text[from];
} else
{ text_char *o;
int copy;
o = chars = buf;
s = &tl->text[from];
copy = tl->text ? tl->size-from : 0;
for(i=0; i<copy; i++)
*o++ = *s++;
for(; i<len; i++, o++)
{ o->code = ' ';
o->flags = TF_DEFAULT;
}
}
for(t=text, s=chars, i=0; i < len; i++, t++, s++)
*t = s->code;
if ( insel ) /* TBD: Cache */
{ SetBkColor(hdc, b->sel_background);
SetTextColor(hdc, b->sel_foreground);
TextOut(hdc, *cx, ty, text, len);
*cx += tchar_width(b, hdc, text, len);
} else
{ int start, segment;
for(start=0, s=chars, t=text;
start<len;
start+=segment, s+=segment, t+=segment)
{ text_flags flags = s->flags;
int left = len-start;
for(segment=0; s[segment].flags == flags && segment<left; segment++)
;
if ( TF_FG(flags) == ANSI_COLOR_DEFAULT )
SetTextColor(hdc, b->foreground);
else
SetTextColor(hdc, b->ansi_color[TF_FG(flags)]);
if ( TF_BG(flags) == ANSI_COLOR_DEFAULT )
SetBkColor(hdc, b->background);
else
SetBkColor(hdc, b->ansi_color[TF_BG(flags)]);
TextOut(hdc, *cx, ty, t, segment);
if ( TF_BOLD(flags) )
{ SetBkMode(hdc, TRANSPARENT);
TextOut(hdc, (*cx)+1, ty, t, segment);
TextOut(hdc, *cx, ty+1, t, segment);
SetBkMode(hdc, OPAQUE);
}
*cx += tchar_width(b, hdc, t, segment);
}
}
}
static void
rlc_redraw(RlcData b)
{ PAINTSTRUCT ps;
HDC hdc = BeginPaint(b->window, &ps);
int sl = max(0, ps.rcPaint.top/b->ch);
int el = min(b->window_size, ps.rcPaint.bottom/b->ch);
int l = rlc_add_lines(b, b->window_start, sl);
int pl = sl; /* physical line */
RECT rect;
HBRUSH bg;
int stockbg;
int insel = FALSE; /* selected lines? */
SelectObject(hdc, b->hfont);
SetTextColor(hdc, b->foreground);
SetBkColor(hdc, b->background);
if ( b->background == RGB(255, 255, 255) )
{ bg = GetStockObject(WHITE_BRUSH);
stockbg = TRUE;
} else
{ bg = CreateSolidBrush(b->background);
stockbg = FALSE;
}
if ( b->has_focus && b->caret_is_shown )
{ HideCaret(b->window);
b->caret_is_shown = FALSE;
}
if ( rlc_count_lines(b, b->first, b->sel_start_line) <
rlc_count_lines(b, b->first, l) &&
rlc_count_lines(b, b->first, b->sel_end_line) >=
rlc_count_lines(b, b->first, l) )
insel = TRUE;
if ( insel )
{ SetBkColor(hdc, b->sel_background);
SetTextColor(hdc, b->sel_foreground);
}
for(; pl <= el; l = NextLine(b, l), pl++)
{ TextLine tl = &b->lines[l];
int ty = b->ch * pl;
int cx = b->cw;
rect.top = ty;
rect.bottom = rect.top + b->ch;
/* compute selection */
if ( l == b->sel_start_line )
{ int cf = b->sel_start_char;
int ce = (b->sel_end_line != b->sel_start_line ? b->width
: b->sel_end_char);
rcl_paint_text(b, hdc, tl, 0, cf, ty, &cx, insel);
insel = TRUE;
rcl_paint_text(b, hdc, tl, cf, ce, ty, &cx, insel);
if ( l == b->sel_end_line )
{ insel = FALSE;
rcl_paint_text(b, hdc, tl, ce, b->width, ty, &cx, insel);
} else
insel = TRUE;
} else if ( l == b->sel_end_line ) /* end of selection */
{ int ce = b->sel_end_char;
rcl_paint_text(b, hdc, tl, 0, ce, ty, &cx, insel);
insel = FALSE;
rcl_paint_text(b, hdc, tl, ce, b->width, ty, &cx, insel);
} else /* entire line in/out selection */
{ rcl_paint_text(b, hdc, tl, 0, b->width, ty, &cx, insel);
}
/* clear remainder of line */
if ( cx < b->width * (b->cw+1) )
{ rect.left = cx;
rect.right = b->width * (b->cw+1);
rect.top = b->ch * pl;
rect.bottom = rect.top + b->ch;
FillRect(hdc, &rect, bg);
}
tl->changed = CHG_RESET;
if ( l == b->last ) /* clear to end of window */
{ rect.left = b->cw;
rect.right = b->width * (b->cw+1);
rect.top = b->ch * (pl+1);
rect.bottom = b->ch * (el+1);
FillRect(hdc, &rect, bg);
break;
}
}
rlc_place_caret(b);
b->changed = CHG_RESET;
if ( !stockbg )
DeleteObject(bg);
EndPaint(b->window, &ps);
rlc_update_scrollbar(b);
}
static void
rlc_request_redraw(RlcData b)
{ if ( b->changed & CHG_CHANGED )
{ if ( b->window )
InvalidateRect(b->window, NULL, FALSE);
} else
{ int i = b->window_start;
int y = 0;
RECT rect;
int first = TRUE;
rect.left = b->cw;
rect.right = (b->width+1) * b->cw;
for(; y < b->window_size; y++, i = NextLine(b, i))
{ TextLine l = &b->lines[i];
if ( l->changed & CHG_CHANGED )
{ if ( first )
{ rect.top = y * b->ch;
rect.bottom = rect.top + b->ch;
first = FALSE;
} else
rect.bottom = (y+1) * b->ch;
}
if ( i == b->last )
break;
}
if ( !first && b->window )
InvalidateRect(b->window, &rect, FALSE);
else if ( b->changed & CHG_CARET )
rlc_place_caret(b);
}
}
static void
rlc_normalise(RlcData b)
{ if ( rlc_count_lines(b, b->window_start, b->caret_y) >= b->window_size )
{ b->window_start = rlc_add_lines(b, b->caret_y, -(b->window_size-1));
b->changed |= CHG_CARET|CHG_CLEAR|CHG_CHANGED;
rlc_request_redraw(b);
}
}
static void
rlc_resize_pixel_units(RlcData b, int w, int h)
{ int nw = max(20, w/b->cw)-2; /* 1 character space for margins */
int nh = max(1, h/b->ch);
DEBUG(Dprintf(_T("rlc_resize_pixel_units(%p, %d, %d) (%dx%d)\n"),
b, w, h, nw, nh));
if ( b->width == nw && b->window_size == nh )
return; /* no real change */
rlc_resize(b, nw, nh);
if ( _rlc_resize_hook )
(*_rlc_resize_hook)(b->width, b->window_size);
else
{
#ifdef SIGWINCH
raise(SIGWINCH);
#endif
}
rlc_request_redraw(b);
}
/*******************************
* FONT *
*******************************/
static void
rlc_init_text_dimensions(RlcData b, HFONT font)
{ HDC hdc;
TEXTMETRIC tm;
if ( font )
{ b->hfont = font;
} else if ( b->create_attributes )
{ rlc_console_attr *a = b->create_attributes;
if ( !a->face_name[0] )
b->hfont = GetStockObject(ANSI_FIXED_FONT);
else
{ LOGFONT lfont;
memset(&lfont, 0, sizeof(lfont));
lfont.lfHeight = a->font_size;
lfont.lfWeight = a->font_weight;
lfont.lfPitchAndFamily = a->font_family;
lfont.lfCharSet = a->font_char_set;
_tcsncpy(lfont.lfFaceName, a->face_name, 31);
if ( !(b->hfont = CreateFontIndirect(&lfont)) )
b->hfont = GetStockObject(ANSI_FIXED_FONT);
}
} else
b->hfont = GetStockObject(ANSI_FIXED_FONT);
/* test for fixed?*/
hdc = GetDC(NULL);
SelectObject(hdc, b->hfont);
GetTextMetrics(hdc, &tm);
b->cw = tm.tmAveCharWidth;
b->cb = tm.tmHeight;
b->ch = tm.tmHeight + tm.tmExternalLeading;
b->fixedfont = (tm.tmPitchAndFamily & TMPF_FIXED_PITCH ? FALSE : TRUE);
ReleaseDC(NULL, hdc);
if ( b->window )
{ RECT rect;
if ( b->has_focus == TRUE )
{ CreateCaret(b->window, NULL, b->fixedfont ? b->cw : 3, b->ch-1);
rlc_place_caret(b);
}
GetClientRect(b->window, &rect);
rlc_resize_pixel_units(b, rect.right - rect.left, rect.bottom - rect.top);
}
}
static int
text_width(RlcData b, HDC hdc, const text_char *text, int len)
{ if ( b->fixedfont )
{ return len * b->cw;
} else
{ SIZE size;
TCHAR tmp[MAXLINE];
int i;
for(i=0; i<len; i++)
tmp[i] = text[i].code;
GetTextExtentPoint32(hdc, tmp, len, &size);
return size.cx;
}
}
static int
tchar_width(RlcData b, HDC hdc, const TCHAR *text, int len)
{ if ( b->fixedfont )
{ return len * b->cw;
} else
{ SIZE size;
GetTextExtentPoint32(hdc, text, len, &size);
return size.cx;
}
}
static void
rlc_save_font_options(HFONT font, rlc_console_attr *attr)
{ if ( font == GetStockObject(ANSI_FIXED_FONT) )
{ attr->face_name[0] = '\0';
} else
{ LOGFONT lf;
if ( GetObject(font, sizeof(lf), &lf) )
{ memcpy(attr->face_name, lf.lfFaceName, sizeof(attr->face_name)-1);
attr->font_family = lf.lfPitchAndFamily;
attr->font_size = lf.lfHeight;
attr->font_weight = lf.lfWeight;
attr->font_char_set = lf.lfCharSet;
}
}
}
/*******************************
* FONT SELECTION *
*******************************/
static void
rlc_queryfont(RlcData b)
{ CHOOSEFONT cf;
LOGFONT lf;
memset(&cf, 0, sizeof(cf));
memset(&lf, 0, sizeof(lf));
lf.lfHeight = 16;
lf.lfWeight = FW_NORMAL;
lf.lfPitchAndFamily = FIXED_PITCH|FF_MODERN;
cf.lStructSize = sizeof(cf);
cf.hwndOwner = b->window;
cf.lpLogFont = &lf;
cf.Flags = CF_SCREENFONTS|
CF_NOVERTFONTS|
CF_NOSIMULATIONS|
CF_FORCEFONTEXIST|
CF_INITTOLOGFONTSTRUCT;
cf.nFontType = SCREEN_FONTTYPE;
if ( ChooseFont(&cf) )
{ HFONT f;
if ( (f = CreateFontIndirect(&lf)) )
{ rlc_init_text_dimensions(b, f);
InvalidateRect(b->window, NULL, TRUE);
}
}
}
/*******************************
* BUFFER INITIALISATION *
*******************************/
static RlcData
rlc_make_buffer(int w, int h)
{ RlcData b = rlc_malloc(sizeof(rlc_data));
int i;
memset(b, 0, sizeof(*b));
b->magic = RLC_MAGIC;
b->height = h;
b->width = w;
b->window_size = 25;
b->lines = rlc_malloc(sizeof(text_line) * h);
b->cmdstat = CMD_INITIAL;
b->changed = CHG_CARET|CHG_CHANGED|CHG_CLEAR;
b->imode = IMODE_COOKED; /* switch on first rlc_read() call */
b->imodeswitch = FALSE;
b->lhead = NULL;
b->ltail = NULL;
memset(b->lines, 0, sizeof(text_line) * h);
for(i=0; i<h; i++)
b->lines[i].adjusted = TRUE;
rlc_init_word_chars();
return b;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Copy all lines one `back' (i.e. towards older lines). If the oldest
(first) line is adjacent to the last, throw it away.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static void
rlc_shift_lines_down(RlcData b, int line)
{ int i = b->first;
int p = PrevLine(b, i);
if ( p != b->last ) /* move first (oldest line) */
{ b->first = p;
b->lines[p] = b->lines[i];
} else /* delete first (oldest) line */
rlc_free_line(b, b->first);
/* copy the lines */
for(p=i, i = NextLine(b, i); p != line; p=i, i = NextLine(b, i))
b->lines[p] = b->lines[i];
b->lines[line].text = NULL; /* make this one `free' */
b->lines[line].size = 0;
b->lines[line].adjusted = TRUE;
b->lines[line].softreturn = FALSE;
}
static void
rlc_shift_lines_up(RlcData b, int line)
{ int prev = PrevLine(b, line);
while(line != b->first)
{ b->lines[line] = b->lines[prev];
line = prev;
prev = PrevLine(b, prev);
}
rlc_reinit_line(b, b->first);
b->first = NextLine(b, b->first);
}
static void
rlc_resize(RlcData b, int w, int h)
{ int i;
if ( b->width == w && b->window_size == h )
return; /* no real change */
DEBUG(Dprintf(_T("Resizing %dx%d --> %dx%d\n"),
b->width, b->window_size, w, h));
b->window_size = h;
b->width = w;
for(i = b->first; /*i != b->last*/; i = NextLine(b, i))
{ TextLine tl = &b->lines[i];
if ( tl->text && tl->adjusted == FALSE )
rlc_adjust_line(b, i);
if ( tl->size > w )
{ if ( !tl->softreturn ) /* hard --> soft */
{ TextLine pl;
rlc_shift_lines_down(b, i);
DEBUG(Dprint_lines(b, b->first, b->first));
DEBUG(Dprintf(_T("b->first = %d, b->last = %d\n"), b->first, b->last));
pl = &b->lines[PrevLine(b, i)]; /* this is the moved line */
tl->text = rlc_malloc((pl->size - w)*sizeof(text_char));
memmove(tl->text, &pl->text[w], (pl->size - w)*sizeof(text_char));
DEBUG(Dprintf(_T("Copied %d chars from line %d to %d\n"),
pl->size - w, pl - b->lines, i));
tl->size = pl->size - w;
tl->adjusted = TRUE;
tl->softreturn = FALSE;
pl->softreturn = TRUE;
pl->text = rlc_realloc(pl->text, w * sizeof(text_char));
pl->size = w;
pl->adjusted = TRUE;
i = (int)(pl - b->lines);
DEBUG(Dprint_lines(b, b->first, b->last));
} else /* put in next line */
{ TextLine nl;
int move = tl->size - w;
if ( i == b->last )
rlc_add_line(b);
nl = &b->lines[NextLine(b, i)];
nl->text = rlc_realloc(nl->text, (nl->size + move)*sizeof(text_char));
memmove(&nl->text[move], nl->text, nl->size*sizeof(text_char));
memmove(nl->text, &tl->text[w], move*sizeof(text_char));
nl->size += move;
tl->size = w;
}
} else if ( tl->text && tl->softreturn && tl->size < w )
{ TextLine nl;
if ( i == b->last )
rlc_add_line(b);
nl = &b->lines[NextLine(b, i)];
nl->text = rlc_realloc(nl->text, (nl->size + tl->size)*sizeof(text_char));
memmove(&nl->text[tl->size], nl->text, nl->size*sizeof(text_char));
memmove(nl->text, tl->text, tl->size*sizeof(text_char));
nl->size += tl->size;
nl->adjusted = TRUE;
rlc_shift_lines_up(b, i);
}
if ( i == b->last )
break;
}
for(i = NextLine(b, i); i != b->first; i = NextLine(b, i))
rlc_free_line(b, i);
if ( rlc_count_lines(b, b->first, b->last) < h )
b->window_start = b->first;
else
b->window_start = rlc_add_lines(b, b->last, -(h-1));
b->caret_y = b->last;
b->caret_x = b->lines[b->last].size;
b->changed |= CHG_CARET|CHG_CHANGED|CHG_CLEAR;
rlc_check_assertions(b);
}
static void
rlc_reinit_line(RlcData b, int line)
{ TextLine tl = &b->lines[line];
tl->text = NULL;
tl->adjusted = FALSE;
tl->size = 0;
tl->softreturn = FALSE;
}
static void
rlc_free_line(RlcData b, int line)
{ TextLine tl = &b->lines[line];
if ( tl->text )
{ rlc_free(tl->text);
rlc_reinit_line(b, line);
}
}
static void
rlc_adjust_line(RlcData b, int line)
{ TextLine tl = &b->lines[line];
if ( tl->text && !tl->adjusted )
{ tl->text = rlc_realloc(tl->text, tl->size == 0
? sizeof(text_char)
: tl->size * sizeof(text_char));
tl->adjusted = TRUE;
}
}
static void
rlc_unadjust_line(RlcData b, int line)
{ TextLine tl = &b->lines[line];
if ( tl->text )
{ if ( tl->adjusted )
{ tl->text = rlc_realloc(tl->text, (b->width + 1)*sizeof(text_char));
tl->adjusted = FALSE;
}
} else
{ tl->text = rlc_malloc((b->width + 1)*sizeof(text_char));
tl->adjusted = FALSE;
tl->size = 0;
}
}
static void
rlc_open_line(RlcData b)
{ int i = b->last;
if ( i == b->sel_start_line )
rlc_set_selection(b, 0, 0, 0, 0); /* clear the selection */
if ( i == b->first )
{ rlc_free_line(b, b->first);
b->first = NextLine(b, b->first);
}
b->lines[i].text = rlc_malloc((b->width + 1)*sizeof(text_char));
b->lines[i].adjusted = FALSE;
b->lines[i].size = 0;
b->lines[i].softreturn = FALSE;
}
static void
rlc_add_line(RlcData b)
{ b->last = NextLine(b, b->last);
rlc_open_line(b);
}
/*******************************
* CALCULATIONS *
*******************************/
static int
rlc_count_lines(RlcData b, int from, int to)
{ if ( to >= from )
return to-from;
return to + b->height - from;
}
static int
rlc_add_lines(RlcData b, int here, int add)
{ here += add;
while ( here < 0 )
here += b->height;
while ( here >= b->height )
here -= b->height;
return here;
}
/*******************************
* ANSI SEQUENCE HANDLING *
*******************************/
static void
rlc_need_arg(RlcData b, int arg, int def)
{ if ( b->argc < arg )
{ b->argv[arg-1] = def;
b->argc = arg;
}
}
static void
rlc_caret_up(RlcData b, int arg)
{ while(arg-- > 0 && b->caret_y != b->first)
b->caret_y = PrevLine(b, b->caret_y);
b->changed |= CHG_CARET;
}
static void
rlc_caret_down(RlcData b, int arg)
{ while ( arg-- > 0 )
{ if ( b->caret_y == b->last )
rlc_add_line(b);
b->caret_y = NextLine(b, b->caret_y);
b->lines[b->caret_y].softreturn = FALSE; /* ? why not only on open? */
}
b->changed |= CHG_CARET;
/* scroll? */
if ( rlc_count_lines(b, b->window_start, b->caret_y) >= b->window_size )
{ b->window_start = rlc_add_lines(b, b->caret_y, -(b->window_size-1));
b->changed |= CHG_CHANGED|CHG_CLEAR;
}
rlc_check_assertions(b);
}
static void
rlc_caret_forward(RlcData b, int arg)
{ while(arg-- > 0)
{ if ( ++b->caret_x >= b->width )
{ b->lines[b->caret_y].softreturn = TRUE;
b->caret_x = 0;
rlc_caret_down(b, 1);
}
}
b->changed |= CHG_CARET;
}
static void
rlc_caret_backward(RlcData b, int arg)
{ while(arg-- > 0)
{ if ( b->caret_x-- == 0 )
{ rlc_caret_up(b, 1);
b->caret_x = b->width-1;
}
}
b->changed |= CHG_CARET;
}
static void
rlc_cariage_return(RlcData b)
{ b->caret_x = 0;
b->changed |= CHG_CARET;
}
static void
rlc_tab(RlcData b)
{ TextLine tl = &b->lines[b->caret_y];
do
{ rlc_caret_forward(b, 1);
} while( (b->caret_x % 8) != 0 );
if ( tl->size < b->caret_x )
{ rlc_unadjust_line(b, b->caret_y);
while ( tl->size < b->caret_x )
{ text_char *tc = &tl->text[tl->size++];
tc->code = ' ';
tc->flags = b->sgr_flags;
}
}
b->changed |= CHG_CARET;
}
static void
rlc_set_caret(RlcData b, int x, int y)
{ int cy = rlc_count_lines(b, b->window_start, b->caret_y);
y = Bounds(y, 0, b->window_size);
if ( y < cy )
b->caret_y = rlc_add_lines(b, b->window_start, y);
else
rlc_caret_down(b, y-cy);
b->caret_x = Bounds(x, 0, b->width-1);
b->changed |= CHG_CARET;
}
static void
rlc_save_caret_position(RlcData b)
{ b->scaret_y = rlc_count_lines(b, b->window_start, b->caret_y);
b->scaret_x = b->caret_x;
}
static void
rlc_restore_caret_position(RlcData b)
{ rlc_set_caret(b, b->scaret_x, b->scaret_y);
}
static void
rlc_erase_display(RlcData b)
{ int i = b->window_start;
int last = rlc_add_lines(b, b->window_start, b->window_size);
do
{ b->lines[i].size = 0;
i = NextLine(b, i);
} while ( i != last );
b->changed |= CHG_CHANGED|CHG_CLEAR|CHG_CARET;
rlc_set_caret(b, 0, 0);
}
static void
rlc_erase_line(RlcData b)
{ TextLine tl = &b->lines[b->caret_y];
tl->size = b->caret_x;
tl->changed |= CHG_CHANGED|CHG_CLEAR;
}
static void
rlc_sgr(RlcData b, int sgr)
{ if ( sgr == 0 )
{ b->sgr_flags = TF_DEFAULT;
} else if ( sgr >= 30 && sgr <= 39 )
{ b->sgr_flags = TF_SET_FG(b->sgr_flags,
sgr == 39 ? ANSI_COLOR_DEFAULT : sgr-30);
} else if ( sgr >= 40 && sgr <= 49 )
{ b->sgr_flags = TF_SET_BG(b->sgr_flags,
sgr == 49 ? ANSI_COLOR_DEFAULT : sgr-40);
} else if ( sgr >= 90 && sgr <= 99 )
{ b->sgr_flags = TF_SET_FG(b->sgr_flags,
sgr == 99 ? ANSI_COLOR_DEFAULT : sgr-90+8);
} else if ( sgr >= 100 && sgr <= 109 )
{ b->sgr_flags = TF_SET_BG(b->sgr_flags,
sgr == 109 ? ANSI_COLOR_DEFAULT : sgr-100+8);
} else if ( sgr == 1 )
{ b->sgr_flags = TF_SET_BOLD(b->sgr_flags, 1);
} else if ( sgr == 4 )
{ b->sgr_flags = TF_SET_UNDERLINE(b->sgr_flags, 1);
}
}
static void
rlc_put(RlcData b, int chr)
{ TextLine tl = &b->lines[b->caret_y];
text_char *tc;
rlc_unadjust_line(b, b->caret_y);
while( tl->size < b->caret_x )
{ tc = &tl->text[tl->size++];
tc->code = ' ';
tc->flags = b->sgr_flags;
}
tc = &tl->text[b->caret_x];
tc->code = chr;
tc->flags = b->sgr_flags;
if ( tl->size <= b->caret_x )
tl->size = b->caret_x + 1;
tl->changed |= CHG_CHANGED;
rlc_caret_forward(b, 1);
}
#ifdef _DEBUG
#define CMD(c) {cmd = _T(#c); c;}
#else
#define CMD(c) {c;}
#endif
static void
rlc_putansi(RlcData b, int chr)
{
#ifdef _DEBUG
TCHAR *cmd;
#endif
switch(b->cmdstat)
{ case CMD_INITIAL:
switch(chr)
{ case '\b':
CMD(rlc_caret_backward(b, 1));
break;
case Control('G'):
MessageBeep(MB_ICONEXCLAMATION);
break;
case '\r':
CMD(rlc_cariage_return(b));
break;
case '\n':
CMD(rlc_caret_down(b, 1));
break;
case '\t':
CMD(rlc_tab(b));
break;
case 27: /* ESC */
b->cmdstat = CMD_ESC;
break;
default:
CMD(rlc_put(b, chr));
break;
}
break;
case CMD_ESC:
switch(chr)
{ case '[':
b->cmdstat = CMD_ANSI;
b->argc = 0;
b->argstat = 0; /* no arg */
break;
default:
b->cmdstat = CMD_INITIAL;
break;
}
break;
case CMD_ANSI: /* ESC [ */
if ( _istdigit((wint_t)chr) )
{ if ( !b->argstat )
{ b->argv[b->argc] = (chr - '0');
b->argstat = 1; /* positive */
} else
{ b->argv[b->argc] = b->argv[b->argc] * 10 + (chr - '0');
}
break;
}
if ( !b->argstat && chr == '-' )
{ b->argstat = -1; /* negative */
break;
}
if ( b->argstat )
{ b->argv[b->argc] *= b->argstat;
if ( b->argc < (ANSI_MAX_ARGC-1) )
b->argc++; /* silently discard more of them */
b->argstat = 0;
}
switch(chr)
{ case ';':
return; /* wait for more args */
case 'H':
case 'f':
rlc_need_arg(b, 1, 0);
rlc_need_arg(b, 2, 0);
CMD(rlc_set_caret(b, b->argv[0], b->argv[1]));
break;
case 'A':
rlc_need_arg(b, 1, 1);
CMD(rlc_caret_up(b, b->argv[0]));
break;
case 'B':
rlc_need_arg(b, 1, 1);
CMD(rlc_caret_down(b, b->argv[0]));
break;
case 'C':
rlc_need_arg(b, 1, 1);
CMD(rlc_caret_forward(b, b->argv[0]));
break;
case 'D':
rlc_need_arg(b, 1, 1);
CMD(rlc_caret_backward(b, b->argv[0]));
break;
case 's':
CMD(rlc_save_caret_position(b));
break;
case 'u':
CMD(rlc_restore_caret_position(b));
break;
case 'J':
if ( b->argv[0] == 2 )
CMD(rlc_erase_display(b));
break;
case 'K':
CMD(rlc_erase_line(b));
break;
case 'm':
{ int i;
rlc_need_arg(b, 1, 0);
for(i=0; i<b->argc; i++)
CMD(rlc_sgr(b, b->argv[i]));
break;
}
}
b->cmdstat = CMD_INITIAL;
}
rlc_check_assertions(b);
}
/*******************************
* CUT/PASTE *
*******************************/
static void
rlc_paste(RlcData b)
{ HGLOBAL mem;
if ( b->window )
{ OpenClipboard(b->window);
if ( (mem = GetClipboardData(CF_UNICODETEXT)) )
{ wchar_t *data = GlobalLock(mem);
int i;
RlcQueue q = b->queue;
if ( q )
{ for(i=0; data[i]; i++)
{ rlc_add_queue(b, q, data[i]);
if ( data[i] == '\r' && data[i+1] == '\n' )
i++;
}
}
GlobalUnlock(mem);
} else if ( (mem = GetClipboardData(CF_TEXT)) )
{ char far *data = GlobalLock(mem);
int i;
RlcQueue q = b->queue;
if ( q )
{ for(i=0; data[i]; i++)
{ rlc_add_queue(b, q, data[i]);
if ( data[i] == '\r' && data[i+1] == '\n' )
i++;
}
}
GlobalUnlock(mem);
}
CloseClipboard();
}
}
/*******************************
* LINE-READ SUPPORT *
*******************************/
void
rlc_get_mark(rlc_console c, RlcMark m)
{ RlcData b = rlc_get_data(c);
m->mark_x = b->caret_x;
m->mark_y = b->caret_y;
}
void
rlc_goto_mark(rlc_console c, RlcMark m, const TCHAR *data, size_t offset)
{ RlcData b = rlc_get_data(c);
b->caret_x = m->mark_x;
b->caret_y = m->mark_y;
for( ; offset-- > 0; data++ )
{ switch(*data)
{ case '\t':
rlc_tab(b);
break;
case '\n':
b->caret_x = 0;
rlc_caret_down(b, 1);
break;
default:
rlc_caret_forward(b, 1);
}
}
}
void
rlc_erase_from_caret(rlc_console c)
{ RlcData b = rlc_get_data(c);
int i = b->caret_y;
int x = b->caret_x;
int last = rlc_add_lines(b, b->window_start, b->window_size);
do
{ TextLine tl = &b->lines[i];
if ( tl->size != x )
{ tl->size = x;
tl->changed |= CHG_CHANGED|CHG_CLEAR;
}
i = NextLine(b, i);
x = 0;
} while ( i != last );
}
void
rlc_putchar(rlc_console c, int chr)
{ RlcData b = rlc_get_data(c);
rlc_putansi(b, chr);
}
TCHAR *
rlc_read_screen(rlc_console c, RlcMark f, RlcMark t)
{ RlcData b = rlc_get_data(c);
TCHAR *buf;
buf = rlc_read_from_window(b, f->mark_y, f->mark_x, t->mark_y, t->mark_x);
return buf;
}
void
rlc_update(rlc_console c)
{ RlcData b = rlc_get_data(c);
if ( b->window )
{ rlc_normalise(b);
rlc_request_redraw(b);
UpdateWindow(b->window);
}
}
/*******************************
* UPDATE THREAD *
*******************************/
DWORD WINAPI
window_loop(LPVOID arg)
{ RlcData b = (RlcData) arg;
rlc_create_window(b);
/* if we do not do this, all windows */
/* created by Prolog (XPCE) will be */
/* in the background and inactive! */
if ( !AttachThreadInput(b->application_thread_id,
b->console_thread_id, TRUE) )
rlc_putansi(b, '!');
PostThreadMessage(b->application_thread_id, WM_RLC_READY, 0, 0);
while(!b->closing)
{ switch( b->imode )
{ case IMODE_COOKED:
{ TCHAR *line = read_line(b);
if ( line != RL_CANCELED_CHARP )
{ LQueued lq = rlc_malloc(sizeof(lqueued));
lq->next = NULL;
lq->line = line;
if ( b->ltail )
{ b->ltail->next = lq;
b->ltail = lq;
} else
{ b->lhead = b->ltail = lq;
/* awake main thread */
PostThreadMessage(b->application_thread_id, WM_RLC_INPUT, 0, 0);
}
}
break;
}
case IMODE_RAW:
{ MSG msg;
if ( rlc_get_message(&msg, NULL, 0, 0) )
{ TranslateMessage(&msg);
DispatchMessage(&msg);
rlc_flush_output(b);
} else
goto out;
if ( b->imodeswitch )
{ b->imodeswitch = FALSE;
}
}
}
}
if ( b->closing <= 2 )
{ MSG msg;
TCHAR *waiting = _T("\r\nWaiting for Prolog. ")
_T("Close again to force termination ..");
rlc_write(b, waiting, _tcslen(waiting));
while ( b->closing <= 2 && rlc_get_message(&msg, NULL, 0, 0) )
{ TranslateMessage(&msg);
DispatchMessage(&msg);
rlc_flush_output(b);
}
}
out:
{ DWORD appthread = b->application_thread_id;
rlc_destroy(b);
PostThreadMessage(appthread, WM_RLC_READY, 0, 0);
}
return 0;
}
/*******************************
* WATCOM/DOS I/O *
*******************************/
int
getch(rlc_console c)
{ RlcData b = rlc_get_data(c);
RlcQueue q = b->queue;
int fromcon = (GetCurrentThreadId() == b->console_thread_id);
while( rlc_is_empty_queue(q) )
{ if ( q->flags & RLC_EOF )
return EOF;
if ( !fromcon )
{ MSG msg;
if ( rlc_get_message(&msg, NULL, 0, 0) )
{ TranslateMessage(&msg);
DispatchMessage(&msg);
} else
return EOF;
} else
{ rlc_dispatch(b);
if ( b->imodeswitch )
{ b->imodeswitch = FALSE;
return IMODE_SWITCH_CHAR;
}
}
}
return rlc_from_queue(q);
}
int
getche(rlc_console c)
{ RlcData b = rlc_get_data(c);
int chr = getch(b);
rlc_putansi(b, chr);
return chr;
}
/*******************************
* GO32 FUNCTIONS *
*******************************/
int
getkey(rlc_console con)
{ int c;
RlcData b = rlc_get_data(con);
int fromcon = (GetCurrentThreadId() == b->console_thread_id);
if ( !fromcon && b->imode != IMODE_RAW )
{ int old = b->imode;
b->imode = IMODE_RAW;
b->imodeswitch = TRUE;
c = getch(b);
b->imode = old;
b->imodeswitch = TRUE;
} else
c = getch(b);
return c;
}
int
kbhit(rlc_console c)
{ RlcData b = rlc_get_data(c);
return !rlc_is_empty_queue(b->queue);
}
void
ScreenGetCursor(rlc_console c, int *row, int *col)
{ RlcData b = rlc_get_data(c);
*row = rlc_count_lines(b, b->window_start, b->caret_y) + 1;
*col = b->caret_x + 1;
}
void
ScreenSetCursor(rlc_console c, int row, int col)
{ RlcData b = rlc_get_data(c);
rlc_set_caret(b, col-1, row-1);
}
int
ScreenCols(rlc_console c)
{ RlcData b = rlc_get_data(c);
return b->width;
}
int
ScreenRows(rlc_console c)
{ RlcData b = rlc_get_data(c);
return b->window_size;
}
/*******************************
* QUEUE *
*******************************/
#define QN(q, i) ((i)+1 >= (q)->size ? 0 : (i)+1)
RlcQueue
rlc_make_queue(int size)
{ RlcQueue q;
if ( (q = rlc_malloc(sizeof(rlc_queue))) )
{ q->first = q->last = 0;
q->size = size;
q->flags = 0;
if ( (q->buffer = rlc_malloc(sizeof(TCHAR) * size)) )
return q;
}
return NULL; /* not enough memory */
}
static int
rlc_resize_queue(RlcQueue q, int size)
{ TCHAR *newbuf;
if ( (newbuf = rlc_malloc(size*sizeof(TCHAR))) )
{ TCHAR *o = newbuf;
int c;
while( (c=rlc_from_queue(q)) != -1 )
*o++ = c;
if ( q->buffer )
rlc_free(q->buffer);
q->buffer = newbuf;
q->first = 0;
q->last = (int)(o-newbuf);
q->size = size;
return TRUE;
}
return FALSE;
}
static int
rlc_add_queue(RlcData b, RlcQueue q, int chr)
{ int empty = (q->first == q->last);
while(q->size < 50000)
{ if ( QN(q, q->last) != q->first )
{ q->buffer[q->last] = chr;
q->last = QN(q, q->last);
if ( empty )
PostThreadMessage(b->application_thread_id, WM_RLC_INPUT, 0, 0);
return TRUE;
}
rlc_resize_queue(q, q->size*2);
}
return FALSE;
}
int
rlc_is_empty_queue(RlcQueue q)
{ if ( q->first == q->last )
return TRUE;
return FALSE;
}
static int
rlc_from_queue(RlcQueue q)
{ if ( q->first != q->last )
{ int chr = q->buffer[q->first];
q->first = QN(q, q->first);
return chr;
}
return -1;
}
/*******************************
* BUFFERED I/O *
*******************************/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
When using UNICODE, count is in bytes!
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
size_t
rlc_read(rlc_console c, TCHAR *buf, size_t count)
{ RlcData d = rlc_get_data(c);
size_t give;
MSG msg;
if ( d->closing )
return 0; /* signal EOF when closing */
PostThreadMessage(d->console_thread_id,
WM_RLC_FLUSH,
0, 0);
if ( _rlc_update_hook )
(*_rlc_update_hook)();
d->promptbuf[d->promptlen] = EOS;
_tcscpy(d->prompt, d->promptbuf);
if ( d->read_buffer.given >= d->read_buffer.length )
{ if ( d->read_buffer.line )
{ rlc_free(d->read_buffer.line);
d->read_buffer.line = NULL;
}
if ( d->imode != IMODE_COOKED )
{ d->imode = IMODE_COOKED;
d->imodeswitch = TRUE;
}
while(!d->lhead)
{ if ( rlc_get_message(&msg, NULL, 0, 0) )
{ TranslateMessage(&msg);
DispatchMessage(&msg);
} else
return -1;
}
{ LQueued lq = d->lhead;
d->read_buffer.line = lq->line;
if ( lq->next )
d->lhead = lq->next;
else
d->lhead = d->ltail = NULL;
rlc_free(lq);
}
d->read_buffer.length = _tcslen(d->read_buffer.line);
d->read_buffer.given = 0;
}
if ( d->read_buffer.length - d->read_buffer.given > count )
give = count;
else
give = d->read_buffer.length - d->read_buffer.given;
_tcsncpy(buf, d->read_buffer.line+d->read_buffer.given, give);
d->read_buffer.given += give;
return give;
}
static void
rlc_do_write(RlcData b, TCHAR *buf, int count)
{ if ( count > 0 )
{ int n = 0;
TCHAR *s = buf;
while(n++ < count)
{ int chr = *s++;
if ( chr == '\n' )
rlc_putansi(b, '\r');
rlc_putansi(b, chr);
}
rlc_normalise(b);
if ( b->window )
{ rlc_request_redraw(b);
UpdateWindow(b->window);
}
}
}
int
rlc_flush_output(rlc_console c)
{ RlcData b = rlc_get_data(c);
if ( !b )
return -1;
if ( b->output_queued )
{ rlc_do_write(b, b->output_queue, b->output_queued);
b->output_queued = 0;
}
return 0;
}
size_t
rlc_write(rlc_console c, TCHAR *buf, size_t count)
{ DWORD_PTR result;
TCHAR *e, *s;
RlcData b = rlc_get_data(c);
if ( !b )
return -1;
for(s=buf, e=&buf[count]; s<e; s++)
{ if ( *s == '\n' )
b->promptlen = 0;
else if ( b->promptlen < MAXPROMPT-1 )
b->promptbuf[b->promptlen++] = *s;
}
if ( b->window )
{ if ( SendMessageTimeout(b->window,
WM_RLC_WRITE,
(WPARAM)count,
(LPARAM)buf,
SMTO_NORMAL,
10000,
&result) )
{ PostMessage(b->window,
WM_RLC_FLUSH,
0, 0);
return count;
}
}
return -1; /* I/O error */
}
static void
free_rlc_data(RlcData b)
{ b->magic = 42; /* so next gets errors */
if ( b->lines )
{ int i;
for(i=0; i<b->height; i++)
{ if ( b->lines[i].text )
free(b->lines[i].text);
}
free(b->lines);
}
if ( b->read_buffer.line )
free(b->read_buffer.line);
free(b);
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
rlc_close() tries to gracefully get rid of the console thread. It does
so by posting WM_RLC_CLOSEWIN and then waiting for a WM_RLC_READY reply.
It waits for a maximum of 1.5 second, which should be fine as the
console thread should not have intptr_t-lasting activities.
If the timeout expires it hopes for the best. This was the old situation
and proved to be sound on Windows-NT, but not on 95 and '98.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
int
rlc_close(rlc_console c)
{ RlcData b = (RlcData)c;
MSG msg;
int i;
if ( b->magic != RLC_MAGIC )
return -1;
rlc_save_options(b);
b->closing = 3;
PostMessage(b->window, WM_RLC_CLOSEWIN, 0, 0);
/* wait for termination */
for(i=0; i<30; i++)
{ if ( PeekMessage(&msg, NULL, WM_RLC_READY, WM_RLC_READY, PM_REMOVE) )
break;
Sleep(50);
}
b->magic = 0;
free_user_data(c);
free_rlc_data(b);
return 0;
}
const TCHAR *
rlc_prompt(rlc_console c, const TCHAR *new)
{ RlcData b = rlc_get_data(c);
if ( b )
{ if ( new )
{ _tcsncpy(b->prompt, new, MAXPROMPT);
b->prompt[MAXPROMPT-1] = EOS;
}
return b->prompt;
}
return _T("");
}
void
rlc_clearprompt(rlc_console c)
{ RlcData b = rlc_get_data(c);
if ( b )
{ b->promptlen = 0;
b->prompt[0] = EOS;
}
}
/*******************************
* MISC STUFF *
*******************************/
void
rlc_title(rlc_console c, TCHAR *title, TCHAR *old, int size)
{ RlcData b = rlc_get_data(c);
if ( old )
memmove(old, b->current_title, size*sizeof(TCHAR));
if ( title )
{ if ( b->window )
SetWindowText(b->window, title);
memmove(b->current_title, title, RLC_TITLE_MAX*sizeof(TCHAR));
}
}
void
rlc_icon(rlc_console c, HICON icon)
{
SetClassLongPtr(rlc_hwnd(c), GCLP_HICON, (LONG_PTR) icon);
}
int
rlc_window_pos(rlc_console c,
HWND hWndInsertAfter,
int x, int y, int w, int h,
UINT flags)
{ RlcData b = rlc_get_data(c);
if ( b )
{ w *= b->cw;
h *= b->ch;
SetWindowPos(b->window, hWndInsertAfter,
x, y, w, h,
flags);
return TRUE;
}
return FALSE;
}
HANDLE
rlc_hinstance()
{ return _rlc_hinstance;
}
HWND
rlc_hwnd(rlc_console c)
{ RlcData b = rlc_get_data(c);
return b ? b->window : (HWND)NULL;
}
/*******************************
* SETTING OPTIONS *
*******************************/
int
rlc_copy_output_to_debug_output(int new)
{ int old = _rlc_copy_output_to_debug_output;
_rlc_copy_output_to_debug_output = new;
return old;
}
RlcUpdateHook
rlc_update_hook(RlcUpdateHook new)
{ RlcUpdateHook old = _rlc_update_hook;
_rlc_update_hook = new;
return old;
}
RlcTimerHook
rlc_timer_hook(RlcTimerHook new)
{ RlcTimerHook old = _rlc_timer_hook;
_rlc_timer_hook = new;
return old;
}
RlcRenderHook
rlc_render_hook(RlcRenderHook new)
{ RlcRenderHook old = _rlc_render_hook;
_rlc_render_hook = new;
return old;
}
RlcRenderAllHook
rlc_render_all_hook(RlcRenderAllHook new)
{ RlcRenderAllHook old = _rlc_render_all_hook;
_rlc_render_all_hook = new;
return old;
}
RlcInterruptHook
rlc_interrupt_hook(RlcInterruptHook new)
{ RlcInterruptHook old = _rlc_interrupt_hook;
_rlc_interrupt_hook = new;
return old;
}
RlcResizeHook
rlc_resize_hook(RlcResizeHook new)
{ RlcResizeHook old = _rlc_resize_hook;
_rlc_resize_hook = new;
return old;
}
RlcMenuHook
rlc_menu_hook(RlcMenuHook new)
{ RlcMenuHook old = _rlc_menu_hook;
_rlc_menu_hook = new;
return old;
}
RlcMessageHook
rlc_message_hook(RlcMessageHook new)
{ RlcMessageHook old = _rlc_message_hook;
_rlc_message_hook = new;
return old;
}
int
rlc_set(rlc_console c, int what, uintptr_t data, RlcFreeDataHook hook)
{ RlcData b = rlc_get_data(c);
switch(what)
{ default:
if ( what >= RLC_VALUE(0) &&
what <= RLC_VALUE(MAX_USER_VALUES) )
{ b->values[what-RLC_VALUE(0)].data = data;
b->values[what-RLC_VALUE(0)].hook = hook;
return TRUE;
}
return FALSE;
}
}
int
rlc_get(rlc_console c, int what, uintptr_t *data)
{ RlcData b = (RlcData)c;
if ( !b )
return FALSE;
switch(what)
{ case RLC_APPLICATION_THREAD:
*data = (uintptr_t)b->application_thread;
return TRUE;
case RLC_APPLICATION_THREAD_ID:
*data = (uintptr_t)b->application_thread_id;
return TRUE;
default:
if ( what >= RLC_VALUE(0) &&
what <= RLC_VALUE(MAX_USER_VALUES) )
{ *data = b->values[what-RLC_VALUE(0)].data;
return TRUE;
}
return FALSE;
}
}
static void
free_user_data(RlcData b)
{ user_data *d = b->values;
int i;
for(i=0; i<MAX_USER_VALUES; i++, d++)
{ RlcFreeDataHook hook;
if ( (hook=d->hook) )
{ uintptr_t data = d->data;
d->hook = NULL;
d->data = 0L;
(*hook)(data);
}
}
}
/*******************************
* UTIL *
*******************************/
static void
noMemory()
{ MessageBox(NULL, _T("Not enough memory"), _T("Console"), MB_OK|MB_TASKMODAL);
ExitProcess(1);
}
void *
rlc_malloc(size_t size)
{ void *ptr = malloc(size);
if ( !ptr && size > 0 )
noMemory();
#ifdef _DEBUG
memset(ptr, 0xbf, size);
#endif
return ptr;
}
void *
rlc_realloc(void *ptr, size_t size)
{ void *ptr2 = realloc(ptr, size);
if ( !ptr2 && size > 0 )
noMemory();
return ptr2;
}
void
rlc_free(void *ptr)
{ free(ptr);
}
#ifndef initHeapDebug
/*******************************
* DEBUG *
*******************************/
static void
initHeapDebug(void)
{ int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
if ( !(tmpFlag & _CRTDBG_CHECK_ALWAYS_DF) )
{ /*MessageBox(NULL,
"setting malloc() debugging",
"SWI-Prolog console",
MB_OK|MB_TASKMODAL);*/
tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;
_CrtSetDbgFlag(tmpFlag);
} else
{
/*MessageBox(NULL,
"malloc() debugging lready set",
"SWI-Prolog console",
MB_OK|MB_TASKMODAL);*/
}
}
#endif /*initHeapDebug*/
#ifdef _DEBUG
static void
Dprintf(const TCHAR *fmt, ...)
{ TCHAR buf[1024];
va_list args;
va_start(args, fmt);
vswprintf(buf, sizeof(buf)/sizeof(TCHAR), fmt, args);
va_end(args);
OutputDebugString(buf);
}
static void
Dprint_lines(RlcData b, int from, int to)
{ TCHAR buf[1024];
for( ; ; from = NextLine(b, from))
{ TextLine tl = &b->lines[from];
memcpy(buf, tl->text, tl->size);
buf[tl->size] = EOS;
Dprintf(_T("%03d: (0x%08x) \"%s\"\n"), from, tl->text, buf);
if ( from == to )
break;
}
}
#endif
|
{
"pile_set_name": "Github"
}
|
<?php
if (!is_callable('random_int')) {
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2018 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Fetch a random integer between $min and $max inclusive
*
* @param int $min
* @param int $max
*
* @throws Exception
*
* @return int
*/
function random_int($min, $max)
{
/**
* Type and input logic checks
*
* If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX)
* (non-inclusive), it will sanely cast it to an int. If you it's equal to
* ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer. Floats
* lose precision, so the <= and => operators might accidentally let a float
* through.
*/
try {
/** @var int $min */
$min = RandomCompat_intval($min);
} catch (TypeError $ex) {
throw new TypeError(
'random_int(): $min must be an integer'
);
}
try {
/** @var int $max */
$max = RandomCompat_intval($max);
} catch (TypeError $ex) {
throw new TypeError(
'random_int(): $max must be an integer'
);
}
/**
* Now that we've verified our weak typing system has given us an integer,
* let's validate the logic then we can move forward with generating random
* integers along a given range.
*/
if ($min > $max) {
throw new Error(
'Minimum value must be less than or equal to the maximum value'
);
}
if ($max === $min) {
return (int) $min;
}
/**
* Initialize variables to 0
*
* We want to store:
* $bytes => the number of random bytes we need
* $mask => an integer bitmask (for use with the &) operator
* so we can minimize the number of discards
*/
$attempts = $bits = $bytes = $mask = $valueShift = 0;
/** @var int $attempts */
/** @var int $bits */
/** @var int $bytes */
/** @var int $mask */
/** @var int $valueShift */
/**
* At this point, $range is a positive number greater than 0. It might
* overflow, however, if $max - $min > PHP_INT_MAX. PHP will cast it to
* a float and we will lose some precision.
*
* @var int|float $range
*/
$range = $max - $min;
/**
* Test for integer overflow:
*/
if (!is_int($range)) {
/**
* Still safely calculate wider ranges.
* Provided by @CodesInChaos, @oittaa
*
* @ref https://gist.github.com/CodesInChaos/03f9ea0b58e8b2b8d435
*
* We use ~0 as a mask in this case because it generates all 1s
*
* @ref https://eval.in/400356 (32-bit)
* @ref http://3v4l.org/XX9r5 (64-bit)
*/
$bytes = PHP_INT_SIZE;
/** @var int $mask */
$mask = ~0;
} else {
/**
* $bits is effectively ceil(log($range, 2)) without dealing with
* type juggling
*/
while ($range > 0) {
if ($bits % 8 === 0) {
++$bytes;
}
++$bits;
$range >>= 1;
/** @var int $mask */
$mask = $mask << 1 | 1;
}
$valueShift = $min;
}
/** @var int $val */
$val = 0;
/**
* Now that we have our parameters set up, let's begin generating
* random integers until one falls between $min and $max
*/
/** @psalm-suppress RedundantCondition */
do {
/**
* The rejection probability is at most 0.5, so this corresponds
* to a failure probability of 2^-128 for a working RNG
*/
if ($attempts > 128) {
throw new Exception(
'random_int: RNG is broken - too many rejections'
);
}
/**
* Let's grab the necessary number of random bytes
*/
$randomByteString = random_bytes($bytes);
/**
* Let's turn $randomByteString into an integer
*
* This uses bitwise operators (<< and |) to build an integer
* out of the values extracted from ord()
*
* Example: [9F] | [6D] | [32] | [0C] =>
* 159 + 27904 + 3276800 + 201326592 =>
* 204631455
*/
$val &= 0;
for ($i = 0; $i < $bytes; ++$i) {
$val |= ord($randomByteString[$i]) << ($i * 8);
}
/** @var int $val */
/**
* Apply mask
*/
$val &= $mask;
$val += $valueShift;
++$attempts;
/**
* If $val overflows to a floating point number,
* ... or is larger than $max,
* ... or smaller than $min,
* then try again.
*/
} while (!is_int($val) || $val > $max || $val < $min);
return (int) $val;
}
}
|
{
"pile_set_name": "Github"
}
|
#
# Copyright (c) 2017-2020 the rbfx project.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
add_library(CLI11 INTERFACE)
target_include_directories(CLI11
INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
)
install (DIRECTORY include/ DESTINATION ${DEST_THIRDPARTY_HEADERS_DIR}/ FILES_MATCHING PATTERN *.hpp)
if (NOT URHO3D_MERGE_STATIC_LIBS)
install(TARGETS CLI11 EXPORT Urho3D ARCHIVE DESTINATION ${DEST_ARCHIVE_DIR_CONFIG})
endif ()
|
{
"pile_set_name": "Github"
}
|
/***************************************************************************
* ARPHeader.h -- The ARPHeader Class represents an ARP packet. It *
* contains methods to set any header field. In general, these methods do *
* error checkings and byte order conversion. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2019 Insecure.Com LLC ("The Nmap *
* Project"). Nmap is also a registered trademark of the Nmap Project. *
* This program is free software; you may redistribute and/or modify it *
* under the terms of the GNU General Public License as published by the *
* Free Software Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE *
* CLARIFICATIONS AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your *
* right to use, modify, and redistribute this software under certain *
* conditions. If you wish to embed Nmap technology into proprietary *
* software, we sell alternative licenses (contact sales@nmap.com). *
* Dozens of software vendors already license Nmap technology such as *
* host discovery, port scanning, OS detection, version detection, and *
* the Nmap Scripting Engine. *
* *
* Note that the GPL places important restrictions on "derivative works", *
* yet it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we interpret that term as broadly as copyright law *
* allows. For example, we consider an application to constitute a *
* derivative work for the purpose of this license if it does any of the *
* following with any software or content covered by this license *
* ("Covered Software"): *
* *
* o Integrates source code from Covered Software. *
* *
* o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
* or nmap-service-probes. *
* *
* o Is designed specifically to execute Covered Software and parse the *
* results (as opposed to typical shell or execution-menu apps, which will *
* execute anything you tell them to). *
* *
* o Includes Covered Software in a proprietary executable installer. The *
* installers produced by InstallShield are an example of this. Including *
* Nmap with other software in compressed or archival form does not *
* trigger this provision, provided appropriate open source decompression *
* or de-archiving software is widely available for no charge. For the *
* purposes of this license, an installer is considered to include Covered *
* Software even if it actually retrieves a copy of Covered Software from *
* another source during runtime (such as by downloading it from the *
* Internet). *
* *
* o Links (statically or dynamically) to a library which does any of the *
* above. *
* *
* o Executes a helper program, module, or script to do any of the above. *
* *
* This list is not exclusive, but is meant to clarify our interpretation *
* of derived works with some common examples. Other people may interpret *
* the plain GPL differently, so we consider this a special exception to *
* the GPL that we apply to Covered Software. Works which meet any of *
* these conditions must conform to all of the terms of this license, *
* particularly including the GPL Section 3 requirements of providing *
* source code and allowing free redistribution of the work as a whole. *
* *
* As another special exception to the GPL terms, the Nmap Project grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. *
* *
* The Nmap Project has permission to redistribute Npcap, a packet *
* capturing driver and library for the Microsoft Windows platform. *
* Npcap is a separate work with it's own license rather than this Nmap *
* license. Since the Npcap license does not permit redistribution *
* without special permission, our Nmap Windows binary packages which *
* contain Npcap may not be redistributed without special permission. *
* *
* Any redistribution of Covered Software, including any derived works, *
* must obey and carry forward all of the terms of this license, including *
* obeying all GPL rules and restrictions. For example, source code of *
* the whole work must be provided and free redistribution must be *
* allowed. All GPL references to "this License", are to be treated as *
* including the terms and conditions of this license text as well. *
* *
* Because this license imposes special exceptions to the GPL, Covered *
* Work may not be combined (even as part of a larger work) with plain GPL *
* software. The terms, conditions, and exceptions of this license must *
* be included as well. This license is incompatible with some other open *
* source licenses as well. In some cases we can relicense portions of *
* Nmap or grant special permissions to use it in other open source *
* software. Please contact fyodor@nmap.org with any such requests. *
* Similarly, we don't incorporate incompatible open source software into *
* Covered Software without special permission from the copyright holders. *
* *
* If you have any questions about the licensing restrictions on using *
* Nmap in other works, we are happy to help. As mentioned above, we also *
* offer an alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing support and updates. They also fund the continued *
* development of Nmap. Please email sales@nmap.com for further *
* information. *
* *
* If you have received a written license agreement or contract for *
* Covered Software stating terms other than these, you may choose to use *
* and redistribute Covered Software under those terms instead of these. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes. *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to the dev@nmap.org mailing list for possible incorporation into the *
* main distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, or checking them into the Nmap *
* source code repository, it is understood (unless you specify *
* otherwise) that you are offering the Nmap Project the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because *
* the inability to relicense code has caused devastating problems for *
* other Free Software projects (such as KDE and NASM). We also *
* occasionally relicense the code to third parties as discussed above. *
* If you wish to specify special license conditions of your *
* contributions, just say so when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Nmap *
* license file for more details (it's in a COPYING file included with *
* Nmap, and also available from https://svn.nmap.org/nmap/COPYING) *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef __ARPHEADER_H__
#define __ARPHEADER_H__ 1
#include "NetworkLayerElement.h"
/* Lengths */
#define ARP_HEADER_LEN 28
#define IPv4_ADDRESS_LEN 4
#define ETH_ADDRESS_LEN 6
/* Hardware Types */
#define HDR_RESERVED 0 /* [RFC5494] */
#define HDR_ETH10MB 1 /* Ethernet (10Mb) */
#define HDR_ETH3MB 2 /* Experimental Ethernet (3Mb) */
#define HDR_AX25 3 /* Amateur Radio AX.25 */
#define HDR_PRONET_TR 4 /* Proteon ProNET Token Ring */
#define HDR_CHAOS 5 /* Chaos */
#define HDR_IEEE802 6 /* IEEE 802 Networks */
#define HDR_ARCNET 7 /* ARCNET [RFC1201] */
#define HDR_HYPERCHANNEL 8 /* Hyperchannel */
#define HDR_LANSTAR 9 /* Lanstar */
#define HDR_AUTONET 10 /* Autonet Short Address */
#define HDR_LOCALTALK 11 /* LocalTalk */
#define HDR_LOCALNET 12 /* LocalNet (IBM PCNet or SYTEK LocalNET) */
#define HDR_ULTRALINK 13 /* Ultra link */
#define HDR_SMDS 14 /* SMDS */
#define HDR_FRAMERELAY 15 /* Frame Relay */
#define HDR_ATM 16 /* Asynchronous Transmission Mode (ATM) */
#define HDR_HDLC 17 /* HDLC */
#define HDR_FIBRE 18 /* Fibre Channel [RFC4338] */
#define HDR_ATMb 19 /* Asynchronous Transmission Mode (ATM) */
#define HDR_SERIAL 20 /* Serial Line */
#define HDR_ATMc 21 /* Asynchronous Transmission Mode [RFC2225] */
#define HDR_MILSTD 22 /* MIL-STD-188-220 */
#define HDR_METRICOM 23 /* Metricom */
#define HDR_IEEE1394 24 /* IEEE 1394.199 */
#define HDR_MAPOS 25 /* MAPOS [RFC2176] */
#define HDR_TWINAXIAL 26 /* Twinaxial */
#define HDR_EUI64 27 /* EUI-64 */
#define HDR_HIPARP 28 /* HIPARP */
#define HDR_ISO7816 29 /* IP and ARP over ISO 7816-3 */
#define HDR_ARPSEC 30 /* ARPSec */
#define HDR_IPSEC 31 /* IPsec tunnel */
#define HDR_INFINIBAND 32 /* InfiniBand (TM) */
#define HDR_TIA102 33 /* TIA-102 Project 25 Common Air Interface */
#define HDR_WIEGAND 34 /* Wiegand Interface */
#define HDR_PUREIP 35 /* Pure IP */
#define HDR_HW_EXP1 36 /* HW_EXP1 [RFC5494] */
#define HDR_HW_EXP2 37 /* HW_EXP2 [RFC5494] */
/* Operation Codes */
#define OP_ARP_REQUEST 1 /* ARP Request */
#define OP_ARP_REPLY 2 /* ARP Reply */
#define OP_RARP_REQUEST 3 /* Reverse ARP Request */
#define OP_RARP_REPLY 4 /* Reverse ARP Reply */
#define OP_DRARP_REQUEST 5 /* DRARP-Request */
#define OP_DRARP_REPLY 6 /* DRARP-Reply */
#define OP_DRARP_ERROR 7 /* DRARP-Error */
#define OP_INARP_REQUEST 8 /* InARP-Request */
#define OP_INARP_REPLY 9 /* InARP-Reply */
#define OP_ARPNAK 10 /* ARP-NAK */
#define OP_MARS_REQUEST 11 /* MARS-Request */
#define OP_MARS_MULTI 12 /* MARS-Multi */
#define OP_MARS_MSERV 13 /* MARS-MServ */
#define OP_MARS_JOIN 14 /* MARS-Join */
#define OP_MARS_LEAVE 15 /* MARS-Leave */
#define OP_MARS_NAK 16 /* MARS-NAK */
#define OP_MARS_UNSERV 17 /* MARS-Unserv */
#define OP_MARS_SJOIN 18 /* MARS-SJoin */
#define OP_MARS_SLEAVE 19 /* MARS-SLeave */
#define OP_MARS_GL_REQ 20 /* MARS-Grouplist-Request */
#define OP_MARS_GL_REP 21 /* MARS-Grouplist-Reply */
#define OP_MARS_REDIR_MAP 22 /* MARS-Redirect-Map */
#define OP_MAPOS_UNARP 23 /* MAPOS-UNARP [RFC2176] */
#define OP_EXP1 24 /* OP_EXP1 [RFC5494] */
#define OP_EXP2 25 /* OP_EXP2 [RFC5494] */
#define OP_RESERVED 65535 /* Reserved [RFC5494] */
/* TODO @todo: getTargetIP() and getSenderIP() should either
* return struct in_addr or IPAddress but not u32. */
class ARPHeader : public NetworkLayerElement {
private:
struct nping_arp_hdr{
u16 ar_hrd; /* Hardware Type. */
u16 ar_pro; /* Protocol Type. */
u8 ar_hln; /* Hardware Address Length. */
u8 ar_pln; /* Protocol Address Length. */
u16 ar_op; /* Operation Code. */
u8 data[20];
// Cannot use these because the four-flushing alignment screws up
// everything. I miss ANSI C.
//u8 ar_sha[6]; /* Sender Hardware Address. */
//u32 ar_sip; /* Sender Protocol Address (IPv4 address). */
//u8 ar_tha[6]; /* Target Hardware Address. */
//u32 ar_tip; /* Target Protocol Address (IPv4 address). */
}__attribute__((__packed__));
typedef struct nping_arp_hdr nping_arp_hdr_t;
nping_arp_hdr_t h;
public:
/* Misc */
ARPHeader();
~ARPHeader();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
/* Hardware Type */
int setHardwareType(u16 t);
int setHardwareType();
u16 getHardwareType();
/* Protocol Type */
int setProtocolType(u16 t);
int setProtocolType();
u16 getProtocolType();
/* Hardware Address Length */
int setHwAddrLen(u8 v);
int setHwAddrLen();
u8 getHwAddrLen();
/* Hardware Address Length */
int setProtoAddrLen(u8 v);
int setProtoAddrLen();
u8 getProtoAddrLen();
/* Operation Code */
int setOpCode(u16 c);
u16 getOpCode();
/* Sender Hardware Address */
int setSenderMAC(const u8 *m);
u8 *getSenderMAC();
/* Sender Protocol address */
int setSenderIP(struct in_addr i);
u32 getSenderIP();
/* Target Hardware Address */
int setTargetMAC(u8 *m);
u8 *getTargetMAC();
/* Target Protocol Address */
int setTargetIP(struct in_addr i);
u32 getTargetIP();
}; /* End of class ARPHeader */
#endif /* __ARPHEADER_H__ */
|
{
"pile_set_name": "Github"
}
|
/* Part of SWI-Prolog
Author: Jan Wielemaker
E-mail: J.Wielemaker@vu.nl
WWW: http://www.swi-prolog.org
Copyright (c) 2003, University of Amsterdam
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
:- module(thread_create,
[ thread_create/0,
thread_create/1
]).
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This simple test verifies creation and destruction of threads. There
appears to be a HUGE difference in speed between platforms in the
elapsed time it takes to get this test done, so first we try to figure
out how fast it is about.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
thread_create :-
elapsed_time(thread_create(10), T),
( T > 0
-> Times is min(1000, round(10*(5/T)))
; Times = 1000
),
thread_create(Times).
thread_create(Times) :-
forall(between(1, Times, _), test).
elapsed_time(G, T) :-
get_time(T0),
G,
get_time(T1),
T is T1 - T0.
test :-
thread_create(client, Id, []),
thread_join(Id, true).
client.
|
{
"pile_set_name": "Github"
}
|
/**
******************************************************************************
* @file stm32f4xx_hal.c
* @author MCD Application Team
* @version V1.7.0
* @date 17-February-2017
* @brief HAL module driver.
* This is the common part of the HAL initialization
*
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
The common HAL driver contains a set of generic and common APIs that can be
used by the PPP peripheral drivers and the user to start using the HAL.
[..]
The HAL contains two APIs' categories:
(+) Common HAL APIs
(+) Services HAL APIs
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
/** @addtogroup STM32F4xx_HAL_Driver
* @{
*/
/** @defgroup HAL HAL
* @brief HAL module driver.
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup HAL_Private_Constants
* @{
*/
/**
* @brief STM32F4xx HAL Driver version number V1.5.0
*/
#define __STM32F4xx_HAL_VERSION_MAIN (0x01U) /*!< [31:24] main version */
#define __STM32F4xx_HAL_VERSION_SUB1 (0x05U) /*!< [23:16] sub1 version */
#define __STM32F4xx_HAL_VERSION_SUB2 (0x00U) /*!< [15:8] sub2 version */
#define __STM32F4xx_HAL_VERSION_RC (0x00U) /*!< [7:0] release candidate */
#define __STM32F4xx_HAL_VERSION ((__STM32F4xx_HAL_VERSION_MAIN << 24U)\
|(__STM32F4xx_HAL_VERSION_SUB1 << 16U)\
|(__STM32F4xx_HAL_VERSION_SUB2 << 8U )\
|(__STM32F4xx_HAL_VERSION_RC))
#define IDCODE_DEVID_MASK 0x00000FFFU
/* ------------ RCC registers bit address in the alias region ----------- */
#define SYSCFG_OFFSET (SYSCFG_BASE - PERIPH_BASE)
/* --- MEMRMP Register ---*/
/* Alias word address of UFB_MODE bit */
#define MEMRMP_OFFSET SYSCFG_OFFSET
#define UFB_MODE_BIT_NUMBER POSITION_VAL(SYSCFG_MEMRMP_UFB_MODE)
#define UFB_MODE_BB (uint32_t)(PERIPH_BB_BASE + (MEMRMP_OFFSET * 32U) + (UFB_MODE_BIT_NUMBER * 4U))
/* --- CMPCR Register ---*/
/* Alias word address of CMP_PD bit */
#define CMPCR_OFFSET (SYSCFG_OFFSET + 0x20U)
#define CMP_PD_BIT_NUMBER POSITION_VAL(SYSCFG_CMPCR_CMP_PD)
#define CMPCR_CMP_PD_BB (uint32_t)(PERIPH_BB_BASE + (CMPCR_OFFSET * 32U) + (CMP_PD_BIT_NUMBER * 4U))
/* --- MCHDLYCR Register ---*/
/* Alias word address of BSCKSEL bit */
#define MCHDLYCR_OFFSET (SYSCFG_OFFSET + 0x30U)
#define BSCKSEL_BIT_NUMBER POSITION_VAL(SYSCFG_MCHDLYCR_BSCKSEL)
#define MCHDLYCR_BSCKSEL_BB (uint32_t)(PERIPH_BB_BASE + (MCHDLYCR_OFFSET * 32U) + (BSCKSEL_BIT_NUMBER * 4U))
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/** @addtogroup HAL_Private_Variables
* @{
*/
__IO uint32_t uwTick;
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup HAL_Exported_Functions HAL Exported Functions
* @{
*/
/** @defgroup HAL_Exported_Functions_Group1 Initialization and de-initialization Functions
* @brief Initialization and de-initialization functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Initializes the Flash interface the NVIC allocation and initial clock
configuration. It initializes the systick also when timeout is needed
and the backup domain when enabled.
(+) de-Initializes common part of the HAL
(+) Configure The time base source to have 1ms time base with a dedicated
Tick interrupt priority.
(++) Systick timer is used by default as source of time base, but user
can eventually implement his proper time base source (a general purpose
timer for example or other time source), keeping in mind that Time base
duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and
handled in milliseconds basis.
(++) Time base configuration function (HAL_InitTick ()) is called automatically
at the beginning of the program after reset by HAL_Init() or at any time
when clock is configured, by HAL_RCC_ClockConfig().
(++) Source of time base is configured to generate interrupts at regular
time intervals. Care must be taken if HAL_Delay() is called from a
peripheral ISR process, the Tick interrupt line must have higher priority
(numerically lower) than the peripheral interrupt. Otherwise the caller
ISR process will be blocked.
(++) functions affecting time base configurations are declared as __weak
to make override possible in case of other implementations in user file.
@endverbatim
* @{
*/
/**
* @brief This function is used to initialize the HAL Library; it must be the first
* instruction to be executed in the main program (before to call any other
* HAL function), it performs the following:
* Configure the Flash prefetch, instruction and Data caches.
* Configures the SysTick to generate an interrupt each 1 millisecond,
* which is clocked by the HSI (at this stage, the clock is not yet
* configured and thus the system is running from the internal HSI at 16 MHz).
* Set NVIC Group Priority to 4.
* Calls the HAL_MspInit() callback function defined in user file
* "stm32f4xx_hal_msp.c" to do the global low level hardware initialization
*
* @note SysTick is used as time base for the HAL_Delay() function, the application
* need to ensure that the SysTick time base is always set to 1 millisecond
* to have correct HAL operation.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_Init(void)
{
/* Configure Flash prefetch, Instruction cache, Data cache */
#if (INSTRUCTION_CACHE_ENABLE != 0U)
__HAL_FLASH_INSTRUCTION_CACHE_ENABLE();
#endif /* INSTRUCTION_CACHE_ENABLE */
#if (DATA_CACHE_ENABLE != 0U)
__HAL_FLASH_DATA_CACHE_ENABLE();
#endif /* DATA_CACHE_ENABLE */
#if (PREFETCH_ENABLE != 0U)
__HAL_FLASH_PREFETCH_BUFFER_ENABLE();
#endif /* PREFETCH_ENABLE */
/* Set Interrupt Group Priority */
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
/* Use systick as time base source and configure 1ms tick (default clock after Reset is HSI) */
HAL_InitTick(TICK_INT_PRIORITY);
/* Init the low level hardware */
HAL_MspInit();
/* Return function status */
return HAL_OK;
}
/**
* @brief This function de-Initializes common part of the HAL and stops the systick.
* This function is optional.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DeInit(void)
{
/* Reset of all peripherals */
__HAL_RCC_APB1_FORCE_RESET();
__HAL_RCC_APB1_RELEASE_RESET();
__HAL_RCC_APB2_FORCE_RESET();
__HAL_RCC_APB2_RELEASE_RESET();
__HAL_RCC_AHB1_FORCE_RESET();
__HAL_RCC_AHB1_RELEASE_RESET();
__HAL_RCC_AHB2_FORCE_RESET();
__HAL_RCC_AHB2_RELEASE_RESET();
__HAL_RCC_AHB3_FORCE_RESET();
__HAL_RCC_AHB3_RELEASE_RESET();
/* De-Init the low level hardware */
HAL_MspDeInit();
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the MSP.
* @retval None
*/
__weak void HAL_MspInit(void)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_MspInit could be implemented in the user file
*/
}
/**
* @brief DeInitializes the MSP.
* @retval None
*/
__weak void HAL_MspDeInit(void)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_MspDeInit could be implemented in the user file
*/
}
/**
* @brief This function configures the source of the time base.
* The time source is configured to have 1ms time base with a dedicated
* Tick interrupt priority.
* @note This function is called automatically at the beginning of program after
* reset by HAL_Init() or at any time when clock is reconfigured by HAL_RCC_ClockConfig().
* @note In the default implementation, SysTick timer is the source of time base.
* It is used to generate interrupts at regular time intervals.
* Care must be taken if HAL_Delay() is called from a peripheral ISR process,
* The the SysTick interrupt must have higher priority (numerically lower)
* than the peripheral interrupt. Otherwise the caller ISR process will be blocked.
* The function is declared as __weak to be overwritten in case of other
* implementation in user file.
* @param TickPriority: Tick interrupt priority.
* @retval HAL status
*/
__weak HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
{
/*Configure the SysTick to have interrupt in 1ms time basis*/
HAL_SYSTICK_Config(SystemCoreClock/1000U);
/*Configure the SysTick IRQ priority */
HAL_NVIC_SetPriority(SysTick_IRQn, TickPriority ,0U);
/* Return function status */
return HAL_OK;
}
/**
* @}
*/
/** @defgroup HAL_Exported_Functions_Group2 HAL Control functions
* @brief HAL Control functions
*
@verbatim
===============================================================================
##### HAL Control functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Provide a tick value in millisecond
(+) Provide a blocking delay in millisecond
(+) Suspend the time base source interrupt
(+) Resume the time base source interrupt
(+) Get the HAL API driver version
(+) Get the device identifier
(+) Get the device revision identifier
(+) Enable/Disable Debug module during SLEEP mode
(+) Enable/Disable Debug module during STOP mode
(+) Enable/Disable Debug module during STANDBY mode
@endverbatim
* @{
*/
/**
* @brief This function is called to increment a global variable "uwTick"
* used as application time base.
* @note In the default implementation, this variable is incremented each 1ms
* in Systick ISR.
* @note This function is declared as __weak to be overwritten in case of other
* implementations in user file.
* @retval None
*/
__weak void HAL_IncTick(void)
{
uwTick++;
}
/**
* @brief Provides a tick value in millisecond.
* @note This function is declared as __weak to be overwritten in case of other
* implementations in user file.
* @retval tick value
*/
__weak uint32_t HAL_GetTick(void)
{
return uwTick;
}
/**
* @brief This function provides minimum delay (in milliseconds) based
* on variable incremented.
* @note In the default implementation , SysTick timer is the source of time base.
* It is used to generate interrupts at regular time intervals where uwTick
* is incremented.
* @note This function is declared as __weak to be overwritten in case of other
* implementations in user file.
* @param Delay: specifies the delay time length, in milliseconds.
* @retval None
*/
__weak void HAL_Delay(__IO uint32_t Delay)
{
uint32_t tickstart = HAL_GetTick();
uint32_t wait = Delay;
/* Add a period to guarantee minimum wait */
if (wait < HAL_MAX_DELAY)
{
wait++;
}
while((HAL_GetTick() - tickstart) < wait)
{
}
}
/**
* @brief Suspend Tick increment.
* @note In the default implementation , SysTick timer is the source of time base. It is
* used to generate interrupts at regular time intervals. Once HAL_SuspendTick()
* is called, the SysTick interrupt will be disabled and so Tick increment
* is suspended.
* @note This function is declared as __weak to be overwritten in case of other
* implementations in user file.
* @retval None
*/
__weak void HAL_SuspendTick(void)
{
/* Disable SysTick Interrupt */
SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk;
}
/**
* @brief Resume Tick increment.
* @note In the default implementation , SysTick timer is the source of time base. It is
* used to generate interrupts at regular time intervals. Once HAL_ResumeTick()
* is called, the SysTick interrupt will be enabled and so Tick increment
* is resumed.
* @note This function is declared as __weak to be overwritten in case of other
* implementations in user file.
* @retval None
*/
__weak void HAL_ResumeTick(void)
{
/* Enable SysTick Interrupt */
SysTick->CTRL |= SysTick_CTRL_TICKINT_Msk;
}
/**
* @brief Returns the HAL revision
* @retval version : 0xXYZR (8bits for each decimal, R for RC)
*/
uint32_t HAL_GetHalVersion(void)
{
return __STM32F4xx_HAL_VERSION;
}
/**
* @brief Returns the device revision identifier.
* @retval Device revision identifier
*/
uint32_t HAL_GetREVID(void)
{
return((DBGMCU->IDCODE) >> 16U);
}
/**
* @brief Returns the device identifier.
* @retval Device identifier
*/
uint32_t HAL_GetDEVID(void)
{
return((DBGMCU->IDCODE) & IDCODE_DEVID_MASK);
}
/**
* @brief Enable the Debug Module during SLEEP mode
* @retval None
*/
void HAL_DBGMCU_EnableDBGSleepMode(void)
{
SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP);
}
/**
* @brief Disable the Debug Module during SLEEP mode
* @retval None
*/
void HAL_DBGMCU_DisableDBGSleepMode(void)
{
CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP);
}
/**
* @brief Enable the Debug Module during STOP mode
* @retval None
*/
void HAL_DBGMCU_EnableDBGStopMode(void)
{
SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP);
}
/**
* @brief Disable the Debug Module during STOP mode
* @retval None
*/
void HAL_DBGMCU_DisableDBGStopMode(void)
{
CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP);
}
/**
* @brief Enable the Debug Module during STANDBY mode
* @retval None
*/
void HAL_DBGMCU_EnableDBGStandbyMode(void)
{
SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY);
}
/**
* @brief Disable the Debug Module during STANDBY mode
* @retval None
*/
void HAL_DBGMCU_DisableDBGStandbyMode(void)
{
CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY);
}
/**
* @brief Enables the I/O Compensation Cell.
* @note The I/O compensation cell can be used only when the device supply
* voltage ranges from 2.4 to 3.6 V.
* @retval None
*/
void HAL_EnableCompensationCell(void)
{
*(__IO uint32_t *)CMPCR_CMP_PD_BB = (uint32_t)ENABLE;
}
/**
* @brief Power-down the I/O Compensation Cell.
* @note The I/O compensation cell can be used only when the device supply
* voltage ranges from 2.4 to 3.6 V.
* @retval None
*/
void HAL_DisableCompensationCell(void)
{
*(__IO uint32_t *)CMPCR_CMP_PD_BB = (uint32_t)DISABLE;
}
/**
* @brief Return the unique device identifier (UID based on 96 bits)
* @param UID: pointer to 3 words array.
* @retval Device identifier
*/
void HAL_GetUID(uint32_t *UID)
{
UID[0] = (uint32_t)(READ_REG(*((uint32_t *)UID_BASE)));
UID[1] = (uint32_t)(READ_REG(*((uint32_t *)(UID_BASE + 4U))));
UID[2] = (uint32_t)(READ_REG(*((uint32_t *)(UID_BASE + 8U))));
}
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) ||\
defined(STM32F469xx) || defined(STM32F479xx)
/**
* @brief Enables the Internal FLASH Bank Swapping.
*
* @note This function can be used only for STM32F42xxx/43xxx devices.
*
* @note Flash Bank2 mapped at 0x08000000 (and aliased @0x00000000)
* and Flash Bank1 mapped at 0x08100000 (and aliased at 0x00100000)
*
* @retval None
*/
void HAL_EnableMemorySwappingBank(void)
{
*(__IO uint32_t *)UFB_MODE_BB = (uint32_t)ENABLE;
}
/**
* @brief Disables the Internal FLASH Bank Swapping.
*
* @note This function can be used only for STM32F42xxx/43xxx devices.
*
* @note The default state : Flash Bank1 mapped at 0x08000000 (and aliased @0x00000000)
* and Flash Bank2 mapped at 0x08100000 (and aliased at 0x00100000)
*
* @retval None
*/
void HAL_DisableMemorySwappingBank(void)
{
*(__IO uint32_t *)UFB_MODE_BB = (uint32_t)DISABLE;
}
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
{
"pile_set_name": "Github"
}
|
/**
* The MIT License
*
* Copyright (c) justanimate
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
import {
pow,
tau,
sin,
} from '../internal';
export const easeOutElastic = (n: number): number => {
if (!n || n === 1) {
return n;
}
let s, a = 0.1, p = 0.4;
if (!a || a < 1) {
a = 1;
s = p / 4;
}
else {
s = p * Math.asin(1 / a) / tau;
}
return (a * pow(2, -10 * n) * sin((n - s) * (tau) / p) + 1);
};
|
{
"pile_set_name": "Github"
}
|
//
// String+MD5.swift
// Kingfisher
//
// Created by Wei Wang on 18//25.
//
// Copyright (c) 2018 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CommonCrypto
extension String: KingfisherCompatible { }
extension KingfisherWrapper where Base == String {
var md5: String {
guard let data = base.data(using: .utf8) else {
return base
}
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
_ = data.withUnsafeBytes { bytes in
return CC_MD5(bytes, CC_LONG(data.count), &digest)
}
return digest.map { String(format: "%02x", $0) }.joined()
}
}
|
{
"pile_set_name": "Github"
}
|
=== Git в Bash
(((bash)))(((tab completion, bash)))(((shell prompts, bash)))
Если вы используете Bash, то можете задействовать некоторые из его фишек для облегчения работы с Git.
К слову, Git поставляется с плагинами для нескольких командных оболочек, но они выключены по умолчанию.
Для начала, скачайте файл `contrib/completion/git-completion.bash` из репозитория с исходным кодом Git.
Поместите его в укромное место -- например, в вашу домашнюю директорию -- и добавьте следующие строки в `.bashrc`:
[source,console]
-----
. ~/git-completion.bash
-----
Как только закончите с этим, перейдите в директорию с Git репозиторием и наберите:
[source,console]
----
$ git chec<tab>
----
…и Bash дополнит строку до `git checkout`.
Эта магия работает для всех Git команд, их параметров, удалённых репозиториев и имён ссылок там, где это возможно.
Возможно, вам также пригодится отображение информации о репозитории, расположенном в текущей директории.
Вы можете выводить сколь угодно сложную информацию, но обычно достаточно названия текущей ветки и статуса рабочей директории.
Чтобы снабдить строку приветствия этой информацией, скачайте файл `contrib/completion/git-prompt.sh` из репозитория с исходным кодом Git и добавьте примерно такие строки в `.bashrc`:
[source,console]
-----
. ~/git-prompt.sh
export GIT_PS1_SHOWDIRTYSTATE=1
export PS1='\w$(__git_ps1 " (%s)")\$ '
-----
Часть `\w` означает текущую рабочую директорию, `\$` -- индикатор суперпользователя (обычно `$` или `#`), а `__git_ps1 " (%s)"` вызывает функцию, объявленную в `git-prompt.sh`, с аргументом ` (%s)` -- строкой форматирования.
Теперь ваша строка приветствия будет похожа на эту, когда вы зайдёте в директорию с Git репозиторием:
.Кастомизированная строка приветствия `bash`
image::images/git-bash.png["Кастомизированная строка приветствия `bash`"]
Оба вышеперечисленных скрипта снабжены полезной документацией, загляните внутрь `git-completion.bash` и `git-prompt.sh` чтобы узнать больше.
|
{
"pile_set_name": "Github"
}
|
/*
==============================================================================
This file is part of the juce_core module of the JUCE library.
Copyright (c) 2015 - ROLI Ltd.
Permission to use, copy, modify, and/or distribute this software for any purpose with
or without fee is hereby granted, provided that the above copyright notice and this
permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
All other JUCE modules are covered by a dual GPL/commercial license, so if you are
using any other modules, be sure to check that you also comply with their license.
For more details, visit www.juce.com
==============================================================================
*/
#ifndef JUCE_LOGGER_H_INCLUDED
#define JUCE_LOGGER_H_INCLUDED
//==============================================================================
/**
Acts as an application-wide logging class.
A subclass of Logger can be created and passed into the Logger::setCurrentLogger
method and this will then be used by all calls to writeToLog.
The logger class also contains methods for writing messages to the debugger's
output stream.
@see FileLogger
*/
class JUCE_API Logger
{
public:
//==============================================================================
/** Destructor. */
virtual ~Logger();
//==============================================================================
/** Sets the current logging class to use.
Note that the object passed in will not be owned or deleted by the logger, so
the caller must make sure that it is not deleted while still being used.
A null pointer can be passed-in to disable any logging.
*/
static void JUCE_CALLTYPE setCurrentLogger (Logger* newLogger) noexcept;
/** Returns the current logger, or nullptr if none has been set. */
static Logger* getCurrentLogger() noexcept;
/** Writes a string to the current logger.
This will pass the string to the logger's logMessage() method if a logger
has been set.
@see logMessage
*/
static void JUCE_CALLTYPE writeToLog (const String& message);
//==============================================================================
/** Writes a message to the standard error stream.
This can be called directly, or by using the DBG() macro in
juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
*/
static void JUCE_CALLTYPE outputDebugString (const String& text);
protected:
//==============================================================================
Logger();
/** This is overloaded by subclasses to implement custom logging behaviour.
@see setCurrentLogger
*/
virtual void logMessage (const String& message) = 0;
private:
static Logger* currentLogger;
};
#endif // JUCE_LOGGER_H_INCLUDED
|
{
"pile_set_name": "Github"
}
|
------------------------------------------------------------------------------
-- --
-- GNAT2WHY COMPONENTS --
-- --
-- F L O W _ V I S I B I L I T Y --
-- --
-- B o d y --
-- --
-- Copyright (C) 2018-2020, Altran UK Limited --
-- --
-- gnat2why is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 3, or (at your option) any later --
-- version. gnat2why is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public --
-- License for more details. You should have received a copy of the GNU --
-- General Public License distributed with gnat2why; see file COPYING3. --
-- If not, go to http://www.gnu.org/licenses for a complete copy of the --
-- license. --
-- --
------------------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO;
with Common_Containers; use Common_Containers;
with Einfo; use Einfo;
with Flow_Refinement; use Flow_Refinement;
with Graphs;
with Nlists; use Nlists;
with Rtsfind; use Rtsfind;
with Sem_Aux; use Sem_Aux;
with Sem_Ch12; use Sem_Ch12;
with Sem_Util; use Sem_Util;
with SPARK_Util; use SPARK_Util;
with Sinfo; use Sinfo;
with Stand; use Stand;
package body Flow_Visibility is
----------------------------------------------------------------------------
-- Types
----------------------------------------------------------------------------
package Hierarchy_Info_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Entity_Id,
Element_Type => Hierarchy_Info_T,
Hash => Node_Hash,
Equivalent_Keys => "=",
"=" => "=");
type Edge_Kind is (Rule_Own,
Rule_Instance,
Rule_Up_Spec,
Rule_Down_Spec,
Rule_Up_Priv,
Rule_Up_Body);
function Hash (S : Flow_Scope) return Ada.Containers.Hash_Type;
package Scope_Graphs is new
Graphs (Vertex_Key => Flow_Scope,
Edge_Colours => Edge_Kind,
Null_Key => Null_Flow_Scope,
Key_Hash => Hash,
Test_Key => "=");
----------------------------------------------------------------------------
-- Local variables
----------------------------------------------------------------------------
function Standard_Scope return Flow_Scope is
(Ent => Standard_Standard, Part => Visible_Part);
-- ??? this should be a constant, but at the time of elaboration the
-- Standard_Standard is not yet defined.
Hierarchy_Info : Hierarchy_Info_Maps.Map;
Scope_Graph : Scope_Graphs.Graph := Scope_Graphs.Create;
Components : Scope_Graphs.Strongly_Connected_Components;
-- Pre-computed strongly connected components of the visibility graph for
-- quickly answering visibility queries.
----------------------------------------------------------------------------
-- Subprogram declarations
----------------------------------------------------------------------------
function Sanitize (S : Flow_Scope) return Flow_Scope is
(if Present (S) then S else Standard_Scope);
-- Convert between Null_Flow_Scope (which is used in the Flow_Refinement
-- package) to Standard_Scope (which is used here).
function Make_Info (N : Node_Id) return Hierarchy_Info_T;
function Is_Child (Info : Hierarchy_Info_T) return Boolean;
function Is_Nested (Info : Hierarchy_Info_T) return Boolean;
function Is_Instance (Info : Hierarchy_Info_T) return Boolean;
function Is_Instance_Child (Info : Hierarchy_Info_T) return Boolean;
-- Utility routines for the hierarchy data
procedure Print (G : Scope_Graphs.Graph);
-- Pretty-print visibility graph
procedure Print_Path (From, To : Flow_Scope);
pragma Unreferenced (Print_Path);
-- To be used from the debugger
generic
with procedure Process (N : Node_Id);
procedure Traverse_Compilation_Unit (Unit_Node : Node_Id);
-- Call Process on all declarations within compilation unit CU. Unlike the
-- standard frontend traversal, this one traverses into stubs; ??? it is
-- now similar to the generated globals traversal.
----------------------------------------------------------------------------
-- Subprogram bodies
----------------------------------------------------------------------------
-------------------------
-- Connect_Flow_Scopes --
-------------------------
procedure Connect_Flow_Scopes is
procedure Connect (E : Entity_Id; Info : Hierarchy_Info_T);
-------------
-- Connect --
-------------
procedure Connect (E : Entity_Id; Info : Hierarchy_Info_T) is
Spec_V : constant Scope_Graphs.Vertex_Id :=
Scope_Graph.Get_Vertex ((Ent => E, Part => Visible_Part));
Priv_V : constant Scope_Graphs.Vertex_Id :=
(if Info.Is_Package
then Scope_Graph.Get_Vertex ((Ent => E, Part => Private_Part))
else Scope_Graphs.Null_Vertex);
Body_V : constant Scope_Graphs.Vertex_Id :=
Scope_Graph.Get_Vertex ((Ent => E, Part => Body_Part));
-- Vertices for the visible (aka. "spec"), private and body parts
Rule : Edge_Kind;
-- Rule that causes an edge to be added; maintaining it as a global
-- variable is not elegant, but results in a cleaner code.
use type Scope_Graphs.Vertex_Id;
procedure Connect (Source, Target : Scope_Graphs.Vertex_Id)
with Pre => Source /= Scope_Graphs.Null_Vertex
and
Target /= Scope_Graphs.Null_Vertex
and
Source /= Target;
-- Add edge from Source to Target
-------------
-- Connect --
-------------
procedure Connect (Source, Target : Scope_Graphs.Vertex_Id) is
begin
pragma Assert (not Scope_Graph.Edge_Exists (Source, Target));
Scope_Graph.Add_Edge (Source, Target, Rule);
end Connect;
-- Start of processing for Connect
begin
----------------------------------------------------------------------
-- Create edges
----------------------------------------------------------------------
Rule := Rule_Own;
-- This rule is the "my own scope" rule, and is the most obvious form
-- of visibility.
if Info.Is_Package then
Connect (Body_V, Priv_V);
Connect (Priv_V, Spec_V);
else
Connect (Body_V, Spec_V);
end if;
----------------------------------------------------------------------
Rule := Rule_Instance;
-- This is the "generic" rule. It deals with the special upwards
-- visibility of generic instances. Instead of following the
-- normal rules for this we link all our parts to the template's
-- corresponding parts, since the template's position in the graph
-- determines our visibility, not the location of instantiation.
if Is_Instance (Info) then
if Is_Instance_Child (Info) then
Connect
(Spec_V,
Scope_Graph.Get_Vertex ((Ent => Info.Instance_Parent,
Part => Visible_Part)));
if Info.Is_Package then
Connect
(Priv_V,
Scope_Graph.Get_Vertex ((Ent => Info.Instance_Parent,
Part => Private_Part)));
end if;
else
Connect
(Spec_V,
Scope_Graph.Get_Vertex ((Ent => Info.Template,
Part => Visible_Part)));
-- Generic units acquire visibility from where they are
-- instantiated, so they can "see" subprograms used to
-- instantiate them (when instantiated, a formal subprogram
-- becomes a renaming). Same for formal packages.
--
-- ??? do something similar when Is_Instance_Child is True
Connect
(Spec_V,
Scope_Graph.Get_Vertex
(if Is_Nested (Info)
then Info.Container
else (Ent => Info.Parent,
Part => (if Info.Is_Private
then Private_Part
else Visible_Part))));
-- ??? The code for the target scope is repeated in rules
-- Rule_Up_Spec and Rule_Down_Spec; this should be refactored.
-- Visibility of the template's private part only matters if
-- the template itself is a child unit, but it is safe to
-- connect it in any case (and detecting which generic is a
-- child unit would require extra info in phase 2).
if Info.Is_Package then
Connect
(Priv_V,
Scope_Graph.Get_Vertex ((Ent => Info.Template,
Part => Private_Part)));
end if;
Connect
(Body_V,
Scope_Graph.Get_Vertex ((Ent => Info.Template,
Part => Body_Part)));
-- For generic subprograms instantiated in the wrapper packages
-- we need the visibility from the instantiated subprogram body
-- to the wrapper package body, as otherwise the
-- Subprogram_Refinement_Is_Visible says that the instantiated
-- generic subprogram body can't see its own refinement.
--
-- ??? wrapper packages were ignored in the design document,
-- probably this should be revisited.
--
-- ??? we need something similar for generic child subprograms
-- of generic parents (i.e. the Is_Instance_Child branch above)
if not Info.Is_Package then
Connect
(Body_V,
Scope_Graph.Get_Vertex (Body_Scope (Info.Container)));
end if;
end if;
end if;
----------------------------------------------------------------------
Rule := Rule_Up_Spec;
-- This rule deals with upwards visibility, i.e. adding a link to
-- the nearest "enclosing" scope. Generics are dealt with separately,
-- ??? except for generic child instantiations (they have visibility
-- of their parent's instantiation).
if not Is_Instance (Info) then
Connect
(Spec_V,
Scope_Graph.Get_Vertex
(if Is_Nested (Info)
then Info.Container
else (Ent => Info.Parent,
Part => (if Info.Is_Private
then Private_Part
else Visible_Part))));
end if;
----------------------------------------------------------------------
-- As mentioned before, instances break the chain so they need
-- special treatment, and the remaining three rules just add the
-- appropriate links. Note that although the last three are mutually
-- exclusive, any of them might be an instance.
----------------------------------------------------------------------
Rule := Rule_Down_Spec;
-- This rule deals with downwards visibility, i.e. contributing to
-- the visibility of the surrounding context. It is exactly the
-- inverse of Rule_Up_Spec, except there is no special treatment for
-- instances (since a scope does have visibility of the spec of
-- something instantiated inside it).
Connect
(Scope_Graph.Get_Vertex (if Is_Nested (Info)
then Info.Container
else (Ent => Info.Parent,
Part => (if Info.Is_Private
then Private_Part
else Visible_Part))),
Spec_V);
----------------------------------------------------------------------
Rule := Rule_Up_Priv;
-- This rule deals with upwards visibility for the private part of a
-- child package or subprogram. It doesn't apply to instances.
if Is_Child (Info)
and then not Is_Instance (Info)
then
Connect
((if Info.Is_Package
then Priv_V
else Body_V),
Scope_Graph.Get_Vertex ((Ent => Info.Parent,
Part => Private_Part)));
end if;
----------------------------------------------------------------------
Rule := Rule_Up_Body;
-- Finally, this rule deals with the upwards visibility for the body
-- of a nested package. A nested scope will have visibility of its
-- enclosing scope's body, since it is impossible to complete the
-- body anywhere else. Again, it doesn't apply to instances.
if Is_Nested (Info)
and then not Is_Instance (Info)
then
Connect
(Body_V,
Scope_Graph.Get_Vertex ((Ent => Info.Container.Ent,
Part => Body_Part)));
end if;
end Connect;
-- Start of processing for Connect_Flow_Scopes
begin
for C in Hierarchy_Info.Iterate loop
declare
E : Entity_Id renames Hierarchy_Info_Maps.Key (C);
Info : Hierarchy_Info_T renames Hierarchy_Info (C);
begin
Connect (E, Info);
end;
end loop;
-- Release memory to the provers
-- ??? Hierarchy_Info.Clear;
-- At this point we could compute a transitive closure, but that can
-- take huge amount of memory. This is because typically the visibility
-- graph has many vertices and all of them are connected to all the
-- enclosing scopes (up to Standard); however, the visibility paths
-- are short and can be quickly discovered.
-- In phase 1 we print the graph (if requested), but keep the hirarchy
-- info for writing it to the ALI file; in phase 2 we clear the info,
-- as it is no longer needed (while the graph is still needed for failed
-- check explanations).
if Gnat2Why_Args.Global_Gen_Mode then
if Gnat2Why_Args.Flow_Advanced_Debug then
Print (Scope_Graph);
end if;
else
Hierarchy_Info.Clear;
Hierarchy_Info.Reserve_Capacity (0);
end if;
Components := Scope_Graph.SCC;
-- Sanity check: all vertices should be now connected to Standard
declare
Standard : constant Scope_Graphs.Vertex_Id :=
Scope_Graph.Get_Vertex ((Ent => Standard_Standard,
Part => Visible_Part))
with Ghost;
use Scope_Graphs;
begin
pragma Assert
(for all V of Scope_Graph.Get_Collection (All_Vertices) =>
(if V /= Standard
then Scope_Graph.Edge_Exists (Components, V, Standard)));
end;
end Connect_Flow_Scopes;
----------
-- Hash --
----------
function Hash (S : Flow_Scope) return Ada.Containers.Hash_Type is
use type Ada.Containers.Hash_Type;
begin
-- Adding S.Part'Pos, which ranges from 0 to 3, should keep hash values
-- unique, because S.Ent values of different scopes are not that close
-- to each other.
return Node_Hash (S.Ent) + Declarative_Part'Pos (S.Part);
end Hash;
--------------
-- Is_Child --
--------------
function Is_Child (Info : Hierarchy_Info_T) return Boolean is
(Present (Info.Parent));
-----------------
-- Is_Instance --
-----------------
function Is_Instance (Info : Hierarchy_Info_T) return Boolean is
(Present (Info.Template));
-----------------------
-- Is_Instance_Child --
-----------------------
function Is_Instance_Child (Info : Hierarchy_Info_T) return Boolean is
(Present (Info.Instance_Parent));
---------------
-- Is_Nested --
---------------
function Is_Nested (Info : Hierarchy_Info_T) return Boolean is
(Present (Info.Container));
----------------
-- Is_Visible --
----------------
function Is_Visible
(Looking_From : Flow_Scope;
Looking_At : Flow_Scope)
return Boolean
is
begin
-- The visibility graph is not reflexive; we must explicitly check for
-- visibility between the same scopes.
return Looking_From = Looking_At
or else Scope_Graph.Edge_Exists
(Components,
Sanitize (Looking_From),
Sanitize (Looking_At));
end Is_Visible;
---------------
-- Make_Info --
---------------
function Make_Info (N : Node_Id) return Hierarchy_Info_T is
Def_E : constant Entity_Id := Defining_Entity (N);
E : constant Entity_Id :=
(if Nkind (N) = N_Private_Type_Declaration
then DIC_Procedure (Def_E)
elsif Nkind (N) = N_Full_Type_Declaration
then Invariant_Procedure (Def_E)
else Def_E);
Is_Package : Boolean;
Is_Private : Boolean;
Parent : Entity_Id;
Instance_Parent : Entity_Id;
Template : Entity_Id;
Container : Flow_Scope;
begin
-- Special Text_IO packages behave as nested within the Ada.Text_IO
-- (that is what Ada RM A.10.1 mandates), but in GNAT they are defined
-- as private generic children of Ada.Text_IO. We special-case them
-- according to what the Ada RM says.
if Ekind (E) in E_Package | E_Generic_Package then
Is_Package := True;
if Is_Child_Unit (E) then
if Is_Text_IO_Special_Package (E) then
Is_Private := False;
Parent := Empty;
else
Is_Private :=
Nkind (Atree.Parent (N)) = N_Compilation_Unit
and then
Private_Present (Atree.Parent (N));
Parent := Scope (E);
end if;
elsif Get_Flow_Scope (N) = Null_Flow_Scope then
Is_Private := False;
Parent := Standard_Standard;
else
Is_Private := False;
Parent := Empty;
end if;
else
pragma Assert (Ekind (E) in Entry_Kind
| E_Function
| E_Procedure
| E_Protected_Type
| E_Task_Type
| Generic_Subprogram_Kind);
Is_Package := False;
Is_Private :=
Is_Compilation_Unit (E)
and then
Private_Present (Enclosing_Comp_Unit_Node (E));
if Is_Compilation_Unit (E) then
if Ekind (E) in E_Function | E_Procedure
and then Is_Generic_Instance (E)
then
Parent := Empty;
else
Parent := Scope (E);
end if;
else
Parent := Empty;
end if;
end if;
if Is_Generic_Instance (E)
and then not Is_Wrapper_Package (E)
then
Template := Generic_Parent (Specification (N));
-- Deal with instances of child instances; this is based on frontend
-- Install_Parent_Private_Declarations.
if Is_Child_Unit (Template)
and then Is_Generic_Unit (Scope (Template))
then
declare
Child_Inst : constant Entity_Id :=
(if Ekind (E) = E_Package
then E
else Defining_Entity (Atree.Parent (Subprogram_Spec (E))));
-- If the child instance is a package, we can directly pass it
-- to Get_Unit_Instantiation_Node; when it is a subprogram, we
-- must get its wrapper package. Typically it is just the Scope
-- of E, except for instance-as-compilation-unit, where we need
-- to retrieve the wrapper package syntactically.
pragma Assert
(Ekind (E) = E_Package
or else
(Ekind (E) in E_Function | E_Procedure
and then Is_Wrapper_Package (Child_Inst)));
Inst_Node : constant Node_Id :=
Get_Unit_Instantiation_Node (Child_Inst);
begin
pragma Assert (Nkind (Inst_Node) in N_Generic_Instantiation);
-- The original frontend routine expects formal packages too,
-- but in the backend we only instantiations, because formal
-- packages have been expanded to renamings of instances.
pragma Assert (Nkind (Name (Inst_Node)) = N_Expanded_Name);
-- When analysing the generic parent body, frontend expects the
-- child to be named either as "P.C" (N_Expanded_Name) or "C"
-- (N_Identifier); when analysing its instance in the backend
-- we only see N_Expanded_Name.
Instance_Parent := Entity (Prefix (Name (Inst_Node)));
pragma Assert (Ekind (Instance_Parent) = E_Package);
if Present (Renamed_Entity (Instance_Parent)) then
Instance_Parent := Renamed_Entity (Instance_Parent);
pragma Assert (Ekind (Instance_Parent) = E_Package);
end if;
end;
else
Instance_Parent := Empty;
end if;
else
Template := Empty;
Instance_Parent := Empty;
end if;
if Is_Child_Unit (E)
and then Is_Package_Or_Generic_Package (E)
and then Is_Text_IO_Special_Package (E)
then
Container := (Ent => Scope (E), Part => Visible_Part);
else
Container := Get_Flow_Scope (N);
end if;
-------------------------------------------------------------------------
-- Invariant
--
-- This is intentonally a sequance of pragmas and not a Boolean-value
-- function, because with pragmas if one of the conditions fails, it
-- is easier to know which one.
-------------------------------------------------------------------------
pragma Assert (Present (Container) or else Present (Parent));
-- Everything is nested or else has a parent
pragma Assert (not (Is_Private and Present (Container)));
-- Being "private" can only apply to non-nested packages
pragma Assert (if Present (Template) then Is_Generic_Unit (Template));
-- Template, if present, is a generic unit
pragma Assert (if Present (Parent)
then Ekind (Parent) in E_Package | E_Generic_Package);
-- Parent, if present, must be a package or a generic package
-------------------------------------------------------------------------
return (Is_Package => Is_Package,
Is_Private => Is_Private,
Parent => Parent,
Instance_Parent => Instance_Parent,
Template => Template,
Container => Container);
end Make_Info;
-----------
-- Print --
-----------
procedure Print (G : Scope_Graphs.Graph)
is
use Scope_Graphs;
Show_Empty_Subprogram_Bodies : constant Boolean := False;
-- A debug flag fow showing/hiding subprograms with bo bodies (e.g. when
-- the body is in another compilation unit, especially in a predefined
-- one, like System; or when the subprogram is abstract). Those bodies
-- make the graph harder to read.
-- ??? perhaps we should not create vertices for those bodies in the
-- first place.
function NDI (G : Graph; V : Vertex_Id) return Node_Display_Info;
-- Pretty-printing for vertices in the dot output
function EDI
(G : Graph;
A : Vertex_Id;
B : Vertex_Id;
Marked : Boolean;
Colour : Edge_Kind) return Edge_Display_Info;
-- Pretty-printing for edges in the dot output
---------
-- NDI --
---------
function NDI (G : Graph; V : Vertex_Id) return Node_Display_Info
is
S : constant Flow_Scope := G.Get_Key (V);
Label : constant String :=
Full_Source_Name (S.Ent) &
(case S.Part is
when Visible_Part => " (Spec)",
when Private_Part => " (Priv)",
when Body_Part => " (Body)",
when Null_Part => raise Program_Error);
Show : Boolean;
begin
if S.Part = Body_Part
and then Ekind (S.Ent) in E_Function | E_Procedure
and then No (Subprogram_Body_Entity (S.Ent))
then
pragma Assert (G.In_Neighbour_Count (V) = 0);
Show := Show_Empty_Subprogram_Bodies;
else
Show := True;
end if;
return (Show => Show,
Shape => Shape_None,
Colour =>
To_Unbounded_String
(if S = Standard_Scope then "blue"
elsif Is_Generic_Unit (S.Ent) then "red"
else ""),
Fill_Colour => Null_Unbounded_String,
Label => To_Unbounded_String (Label));
end NDI;
---------
-- EDI --
---------
function EDI
(G : Graph;
A : Vertex_Id;
B : Vertex_Id;
Marked : Boolean;
Colour : Edge_Kind) return Edge_Display_Info
is
pragma Unreferenced (B, Marked, Colour);
S : constant Flow_Scope := G.Get_Key (A);
Show : Boolean;
begin
if Ekind (S.Ent) in E_Function | E_Procedure
and then S.Part = Body_Part
and then No (Subprogram_Body_Entity (S.Ent))
then
pragma Assert (G.In_Neighbour_Count (A) = 0);
Show := Show_Empty_Subprogram_Bodies;
else
Show := True;
end if;
return
(Show => Show,
Shape => Edge_Normal,
Colour => Null_Unbounded_String,
Label => Null_Unbounded_String);
-- ??? Label should reflect the Colour argument, but the current
-- names of the rules are too long and produce unreadable graphs.
end EDI;
Filename : constant String :=
Unique_Name (Unique_Main_Unit_Entity) & "_visibility";
-- Start of processing for Print
begin
G.Write_Pdf_File
(Filename => Filename,
Node_Info => NDI'Access,
Edge_Info => EDI'Access);
end Print;
----------------
-- Print_Path --
----------------
procedure Print_Path (From, To : Flow_Scope) is
Source : constant Scope_Graphs.Vertex_Id :=
Scope_Graph.Get_Vertex (Sanitize (From));
Target : constant Scope_Graphs.Vertex_Id :=
Scope_Graph.Get_Vertex (Sanitize (To));
procedure Is_Target
(V : Scope_Graphs.Vertex_Id;
Instruction : out Scope_Graphs.Traversal_Instruction);
procedure Print_Vertex (V : Scope_Graphs.Vertex_Id);
---------------
-- Is_Target --
---------------
procedure Is_Target
(V : Scope_Graphs.Vertex_Id;
Instruction : out Scope_Graphs.Traversal_Instruction)
is
use type Scope_Graphs.Vertex_Id;
begin
Instruction :=
(if V = Target
then Scope_Graphs.Found_Destination
else Scope_Graphs.Continue);
end Is_Target;
------------------
-- Print_Vertex --
------------------
procedure Print_Vertex (V : Scope_Graphs.Vertex_Id) is
S : constant Flow_Scope := Scope_Graph.Get_Key (V);
begin
-- Print_Flow_Scope (S);
-- ??? the above code produces no output in gdb; use Ada.Text_IO
if Present (S.Ent) then
Ada.Text_IO.Put_Line
(Full_Source_Name (S.Ent) &
" | " &
(case Declarative_Part'(S.Part) is
when Visible_Part => "spec",
when Private_Part => "priv",
when Body_Part => "body"));
else
Ada.Text_IO.Put_Line ("standard");
end if;
end Print_Vertex;
-- Start of processing for Print_Path
begin
Scope_Graphs.Shortest_Path
(G => Scope_Graph,
Start => Source,
Allow_Trivial => True,
Search => Is_Target'Access,
Step => Print_Vertex'Access);
end Print_Path;
--------------------------
-- Register_Flow_Scopes --
--------------------------
procedure Register_Flow_Scopes (Unit_Node : Node_Id) is
procedure Process_Scope_Declaration (N : Node_Id)
with Pre => Nkind (N) in N_Entry_Declaration
| N_Generic_Declaration
| N_Package_Declaration
| N_Protected_Type_Declaration
| N_Subprogram_Declaration
| N_Subprogram_Body_Stub
| N_Task_Type_Declaration
| N_Abstract_Subprogram_Declaration
or else (Nkind (N) = N_Subprogram_Body
and then Acts_As_Spec (N))
or else (Nkind (N) = N_Private_Type_Declaration
and then Has_Own_DIC (Defining_Entity (N)))
or else (Nkind (N) = N_Full_Type_Declaration
and then Has_Own_Invariants (Defining_Entity (N)));
-------------------------------
-- Process_Scope_Declaration --
-------------------------------
procedure Process_Scope_Declaration (N : Node_Id) is
Def_E : constant Entity_Id := Defining_Entity (N);
E : constant Entity_Id :=
(if Nkind (N) = N_Private_Type_Declaration
then DIC_Procedure (Def_E)
elsif Nkind (N) = N_Full_Type_Declaration
then Invariant_Procedure (Def_E)
else Def_E);
Info : constant Hierarchy_Info_T := Make_Info (N);
Spec_V, Priv_V, Body_V : Scope_Graphs.Vertex_Id;
-- Vertices for the visible (aka. "spec"), private and body parts
begin
if Is_Eliminated (E) then
-- ??? when returning early we don't need the Info constant
return;
end if;
-- ??? we don't need this info (except for debug?)
Hierarchy_Info.Insert (E, Info);
----------------------------------------------------------------------
-- Create vertices
----------------------------------------------------------------------
Scope_Graph.Add_Vertex ((Ent => E, Part => Visible_Part), Spec_V);
if Info.Is_Package then
Scope_Graph.Add_Vertex ((Ent => E, Part => Private_Part), Priv_V);
end if;
Scope_Graph.Add_Vertex ((Ent => E, Part => Body_Part), Body_V);
end Process_Scope_Declaration;
procedure Traverse is
new Traverse_Compilation_Unit (Process_Scope_Declaration);
-- Start of processing for Build_Graph
begin
if Unit_Node = Standard_Package_Node then
-- The Standard package is special: create vertices for its
-- visible and private parts and connect them. This package declares
-- no subprograms or abstract states, so we don't need a vertex for
-- its body part.
--
-- This is based on the Ada RM 10.1.1(1): "Each library unit (except
-- Standard) has a parent unit, which is a library package or generic
-- library package."
Scope_Graph.Add_Vertex
((Ent => Standard_Standard, Part => Visible_Part));
Scope_Graph.Add_Vertex
((Ent => Standard_Standard, Part => Private_Part));
Scope_Graph.Add_Edge
((Ent => Standard_Standard, Part => Private_Part),
(Ent => Standard_Standard, Part => Visible_Part),
Rule_Own);
else
Traverse (Unit_Node);
end if;
end Register_Flow_Scopes;
-------------------------------
-- Traverse_Compilation_Unit --
-------------------------------
procedure Traverse_Compilation_Unit (Unit_Node : Node_Id)
is
procedure Traverse_Declaration_Or_Statement (N : Node_Id);
procedure Traverse_Declarations_And_HSS (N : Node_Id);
procedure Traverse_Declarations_Or_Statements (L : List_Id);
procedure Traverse_Handled_Statement_Sequence (N : Node_Id);
procedure Traverse_Package_Body (N : Node_Id);
procedure Traverse_Visible_And_Private_Parts (N : Node_Id);
procedure Traverse_Protected_Body (N : Node_Id);
procedure Traverse_Subprogram_Body (N : Node_Id);
procedure Traverse_Task_Body (N : Node_Id);
-- Traverse corresponding construct, calling Process on all declarations
---------------------------------------
-- Traverse_Declaration_Or_Statement --
---------------------------------------
procedure Traverse_Declaration_Or_Statement (N : Node_Id) is
begin
-- Call Process on all interesting declarations and traverse
case Nkind (N) is
when N_Package_Declaration =>
Process (N);
Traverse_Visible_And_Private_Parts (Specification (N));
when N_Generic_Package_Declaration =>
Process (N);
when N_Package_Body =>
if Ekind (Unique_Defining_Entity (N)) /= E_Generic_Package then
Traverse_Package_Body (N);
end if;
when N_Package_Body_Stub =>
if Ekind (Unique_Defining_Entity (N)) /= E_Generic_Package then
Traverse_Package_Body (Get_Body_From_Stub (N));
end if;
when N_Entry_Declaration
| N_Generic_Subprogram_Declaration
| N_Subprogram_Declaration
| N_Abstract_Subprogram_Declaration
=>
-- ??? abstract subprograms have no bodies
Process (N);
when N_Subprogram_Body =>
if Acts_As_Spec (N) then
Process (N);
end if;
if not Is_Generic_Subprogram (Unique_Defining_Entity (N)) then
Traverse_Subprogram_Body (N);
end if;
when N_Entry_Body =>
Traverse_Subprogram_Body (N);
when N_Subprogram_Body_Stub =>
if Is_Subprogram_Stub_Without_Prior_Declaration (N) then
Process (N);
end if;
if not Is_Generic_Subprogram (Unique_Defining_Entity (N)) then
Traverse_Subprogram_Body (Get_Body_From_Stub (N));
end if;
when N_Protected_Body =>
Traverse_Protected_Body (N);
when N_Protected_Body_Stub =>
Traverse_Protected_Body (Get_Body_From_Stub (N));
when N_Protected_Type_Declaration =>
Process (N);
Traverse_Visible_And_Private_Parts (Protected_Definition (N));
when N_Task_Type_Declaration =>
Process (N);
-- Task type definition is optional (unlike protected type
-- definition, which is mandatory).
declare
Task_Def : constant Node_Id := Task_Definition (N);
begin
if Present (Task_Def) then
Traverse_Visible_And_Private_Parts (Task_Def);
end if;
end;
when N_Task_Body =>
Traverse_Task_Body (N);
when N_Task_Body_Stub =>
Traverse_Task_Body (Get_Body_From_Stub (N));
when N_Block_Statement =>
Traverse_Declarations_And_HSS (N);
when N_If_Statement =>
-- Traverse the statements in the THEN part
Traverse_Declarations_Or_Statements (Then_Statements (N));
-- Loop through ELSIF parts if present
if Present (Elsif_Parts (N)) then
declare
Elif : Node_Id := First (Elsif_Parts (N));
begin
while Present (Elif) loop
Traverse_Declarations_Or_Statements
(Then_Statements (Elif));
Next (Elif);
end loop;
end;
end if;
-- Finally traverse the ELSE statements if present
Traverse_Declarations_Or_Statements (Else_Statements (N));
when N_Case_Statement =>
-- Process case branches
declare
Alt : Node_Id := First (Alternatives (N));
begin
loop
Traverse_Declarations_Or_Statements (Statements (Alt));
Next (Alt);
exit when No (Alt);
end loop;
end;
when N_Extended_Return_Statement =>
Traverse_Handled_Statement_Sequence
(Handled_Statement_Sequence (N));
when N_Loop_Statement =>
Traverse_Declarations_Or_Statements (Statements (N));
when N_Private_Type_Declaration =>
-- Both private and full view declarations might be represented
-- by N_Private_Type_Declaration; the former comes from source,
-- the latter comes from rewriting.
if Comes_From_Source (N) then
declare
T : constant Entity_Id := Defining_Entity (N);
begin
if Has_Own_DIC (T)
and then Present (DIC_Procedure (T))
then
Process (N);
end if;
end;
end if;
when N_Full_Type_Declaration =>
declare
T : constant Entity_Id := Defining_Entity (N);
begin
-- For Type_Invariant'Class there will be no invariant
-- procedure; we ignore it, because this aspect is not
-- supported in SPARK anyway.
if Comes_From_Source (N)
and then Has_Own_Invariants (T)
and then Present (Invariant_Procedure (T))
then
Process (N);
end if;
end;
when others =>
null;
end case;
end Traverse_Declaration_Or_Statement;
-----------------------------------
-- Traverse_Declarations_And_HSS --
-----------------------------------
procedure Traverse_Declarations_And_HSS (N : Node_Id) is
begin
Traverse_Declarations_Or_Statements (Declarations (N));
Traverse_Handled_Statement_Sequence (Handled_Statement_Sequence (N));
end Traverse_Declarations_And_HSS;
-----------------------------------------
-- Traverse_Declarations_Or_Statements --
-----------------------------------------
procedure Traverse_Declarations_Or_Statements (L : List_Id) is
N : Node_Id := First (L);
begin
-- Loop through statements or declarations
while Present (N) loop
Traverse_Declaration_Or_Statement (N);
Next (N);
end loop;
end Traverse_Declarations_Or_Statements;
-----------------------------------------
-- Traverse_Handled_Statement_Sequence --
-----------------------------------------
procedure Traverse_Handled_Statement_Sequence (N : Node_Id) is
Handler : Node_Id;
begin
if Present (N) then
Traverse_Declarations_Or_Statements (Statements (N));
if Present (Exception_Handlers (N)) then
Handler := First (Exception_Handlers (N));
while Present (Handler) loop
Traverse_Declarations_Or_Statements (Statements (Handler));
Next (Handler);
end loop;
end if;
end if;
end Traverse_Handled_Statement_Sequence;
---------------------------
-- Traverse_Package_Body --
---------------------------
procedure Traverse_Package_Body (N : Node_Id) is
begin
Traverse_Declarations_Or_Statements (Declarations (N));
Traverse_Handled_Statement_Sequence (Handled_Statement_Sequence (N));
end Traverse_Package_Body;
-----------------------------
-- Traverse_Protected_Body --
-----------------------------
procedure Traverse_Protected_Body (N : Node_Id) is
begin
Traverse_Declarations_Or_Statements (Declarations (N));
end Traverse_Protected_Body;
------------------------------
-- Traverse_Subprogram_Body --
------------------------------
procedure Traverse_Subprogram_Body (N : Node_Id) renames
Traverse_Declarations_And_HSS;
------------------------
-- Traverse_Task_Body --
------------------------
procedure Traverse_Task_Body (N : Node_Id) renames
Traverse_Declarations_And_HSS;
----------------------------------------
-- Traverse_Visible_And_Private_Parts --
----------------------------------------
procedure Traverse_Visible_And_Private_Parts (N : Node_Id) is
begin
Traverse_Declarations_Or_Statements (Visible_Declarations (N));
Traverse_Declarations_Or_Statements (Private_Declarations (N));
end Traverse_Visible_And_Private_Parts;
-- Start of processing for Traverse_Compilation_Unit
begin
Traverse_Declaration_Or_Statement (Unit_Node);
end Traverse_Compilation_Unit;
-------------------------
-- Iterate_Flow_Scopes --
-------------------------
procedure Iterate_Flow_Scopes is
begin
for C in Hierarchy_Info.Iterate loop
Process (Hierarchy_Info_Maps.Key (C), Hierarchy_Info (C));
end loop;
-- Release data that is no longer needed
Hierarchy_Info.Clear;
Hierarchy_Info.Reserve_Capacity (0);
end Iterate_Flow_Scopes;
end Flow_Visibility;
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.